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
feat(board): keep the columns in the status attribute's definition
Elian Doran6c206efaac1d
diff --git a/apps/client/src/test/setup.ts b/apps/client/src/test/setup.tsindex 3e8c458918..37a351e91f 100644--- a/apps/client/src/test/setup.ts+++ b/apps/client/src/test/setup.ts@@ -72,7 +72,13 @@ function mockServer() {if (url === "tree/load") {throw new Error(`A module tried to load from the server the following notes: ${((data as any).noteIds || []).join(",")}\nThis is not supported, use Froca mocking instead and ensure the note exist in the mock.`);}- }+ },++ // Widgets that persist as the user edits (attribute writes, view configs) reach for+ // these; without them the write rejects and surfaces as an unhandled rejection rather+ // than as whatever the test was actually asserting.+ async put(_url: string, _data?: object) {},+ async remove(_url: string) {}}};}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 75a91725ca..34e657e975 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2936,7 +2936,8 @@"add-column-placeholder": "Enter column name...","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-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."},"dashboard_view": {"refresh-widget": "Refresh",diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex ef9dc0ca15..1562d5af62 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 } from "@triliumnext/commons";+import { BulkAction, promotedAttributeDefinitionParser } from "@triliumnext/commons";import appContext from "../../../components/app_context";import FNote from "../../../entities/fnote";@@ -9,7 +9,9 @@ import froca from "../../../services/froca";import { t } from "../../../services/i18n";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 { ColumnMap } from "./data";export default class BoardApi {@@ -24,7 +26,8 @@ export default class BoardApi {statusAttribute: string,private viewConfig: BoardViewData,private saveConfig: (newConfig: BoardViewData) => void,- private setBranchIdToEdit: (branchId: string | undefined) => void+ private setBranchIdToEdit: (branchId: string | undefined) => void,+ private statusDefinition?: BoardStatusDefinition) {this.isRelationMode = statusAttribute.startsWith("~");@@ -122,7 +125,8 @@ export default class BoardApi {}/**- * Persists a new column list.+ * 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.** 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@@ -131,6 +135,48 @@ export default class BoardApi {private storeColumns(columns: BoardColumnData[]) {this.viewConfig = { ...this.viewConfig, columns };this.saveConfig(this.viewConfig);+ // 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))+ .catch((e) => {+ console.error("Failed to store the board columns in the attribute definition:", e);+ toast.showError(t("board_view.column-definition-save-error"));+ });+ }++ /**+ * 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.+ *+ * 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.+ */+ private async storeColumnsInDefinition(options: string[]) {+ if (this.isRelationMode || !canStoreColumnsInDefinition(this.statusDefinition)) {+ return;+ }++ const definition = {+ ...this.statusDefinition?.definition,+ labelType: "select" as const,+ selectOptions: options+ };++ 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.+ attributeId: this.statusDefinition?.isOwned+ ? this.statusDefinition.attribute.attributeId+ : undefined,+ type: "label",+ name: `label:${this.statusAttribute}`,+ value: promotedAttributeDefinitionParser.serialize(definition, "label"),+ // A definition that is not inheritable would not reach the notes on the board at all.+ isInheritable: this.statusDefinition?.attribute.isInheritable ?? true+ });}async insertRowAtPosition(diff --git a/apps/client/src/widgets/collections/board/columns.spec.ts b/apps/client/src/widgets/collections/board/columns.spec.tsnew file mode 100644index 0000000000..9adf7f2650--- /dev/null+++ b/apps/client/src/widgets/collections/board/columns.spec.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from "vitest";++import FAttribute from "../../../entities/fattribute";+import type FNote from "../../../entities/fnote";+import froca from "../../../services/froca";+import noteAttributeCache from "../../../services/note_attribute_cache";+import { buildNote } from "../../../test/easy-froca";+import {+ BOARD_TEMPLATE_ID,+ canStoreColumnsInDefinition,+ getStatusDefinition,+ resolveBoardColumns+} from "./columns";++describe("resolveBoardColumns", () => {+ it("lets the definition lead, then the attachment, then the notes", () => {+ expect(resolveBoardColumns(+ [ "Todo", "Doing" ],+ [ "Doing", "Archived" ],+ [ "Todo", "Blocked" ]+ )).toEqual([ "Todo", "Doing", "Archived", "Blocked" ]);+ });++ it("keeps a column the definition no longer offers rather than dropping its notes", () => {+ expect(resolveBoardColumns([ "Todo" ], [], [ "Renamed away" ]))+ .toEqual([ "Todo", "Renamed away" ]);+ });++ it("falls back to the board's own two sources when nothing is defined", () => {+ expect(resolveBoardColumns([], [ "Todo" ], [ "Done" ])).toEqual([ "Todo", "Done" ]);+ });++ it("drops blanks and treats columns differing only in case as distinct", () => {+ expect(resolveBoardColumns([ "", " " ], [ " Todo " ], [ "todo" ]))+ .toEqual([ "Todo", "todo" ]);+ });+});++describe("getStatusDefinition", () => {+ it("finds the definition for the label, however the group-by names it", () => {+ const board = buildBoard({ "#label:status": "promoted,single,select,options=Todo;Done" });++ for (const groupBy of [ "status", "#status" ]) {+ const found = getStatusDefinition(board, groupBy);+ expect(found?.isOwned).toBe(true);+ expect(found?.options).toEqual([ "Todo", "Done" ]);+ }+ });++ it("offers no choices for a definition that is not a select", () => {+ const board = buildBoard({ "#label:status": "promoted,single,text" });++ const found = getStatusDefinition(board, "status");+ expect(found?.definition.labelType).toBe("text");+ expect(found?.options).toEqual([]);+ });++ it("marks a definition reached through the template as not the board's own", () => {+ const board = buildBoard({}, [+ { noteId: BOARD_TEMPLATE_ID, name: "label:status", value: "promoted,single,text" }+ ]);++ expect(getStatusDefinition(board, "status")).toMatchObject({+ isOwned: false,+ options: []+ });+ });++ it("has nothing to offer for a relation, or for a label nobody defined", () => {+ const board = buildBoard({ "#label:status": "promoted,single,select,options=Todo" });++ expect(getStatusDefinition(board, "~status")).toBeUndefined();+ expect(getStatusDefinition(board, "#")).toBeUndefined();+ expect(getStatusDefinition(board, "priority")).toBeUndefined();+ });+});++describe("canStoreColumnsInDefinition", () => {+ it("may create one where nothing defines the label yet", () => {+ expect(canStoreColumnsInDefinition(undefined)).toBe(true);+ });++ it.each([+ [ "its own", "boardNote", "promoted,single,text", true ],+ [ "the template's, which it may copy", BOARD_TEMPLATE_ID, "promoted,single,text", true ],+ [ "its own, already a select", "boardNote", "promoted,single,select,options=Todo", true ],+ [ "an ancestor's", "someAncestor", "promoted,single,text", false ],+ [ "typed as something else", "boardNote", "promoted,single,date", false ],+ [ "multi-valued", "boardNote", "promoted,multi,text", false ]+ ])("is %s: %s", (_label, ownerNoteId, value, expected) => {+ const board = buildBoard({}, [ { noteId: ownerNoteId, name: "label:status", value } ]);++ expect(canStoreColumnsInDefinition(getStatusDefinition(board, "status"))).toBe(expected);+ });+});++/**+ * 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/columns.ts b/apps/client/src/widgets/collections/board/columns.tsnew file mode 100644index 0000000000..6239fb1178--- /dev/null+++ b/apps/client/src/widgets/collections/board/columns.ts@@ -0,0 +1,112 @@+import { type DefinitionObject } from "@triliumnext/commons";++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.+ */+export const BOARD_TEMPLATE_ID = "_template_board";++export interface BoardStatusDefinition {+ /** The definition attribute, wherever it is owned. */+ attribute: FAttribute;+ definition: DefinitionObject;+ /** Whether the board itself owns it, and so may have its columns written straight into it. */+ isOwned: boolean;+ /** The choices it offers, empty unless it declares a select. */+ options: string[];+}++/**+ * The definition the board groups by, or `undefined` when it groups by something no definition+ * describes — a relation, or a plain label nobody ever defined.+ *+ * @param parentNote the board note.+ * @param groupBy the value of `#board:groupBy`, with the `#`/`~` prefix it may carry.+ */+export function getStatusDefinition(parentNote: FNote, groupBy: string): BoardStatusDefinition | undefined {+ if (groupBy.startsWith("~")) {+ return undefined;+ }++ const name = groupBy.replace(/^#/, "").trim();+ if (!name) {+ return undefined;+ }++ // Nearest-wins, so a board that owns a definition is described by its own rather than by the+ // template's (see FNote#getAttributeDefinitions).+ const attribute = parentNote.getAttributeDefinitions()+ .find((attr) => attr.name === `label:${name}`);+ if (!attribute) {+ return undefined;+ }++ const definition = attribute.getDefinition();+ return {+ attribute,+ definition,+ isOwned: attribute.noteId === parentNote.noteId,+ options: definition.labelType === "select" ? (definition.selectOptions ?? []) : []+ };+}++/**+ * Whether the board may keep its columns in the definition, creating one or taking a copy of the+ * template's where it has none of its own.+ *+ * A definition owned by an ancestor, or by a template the user shares between notes, describes more+ * 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.+ */+export function canStoreColumnsInDefinition(statusDefinition: BoardStatusDefinition | undefined): boolean {+ if (!statusDefinition) {+ // Nothing defines the label yet, so a definition the board creates is its own.+ return true;+ }++ const { attribute, definition, isOwned } = statusDefinition;+ if (!isOwned && attribute.noteId !== BOARD_TEMPLATE_ID) {+ return false;+ }+ if (definition.multiplicity === "multi") {+ return false;+ }++ // `undefined` is the parser's way of saying the type token was absent, which means text.+ return !definition.labelType+ || definition.labelType === "text"+ || definition.labelType === "select";+}++/**+ * The columns to show, from the choices the definition offers, the columns the board persisted, and+ * the values its notes actually carry.+ *+ * The definition leads because it is the shared answer — the same list the promoted field and the+ * table view offer — and the other two follow so that a column can never disappear: one the board+ * 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.+ */+export function resolveBoardColumns(+ definitionOptions: string[],+ persistedColumns: string[],+ discoveredValues: string[]+): string[] {+ const columns: string[] = [];+ const seen = new Set<string>();++ for (const candidate of [ ...definitionOptions, ...persistedColumns, ...discoveredValues ]) {+ const value = candidate.trim();+ if (!value || seen.has(value)) continue;+ seen.add(value);+ columns.push(value);+ }++ return columns;+}diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex a37487ec90..3134bc567e 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -1,5 +1,6 @@import FBranch from "../../../entities/fbranch";import FNote from "../../../entities/fnote";+import { resolveBoardColumns } from "./columns";import { BoardViewData } from "./index";export type ColumnMap = Map<string, {@@ -7,57 +8,44 @@ export type ColumnMap = Map<string, {note: FNote;}[]>;-export async function getBoardData(parentNote: FNote, groupByColumn: string, persistedData: BoardViewData, includeArchived: boolean) {+/**+ * @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.+ */+export async function getBoardData(+ parentNote: FNote,+ groupByColumn: string,+ persistedData: BoardViewData,+ includeArchived: boolean,+ definitionOptions: string[] = []+) {const byColumn: ColumnMap = new Map();// First, scan all notes to find what columns actually existawait recursiveGroupBy(parentNote.getChildBranches(), byColumn, groupByColumn, includeArchived, new Set<string>());- // Get all columns that exist in the notes- const columnsFromNotes = [...byColumn.keys()];+ const persistedColumns = (persistedData.columns ?? []).map(c => c.value);+ const columns = resolveBoardColumns(definitionOptions, persistedColumns, [ ...byColumn.keys() ]);- // Get existing persisted columns and preserve their order- const existingPersistedColumns = persistedData.columns || [];- const existingColumnValues = existingPersistedColumns.map(c => c.value);-- // Find truly new columns (exist in notes but not in persisted data)- const newColumnValues = columnsFromNotes.filter(col => !existingColumnValues.includes(col));-- // Build the complete correct column list: existing + new- const allColumns = [- ...existingPersistedColumns, // Preserve existing order- ...newColumnValues.map(value => ({ value })) // Add new columns- ];-- // Remove duplicates (just in case) and ensure we only keep columns that exist in notes or are explicitly preserved- const deduplicatedColumns = allColumns.filter((column, index) => {- const firstIndex = allColumns.findIndex(c => c.value === column.value);- return firstIndex === index; // Keep only the first occurrence- });-- // Ensure all persisted columns have empty arrays in byColumn (even if no notes use them)- for (const column of deduplicatedColumns) {- if (!byColumn.has(column.value)) {- byColumn.set(column.value, []);+ // A column the notes have nothing in is still a column, so every resolved one gets an entry.+ for (const column of columns) {+ if (!byColumn.has(column)) {+ byColumn.set(column, []);}}- // Return updated persisted data only if there were changes- let newPersistedData: BoardViewData | undefined;- const hasChanges = newColumnValues.length > 0 ||- existingPersistedColumns.length !== deduplicatedColumns.length ||- !existingPersistedColumns.every((col, idx) => deduplicatedColumns[idx]?.value === col.value);-- if (hasChanges) {- newPersistedData = {- ...persistedData,- columns: deduplicatedColumns- };- }+ // The attachment mirrors the resolved list, so a board whose columns now come from its definition+ // stays readable by anything still reading the attachment. Written only when it actually differs,+ // or every refresh would save.+ const hasChanges = persistedColumns.length !== columns.length+ || persistedColumns.some((value, index) => columns[index] !== value);return {byColumn,- newPersistedData,+ columns,+ newPersistedData: hasChanges+ ? { ...persistedData, columns: columns.map(value => ({ value })) }+ : undefined,isInRelationMode: groupByColumn.startsWith("~")};}diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex f687d9468a..a7c15dfc3c 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -17,6 +17,7 @@ import { onWheelHorizontalScroll } from "../../widget_utils";import { ViewModeProps } from "../interface";import Api from "./api";import BoardApi from "./api";+import { getStatusDefinition } from "./columns";import Column from "./column";import { ColumnMap, getBoardData } from "./data";@@ -61,9 +62,14 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCconst [ columnHoverIndex, setColumnHoverIndex ] = useState<number | null>(null);const [ branchIdToEdit, setBranchIdToEdit ] = useState<string>();const [ 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);+ const statusDefinition = useMemo(+ () => getStatusDefinition(parentNote, statusAttributeWithPrefix),+ [ parentNote, statusAttributeWithPrefix, definitionRevision ]);const api = useMemo(() => {- return new Api(byColumn, columns ?? [], parentNote, statusAttributeWithPrefix, viewConfig ?? {}, saveConfig, setBranchIdToEdit );- }, [ byColumn, columns, parentNote, statusAttributeWithPrefix, viewConfig, saveConfig, setBranchIdToEdit ]);+ return new Api(byColumn, columns ?? [], parentNote, statusAttributeWithPrefix, viewConfig ?? {}, saveConfig, setBranchIdToEdit, statusDefinition );+ }, [ byColumn, columns, parentNote, statusAttributeWithPrefix, viewConfig, saveConfig, setBranchIdToEdit, statusDefinition ]);const boardViewContext = useMemo<BoardViewContextData>(() => ({api,parentNote,@@ -85,24 +91,20 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC]);function refresh() {- getBoardData(parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived).then(({ byColumn, newPersistedData, isInRelationMode }) => {- setByColumn(byColumn);- setIsRelationMode(isInRelationMode);-- if (newPersistedData) {- viewConfig = { ...newPersistedData };- saveConfig(newPersistedData);- }-- // Use the order from persistedData.columns, then add any new columns found- const orderedColumns = viewConfig?.columns?.map(col => col.value) || [];- const allColumns = Array.from(byColumn.keys());- const newColumns = allColumns.filter(col => !orderedColumns.includes(col));- setColumns([...orderedColumns, ...newColumns]);- });+ getBoardData(parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived, statusDefinition?.options ?? [])+ .then(({ byColumn, columns, newPersistedData, isInRelationMode }) => {+ setByColumn(byColumn);+ setIsRelationMode(isInRelationMode);+ setColumns(columns);++ if (newPersistedData) {+ viewConfig = { ...newPersistedData };+ saveConfig(newPersistedData);+ }+ });}- useEffect(refresh, [ parentNote, noteIds, viewConfig, statusAttributeWithPrefix ]);+ useEffect(refresh, [ parentNote, noteIds, viewConfig, statusAttributeWithPrefix, statusDefinition ]);const handleColumnDrop = useCallback((fromIndex: number, toIndex: number) => {const newColumns = api.reorderColumn(fromIndex, toIndex);@@ -115,6 +117,12 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC}, [api]);useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ // The column list is read off the definition, which may be edited from the attribute panel,+ // another split, or a synced instance. Re-reading it re-runs the refresh through the effect.+ if (loadResults.getAttributeRows().some(attr => attr.name === `label:${api.statusAttribute}`)) {+ setDefinitionRevision(revision => revision + 1);+ }+// Check if any changes affect our boardconst hasRelevantChanges =// React to changes in status attribute for notes in this boarddiff --git a/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.spec.ts b/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.spec.tsnew file mode 100644index 0000000000..0f35a03976--- /dev/null+++ b/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.spec.ts@@ -0,0 +1,538 @@+import { readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { promotedAttributeDefinitionParser } from "@triliumnext/commons";+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../becca/becca.js";+import becca_loader from "../becca/becca_loader.js";+import BAttribute from "../becca/entities/battribute.js";+import BBranch from "../becca/entities/bbranch.js";+import BNote from "../becca/entities/bnote.js";+import * as cls from "../services/context.js";+import { getSql } from "../services/sql/index.js";+import migration, {+ type BoardMigrationInput,+ BOARD_TEMPLATE_ID,+ deriveDefinitionAttributeId,+ parseBoardColumns,+ planBoardMigration,+ resolveStatusColumns+} from "./0240__migrate_board_status_to_select.js";++// Resolve the fixture relative to this spec. Spec files only ever run under vitest (ESM via Vite),+// so import.meta.url is available; the CLAUDE.md restriction applies to production code bundled to+// CJS, not to tests.+const __dirname = dirname(fileURLToPath(import.meta.url));++describe("Migration 0240: board status becomes a select", () => {++ describe("resolveStatusColumns", () => {+ it("keeps the persisted order, appends what only the notes know, and drops blanks and repeats", () => {+ expect(resolveStatusColumns(+ [ "Todo", "Doing", " Done " ],+ [ "Doing", "Blocked", "", " ", "Todo", "Archived" ]+ )).toEqual([ "Todo", "Doing", "Done", "Blocked", "Archived" ]);+ });++ it("treats columns differing only in case as distinct, as the board view does", () => {+ expect(resolveStatusColumns([ "todo" ], [ "Todo" ])).toEqual([ "todo", "Todo" ]);+ });++ it("returns nothing when there is nothing to offer", () => {+ expect(resolveStatusColumns([], [])).toEqual([]);+ expect(resolveStatusColumns([ "", " " ], [ "" ])).toEqual([]);+ });+ });++ describe("parseBoardColumns", () => {+ it("reads the column values in order", () => {+ const content = JSON.stringify({ columns: [ { value: "Todo" }, { value: "Done" } ] });+ expect(parseBoardColumns(content)).toEqual([ "Todo", "Done" ]);+ });++ it("contributes nothing rather than throwing for content that is not a column list", () => {+ expect(parseBoardColumns("")).toEqual([]);+ expect(parseBoardColumns(" ")).toEqual([]);+ expect(parseBoardColumns("{ not json")).toEqual([]);+ expect(parseBoardColumns("null")).toEqual([]);+ expect(parseBoardColumns(JSON.stringify({}))).toEqual([]);+ expect(parseBoardColumns(JSON.stringify({ columns: "Todo" }))).toEqual([]);+ });++ it("skips entries that carry no string value", () => {+ const content = JSON.stringify({ columns: [ { value: "Todo" }, {}, null, { value: 7 }, { value: "Done" } ] });+ expect(parseBoardColumns(content)).toEqual([ "Todo", "Done" ]);+ });+ });++ describe("deriveDefinitionAttributeId", () => {+ it("is stable for a note, and different per note and per definition", () => {+ const id = deriveDefinitionAttributeId("boardNote1", "label:status");++ expect(id).toBe(deriveDefinitionAttributeId("boardNote1", "label:status"));+ expect(id).toHaveLength(12);+ expect(id).not.toBe(deriveDefinitionAttributeId("boardNote2", "label:status"));+ expect(id).not.toBe(deriveDefinitionAttributeId("boardNote1", "label:priority"));+ });+ });++ describe("planBoardMigration", () => {+ function input(overrides: Partial<BoardMigrationInput> = {}): BoardMigrationInput {+ return {+ noteId: "boardNote1",+ name: "status",+ isSystemNote: false,+ isProtected: false,+ isRelationMode: false,+ isSearchNote: false,+ persistedColumns: [ "Todo", "Done" ],+ discoveredValues: [],+ ...overrides+ };+ }++ function templateDefinition(value = "promoted,alias=Status,single,text") {+ return {+ attributeId: "_template_board_llabel:status",+ ownerNoteId: BOARD_TEMPLATE_ID,+ isInheritable: true,+ definition: promotedAttributeDefinitionParser.parse(value)+ };+ }++ it("copies the template's definition onto the board as a select, keeping alias and promotion", () => {+ const plan = planBoardMigration(input({ existingDefinition: templateDefinition() }));++ expect(plan).toMatchObject({+ action: "write",+ noteId: "boardNote1",+ name: "label:status",+ isInheritable: true,+ optionCount: 2,+ // Written under a derived id, not the template's.+ attributeId: deriveDefinitionAttributeId("boardNote1", "label:status")+ });++ const written = promotedAttributeDefinitionParser.parse(+ plan.action === "write" ? plan.value : "");+ expect(written).toEqual({+ isPromoted: true,+ promotedAlias: "Status",+ multiplicity: "single",+ labelType: "select",+ selectOptions: [ "Todo", "Done" ]+ });+ });++ it("does not make a field appear where the board never had a definition", () => {+ const plan = planBoardMigration(input());++ expect(plan.action).toBe("write");+ const written = promotedAttributeDefinitionParser.parse(+ plan.action === "write" ? plan.value : "");+ expect(written.isPromoted).toBeUndefined();+ expect(written.labelType).toBe("select");+ // Still inheritable, or it would not reach the notes on the board.+ expect(plan).toMatchObject({ isInheritable: true });+ });++ it("updates a definition the board already owns in place, reusing its id", () => {+ const plan = planBoardMigration(input({+ existingDefinition: {+ attributeId: "ownedAttr1",+ ownerNoteId: "boardNote1",+ isInheritable: false,+ definition: promotedAttributeDefinitionParser.parse("promoted,single,text")+ }+ }));++ expect(plan).toMatchObject({+ action: "write",+ attributeId: "ownedAttr1",+ isInheritable: false+ });+ });++ it("names the board's own group-by label rather than assuming status", () => {+ const plan = planBoardMigration(input({ name: "stage" }));+ expect(plan).toMatchObject({ action: "write", name: "label:stage" });+ });++ it("seeds the options from both the attachment and the notes", () => {+ const plan = planBoardMigration(input({+ persistedColumns: [ "Todo" ],+ discoveredValues: [ "Todo", "Blocked" ]+ }));++ expect(plan.action === "write" && promotedAttributeDefinitionParser.parse(plan.value).selectOptions)+ .toEqual([ "Todo", "Blocked" ]);+ });++ it.each([+ [ "system-note", { isSystemNote: true } ],+ [ "protected", { isProtected: true } ],+ [ "relation-mode", { isRelationMode: true } ],+ [ "search-note", { isSearchNote: true } ],+ [ "no-group-by", { name: "" } ],+ [ "no-columns", { persistedColumns: [], discoveredValues: [] } ]+ ])("leaves the board alone when it is %s", (reason, overrides) => {+ expect(planBoardMigration(input(overrides))).toEqual({ action: "skip", reason });+ });++ it.each([+ [ "already-select", "promoted,single,select,options=Todo;Done" ],+ [ "incompatible-type", "promoted,single,date" ],+ [ "multi-value", "promoted,multi,text" ]+ ])("leaves the board alone when the definition is %s", (reason, value) => {+ expect(planBoardMigration(input({ existingDefinition: templateDefinition(value) })))+ .toEqual({ action: "skip", reason });+ });++ it("leaves the board alone when the definition is owned beyond it", () => {+ expect(planBoardMigration(input({+ existingDefinition: { ...templateDefinition(), ownerNoteId: "someAncestor" }+ }))).toEqual({ action: "skip", reason: "foreign-definition" });+ });++ it("is checked in an order that never reads what a protected board would deny", () => {+ // Protection wins over everything else that would otherwise decide the outcome.+ expect(planBoardMigration(input({+ isProtected: true,+ persistedColumns: [],+ discoveredValues: [],+ existingDefinition: templateDefinition("promoted,single,select,options=A")+ }))).toEqual({ action: "skip", reason: "protected" });+ });+ });++ describe("running against a document", () => {+ let sql: ReturnType<typeof getSql>;++ beforeEach(async () => {+ // Resolved here rather than at describe-collection time so that initializeCore() in the+ // setup's beforeAll has run: describe callbacks fire before any beforeAll.+ sql = getSql();+ sql.rebuildFromBuffer(readFileSync(join(__dirname, "../test/fixtures/document.db")));++ await inContext(() => becca_loader.load());+ });++ it("gives a template-created board its own select definition, seeded from both sources", async () => {+ await inContext(() => {+ buildBoard({+ noteId: "boardTemplated",+ templateNoteId: BOARD_TEMPLATE_ID,+ columns: [ "Todo", "In Progress" ],+ children: [+ { noteId: "cardA", status: "Todo" },+ { noteId: "cardB", status: "Blocked" }+ ]+ });+ });++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ const definition = ownedDefinition("boardTemplated", "label:status");+ expect(definition).toBeTruthy();+ expect(definition?.isInheritable).toBe(true);+ expect(definition?.attributeId).toBe(deriveDefinitionAttributeId("boardTemplated", "label:status"));+ expect(definition?.getDefinition()).toEqual({+ isPromoted: true,+ promotedAlias: "Status",+ multiplicity: "single",+ labelType: "select",+ // "Blocked" exists only on a note; "In Progress" only in the attachment.+ selectOptions: [ "Todo", "In Progress", "Blocked" ]+ });++ // The attachment is left as it was, so an older client still reads its columns.+ expect(persistedColumnsOf("boardTemplated")).toEqual([ "Todo", "In Progress" ]);+ });+ });++ it("upgrades a definition the board already owns without adding a second one", async () => {+ await inContext(() => {+ const board = buildBoard({+ noteId: "boardOwning",+ columns: [ "Todo", "Done" ],+ children: [ { noteId: "cardOwning", status: "Todo" } ]+ });+ board.addLabel("label:status", "promoted,alias=State,single,text", true);+ });++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ const definitions = becca.getNoteOrThrow("boardOwning").getOwnedAttributes()+ .filter((attr) => attr.name === "label:status");+ expect(definitions).toHaveLength(1);+ expect(definitions[0].getDefinition()).toEqual({+ isPromoted: true,+ promotedAlias: "State",+ multiplicity: "single",+ labelType: "select",+ selectOptions: [ "Todo", "Done" ]+ });+ // Updated where it stood, rather than written under a derived id.+ expect(definitions[0].attributeId)+ .not.toBe(deriveDefinitionAttributeId("boardOwning", "label:status"));+ });+ });++ it("contributes no columns when the attachment's content cannot be read", async () => {+ await inContext(() => {+ buildBoard({+ noteId: "boardBrokenAttachment",+ columns: [ "Todo", "Done" ],+ children: [ { noteId: "cardBroken", status: "Doing" } ]+ });+ });++ // A board.json whose blob has gone missing throws on read; the values on the notes must+ // still get the board its columns.+ await inContext(() => {+ const attachment = becca.getNoteOrThrow("boardBrokenAttachment")+ .getAttachmentsByRole("viewConfig")[0];+ sql.execute("DELETE FROM blobs WHERE blobId = ?", [ attachment.blobId ]);+ });++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ expect(ownedDefinition("boardBrokenAttachment", "label:status")?.getDefinition().selectOptions)+ .toEqual([ "Doing" ]);+ });+ });++ it("reads the values of grandchildren and archived notes, and honours #board:groupBy", async () => {+ await inContext(() => {+ const board = buildBoard({+ noteId: "boardNested",+ columns: [],+ children: [+ { noteId: "parentCard", status: "Doing", labelName: "stage" },+ // A note that is on the board but has not been filed yet.+ { noteId: "unfiledCard", status: "", labelName: "stage" }+ ]+ });+ board.addLabel("board:groupBy", "#stage");++ const grandchild = buildNote("grandchildCard");+ new BBranch({ noteId: grandchild.noteId, parentNoteId: "parentCard" }).save();+ grandchild.addLabel("stage", "Shipped");++ const archived = buildNote("archivedCard");+ new BBranch({ noteId: archived.noteId, parentNoteId: "boardNested" }).save();+ archived.addLabel("stage", "Cancelled");+ archived.addLabel("archived");+ });++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ const definition = ownedDefinition("boardNested", "label:stage");+ expect(definition?.getDefinition().selectOptions)+ .toEqual([ "Doing", "Shipped", "Cancelled" ]);+ // The board had no definition of its own, so no field is introduced.+ expect(definition?.getDefinition().isPromoted).toBeUndefined();+ });+ });++ it("writes the same row when run twice, and leaves an already-migrated board untouched", async () => {+ await inContext(() => {+ buildBoard({+ noteId: "boardTwice",+ templateNoteId: BOARD_TEMPLATE_ID,+ columns: [ "Todo" ],+ children: [ { noteId: "cardTwice", status: "Todo" } ]+ });+ });++ await inContext(() => migration());+ await inContext(() => becca_loader.load());+ const firstValue = await inContext(() => ownedDefinition("boardTwice", "label:status")?.value);++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ const definitions = becca.getNoteOrThrow("boardTwice").getOwnedAttributes()+ .filter((attr) => attr.name === "label:status");+ expect(definitions).toHaveLength(1);+ expect(definitions[0].value).toBe(firstValue);+ });+ });++ it("leaves the board template, and every other note, without an options list of its own", async () => {+ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ const templateDefinition = becca.getNoteOrThrow(BOARD_TEMPLATE_ID)+ .getOwnedAttributes()+ .filter((attr) => attr.name === "label:status");+ expect(templateDefinition).toHaveLength(1);+ expect(templateDefinition[0].value).toBe("promoted,alias=Status,single,text");+ });+ });++ it.each([+ [ "protected", (board: BNote) => {+ // Flipping the flag through the entity would re-save the title encrypted, which+ // needs a data key; the column is where becca reads the flag from anyway.+ sql.execute("UPDATE notes SET isProtected = 1 WHERE noteId = ?", [ board.noteId ]);+ } ],+ [ "relation-mode", (board: BNote) => { board.addLabel("board:groupBy", "~status"); } ],+ [ "already a select", (board: BNote) => {+ board.addLabel("label:status", "promoted,single,select,options=Todo", true);+ } ],+ [ "typed as something else", (board: BNote) => {+ board.addLabel("label:status", "promoted,single,date", true);+ } ],+ [ "multi-valued", (board: BNote) => {+ board.addLabel("label:status", "promoted,multi,text", true);+ } ]+ ])("does not add a definition to a board that is %s", async (_name, configure) => {+ await inContext(() => {+ const board = buildBoard({+ noteId: "boardSkipped",+ columns: [ "Todo", "Done" ],+ children: [ { noteId: "cardSkipped", status: "Todo" } ]+ });+ configure(board);+ });+ // Picks up anything the configuration wrote straight to the database.+ await inContext(() => becca_loader.load());++ const before = await inContext(() =>+ becca.getNoteOrThrow("boardSkipped").getOwnedAttributes()+ .filter((attr) => attr.name === "label:status")+ .map((attr) => attr.value));++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ expect(becca.getNoteOrThrow("boardSkipped").getOwnedAttributes()+ .filter((attr) => attr.name === "label:status")+ .map((attr) => attr.value)).toEqual(before);+ });+ });++ it("does not touch a board whose definition comes from an ancestor", async () => {+ await inContext(() => {+ const ancestor = buildNote("statusAncestor");+ new BBranch({ noteId: ancestor.noteId, parentNoteId: "root" }).save();+ ancestor.addLabel("label:status", "promoted,single,text", true);++ const board = buildBoard({+ noteId: "boardBelowAncestor",+ parentNoteId: "statusAncestor",+ columns: [ "Todo" ],+ children: [ { noteId: "cardBelowAncestor", status: "Todo" } ]+ });+ expect(board.getLabelValue("viewType")).toBe("board");+ });++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ expect(ownedDefinition("boardBelowAncestor", "label:status")).toBeUndefined();+ });+ });++ it("does not touch notes that are not boards", async () => {+ await inContext(() => {+ const note = buildNote("plainNote");+ new BBranch({ noteId: note.noteId, parentNoteId: "root" }).save();+ note.addLabel("status", "Todo");+ });++ await inContext(() => migration());+ await inContext(() => becca_loader.load());++ await inContext(() => {+ expect(becca.getNoteOrThrow("plainNote").getOwnedAttributes()+ .some((attr) => attr.isDefinition())).toBe(false);+ });+ });+ });+});++/** Runs `fn` inside a CLS context, which entity writes and becca loads both require. */+function inContext<T>(fn: () => T): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ cls.getContext().init(() => {+ try {+ resolve(fn());+ } catch (e) {+ reject(e);+ }+ });+ });+}++function buildNote(noteId: string, type: "text" | "book" | "search" = "text") {+ return new BNote({+ noteId,+ title: noteId,+ type,+ mime: type === "text" ? "text/html" : "",+ isProtected: false,+ blobId: ""+ }).save();+}++function buildBoard({ noteId, parentNoteId = "root", templateNoteId, columns, children = [] }: {+ noteId: string;+ parentNoteId?: string;+ templateNoteId?: string;+ columns: string[];+ children?: { noteId: string; status: string; labelName?: string }[];+}) {+ const board = buildNote(noteId, "book");+ new BBranch({ noteId, parentNoteId }).save();++ if (templateNoteId) {+ board.addRelation("template", templateNoteId);+ } else {+ board.addLabel("viewType", "board");+ }++ if (columns.length) {+ board.saveAttachment({+ role: "viewConfig",+ title: "board.json",+ mime: "application/json",+ content: JSON.stringify({ columns: columns.map((value) => ({ value })) }),+ position: 0+ });+ }++ for (const { noteId: childNoteId, status, labelName } of children) {+ const child = buildNote(childNoteId);+ new BBranch({ noteId: childNoteId, parentNoteId: noteId }).save();+ child.addLabel(labelName ?? "status", status);+ }++ return board;+}++function ownedDefinition(noteId: string, definitionName: string): BAttribute | undefined {+ return becca.getNoteOrThrow(noteId).getOwnedAttributes()+ .find((attr) => attr.name === definitionName);+}++function persistedColumnsOf(noteId: string): string[] {+ const attachment = becca.getNoteOrThrow(noteId).getAttachmentsByRole("viewConfig")+ .find((candidate) => candidate.title === "board.json");+ return attachment ? parseBoardColumns(attachment.getContent() as unknown as string) : [];+}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.tsnew file mode 100644index 0000000000..61c727648f--- /dev/null+++ b/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.ts@@ -0,0 +1,351 @@+import { type DefinitionObject, promotedAttributeDefinitionParser } from "@triliumnext/commons";++import becca from "../becca/becca";+import becca_loader from "../becca/becca_loader";+import BAttribute from "../becca/entities/battribute";+import type BNote from "../becca/entities/bnote";+import { getContext } from "../services/context";+import { md5 } from "../services/utils/index";+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.+ *+ * 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.+ */+export default () => {+ getContext().init(() => {+ becca_loader.load();++ for (const note of Object.values(becca.notes)) {+ if (note.getLabelValue("viewType") !== "board") {+ continue;+ }++ const plan = planBoardMigration(collectBoardInput(note));+ if (plan.action === "skip") {+ console.log(`Leaving board '${note.noteId}' as it is: ${plan.reason}.`);+ continue;+ }++ console.log(`Migrating board '${note.noteId}': '${plan.name}' becomes a select of ${plan.optionCount} option(s).`);+ writeDefinition(plan);+ }+ });+};++/** The label a board groups by when it does not name one itself, mirroring the board view's default. */+export const DEFAULT_GROUP_BY = "status";++/** The definition a template-created board inherits is owned by this note, and only by this note. */+export const BOARD_TEMPLATE_ID = "_template_board";++const VIEW_CONFIG_ROLE = "viewConfig";+const BOARD_VIEW_CONFIG_TITLE = "board.json";++/** Why a board was left alone, logged so a support question can be answered from the startup log. */+export type SkipReason =+ /** A hidden-subtree note — `_template_board` is itself a board, and is the one that must not own options. */+ | "system-note"+ /** The columns live in an encrypted attachment, which a migration has no key for. */+ | "protected"+ /** The columns are target notes, which a label definition cannot describe. */+ | "relation-mode"+ /** A search board's results are not its subtree, so an inheritable definition would not reach them. */+ | "search-note"+ /** `#board:groupBy` is set to an empty value. */+ | "no-group-by"+ /** Already migrated — the board owns a select definition. */+ | "already-select"+ /** The definition says the values are dates, numbers, … — the board groups by something typed. */+ | "incompatible-type"+ /** A note may hold several values at once, which a single-choice column list cannot express. */+ | "multi-value"+ /** The definition is owned by an ancestor or a template shared beyond this board. */+ | "foreign-definition"+ /** Nothing to offer: no columns are persisted and no note carries the label. */+ | "no-columns";++export interface ExistingDefinition {+ attributeId: string;+ /** Which note carries the definition — the board itself, a template, or an ancestor. */+ ownerNoteId: string;+ isInheritable: boolean;+ definition: DefinitionObject;+}++export interface BoardMigrationInput {+ noteId: string;+ /** The label name to group by, without the `#` prefix it may have been written with. */+ name: string;+ /** Whether the note belongs to the hidden subtree, whose ids are all prefixed with `_`. */+ isSystemNote: boolean;+ isProtected: boolean;+ isRelationMode: boolean;+ isSearchNote: boolean;+ /** The definition the board can already see for {@link name}, wherever it is owned. */+ existingDefinition?: ExistingDefinition;+ /** The columns held in `board.json`, in the order the board shows them. */+ persistedColumns: string[];+ /** The values the board's descendants actually carry, in tree order. */+ discoveredValues: string[];+}++export type BoardMigrationPlan =+ | { action: "skip"; reason: SkipReason }+ | {+ action: "write";+ /** Reused when the board already owns the definition, derived otherwise. */+ attributeId: string;+ noteId: string;+ /** The full definition attribute name, e.g. `label:status`. */+ name: string;+ value: string;+ isInheritable: boolean;+ /** Only for the log line — the value already carries the options. */+ optionCount: number;+ };++/**+ * Decides what a single board needs, from plain data only, so the whole decision table can be+ * exercised without a database.+ *+ * The definition that is written keeps everything the existing one said — its alias, and whether it+ * was promoted — and only changes the type to `select` and attaches the options. A board with no+ * definition at all gets one that is *not* promoted: it never showed a Status field on its notes,+ * and gaining the column must not also make one appear.+ */+export function planBoardMigration(input: BoardMigrationInput): BoardMigrationPlan {+ if (input.isSystemNote) return { action: "skip", reason: "system-note" };+ if (input.isProtected) return { action: "skip", reason: "protected" };+ if (input.isRelationMode) return { action: "skip", reason: "relation-mode" };+ if (input.isSearchNote) return { action: "skip", reason: "search-note" };+ if (!input.name) return { action: "skip", reason: "no-group-by" };++ const existing = input.existingDefinition;+ const isOwnedByBoard = existing?.ownerNoteId === input.noteId;++ if (existing) {+ // An ancestor's definition, or a user template shared with other notes, describes more than+ // this board; a copy here would shadow nothing and merely duplicate the field.+ if (!isOwnedByBoard && existing.ownerNoteId !== BOARD_TEMPLATE_ID) {+ return { action: "skip", reason: "foreign-definition" };+ }+ if (existing.definition.labelType === "select") {+ return { action: "skip", reason: "already-select" };+ }+ // `undefined` is the parser's way of saying the type token was absent, which means text.+ if (existing.definition.labelType && existing.definition.labelType !== "text") {+ return { action: "skip", reason: "incompatible-type" };+ }+ if (existing.definition.multiplicity === "multi") {+ return { action: "skip", reason: "multi-value" };+ }+ }++ const options = resolveStatusColumns(input.persistedColumns, input.discoveredValues);+ if (!options.length) {+ return { action: "skip", reason: "no-columns" };+ }++ const name = `label:${input.name}`;+ return {+ action: "write",+ // Reusing the id when the board owns the definition updates it in place; otherwise the id is+ // derived so that every instance migrating this document writes the same row (see+ // deriveDefinitionAttributeId).+ attributeId: isOwnedByBoard && existing+ ? existing.attributeId+ : deriveDefinitionAttributeId(input.noteId, name),+ noteId: input.noteId,+ name,+ value: promotedAttributeDefinitionParser.serialize({+ ...existing?.definition,+ labelType: "select",+ selectOptions: options+ }, "label"),+ // The template's definition is inheritable, and a definition that is not would not reach the+ // notes on the board at all.+ isInheritable: existing?.isInheritable ?? true,+ optionCount: options.length+ };+}++/**+ * The options to offer, from the columns the board persisted and the values its notes actually carry.+ *+ * Persisted columns come first and in their stored order — that is the order the user arranged — and+ * anything only a note knows about is appended, so a column can never be lost by migrating. Blank+ * entries are dropped (the board has no blank column) and the comparison is exact, since two columns+ * differing only in case are two columns to the board view as well.+ */+export function resolveStatusColumns(persistedColumns: string[], discoveredValues: string[]): string[] {+ const options: string[] = [];+ const seen = new Set<string>();++ for (const candidate of [ ...persistedColumns, ...discoveredValues ]) {+ const value = candidate.trim();+ if (!value || seen.has(value)) continue;+ seen.add(value);+ options.push(value);+ }++ return options;+}++/**+ * Reads the column list out of a `board.json` attachment, tolerating anything that is not one.+ *+ * The attachment is written by the client and may predate the current shape, be truncated, or have+ * been edited by hand; none of that is worth failing a migration over, and an unreadable attachment+ * simply contributes no columns — the values on the notes still do.+ */+export function parseBoardColumns(content: string): string[] {+ if (!content.trim()) {+ return [];+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(content);+ } catch {+ return [];+ }++ const columns = (parsed as { columns?: unknown } | null)?.columns;+ if (!Array.isArray(columns)) {+ return [];+ }++ return columns+ .map((column) => (column as { value?: unknown } | null)?.value)+ .filter((value): value is string => typeof value === "string");+}++/**+ * The id to write the definition under, derived from the note and the definition name rather than+ * generated.+ *+ * `dbVersion` is a not-synced option, so every instance sharing a document runs this migration+ * against its own copy. With a generated id each would write a different row and the sync would leave+ * the note carrying two definitions of the same name — exactly the duplicated field this migration+ * exists to avoid. Deriving the id makes the two writes the same row, which converges.+ */+export function deriveDefinitionAttributeId(noteId: string, definitionName: string): string {+ return md5(`${noteId}|${definitionName}`).substring(0, 12);+}++/** Gathers everything {@link planBoardMigration} needs, reading nothing a protected note would deny. */+function collectBoardInput(note: BNote): BoardMigrationInput {+ const groupBy = (note.getLabelValue("board:groupBy") ?? DEFAULT_GROUP_BY).trim();+ const isRelationMode = groupBy.startsWith("~");+ const name = groupBy.replace(/^[#~]/, "").trim();++ const base = {+ noteId: note.noteId,+ name,+ // The hidden subtree gives its notes ids of their own, all starting with an underscore.+ isSystemNote: note.noteId.startsWith("_"),+ isProtected: !!note.isProtected,+ isRelationMode,+ isSearchNote: note.type === "search"+ };++ // The attachment of a protected note is encrypted, and a search note's results are not its+ // subtree; in every skipped case below, neither is read.+ if (base.isSystemNote || base.isProtected || isRelationMode || base.isSearchNote || !name) {+ return { ...base, persistedColumns: [], discoveredValues: [] };+ }++ return {+ ...base,+ existingDefinition: findExistingDefinition(note, name),+ persistedColumns: readPersistedColumns(note),+ discoveredValues: readDiscoveredValues(note, name)+ };+}++/** The definition the board can see for the label, owned or inherited, whichever comes first. */+function findExistingDefinition(note: BNote, name: string): ExistingDefinition | undefined {+ // Owned attributes are listed before inherited ones, so a board that has already been migrated+ // finds its own copy rather than the template's.+ const attribute = note.getAttributes()+ .find((attr) => attr.isDefinition() && attr.name === `label:${name}`);+ if (!attribute) {+ return undefined;+ }++ return {+ attributeId: attribute.attributeId,+ ownerNoteId: attribute.noteId,+ isInheritable: attribute.isInheritable,+ definition: attribute.getDefinition()+ };+}++function readPersistedColumns(note: BNote): string[] {+ const attachment = note.getAttachmentsByRole(VIEW_CONFIG_ROLE)+ .find((candidate) => candidate.title === BOARD_VIEW_CONFIG_TITLE);+ if (!attachment) {+ return [];+ }++ try {+ return parseBoardColumns(unwrapStringOrBuffer(attachment.getContent()));+ } catch (e) {+ console.log(`Could not read '${BOARD_VIEW_CONFIG_TITLE}' of board '${note.noteId}':`, e);+ return [];+ }+}++/**+ * The values the board's notes carry, read the way the board view reads them: the whole subtree+ * rather than the direct children, archived notes included so that a column does not disappear with+ * the last note that was filed under it.+ */+function readDiscoveredValues(note: BNote, name: string): string[] {+ const values: string[] = [];++ for (const descendant of note.getSubtree({ includeArchived: true, includeHidden: false }).notes) {+ if (descendant.noteId === note.noteId) continue;++ const value = descendant.getLabelValue(name);+ if (value) {+ values.push(value);+ }+ }++ return values;+}++function writeDefinition(plan: Extract<BoardMigrationPlan, { action: "write" }>) {+ const existing = becca.attributes[plan.attributeId];++ // Constructing a second BAttribute for an id becca already holds would push a duplicate onto the+ // note's owned attributes, so an existing row — the board's own definition, or this migration's+ // own earlier write — is edited rather than replaced.+ if (existing) {+ existing.value = plan.value;+ existing.isInheritable = plan.isInheritable;+ existing.save();+ return;+ }++ new BAttribute({+ attributeId: plan.attributeId,+ noteId: plan.noteId,+ type: "label",+ name: plan.name,+ value: plan.value,+ isInheritable: plan.isInheritable+ }).save();+}diff --git a/packages/trilium-core/src/migrations/migrations.ts b/packages/trilium-core/src/migrations/migrations.tsindex 7faf7a9a41..5e06935d9c 100644--- a/packages/trilium-core/src/migrations/migrations.ts+++ b/packages/trilium-core/src/migrations/migrations.ts@@ -9,6 +9,12 @@ export function getMaxMigrationVersion() {// Migrations should be kept in descending order, so the latest migration is first.export const MIGRATIONS: (SqlMigration | JsMigration)[] = [+ // Give every board its own select definition for the label it groups by, so the columns stop+ // living only in the board.json attachment+ {+ version: 240,+ module: () => import("./0240__migrate_board_status_to_select.js")+ },// Turn TOTP back off for installs that had disabled MFA before the enable flag was removed{version: 239,diff --git a/packages/trilium-core/src/test/fixtures/document.db b/packages/trilium-core/src/test/fixtures/document.dbindex 5c2ba0797a..deff1cafed 100644Binary files a/packages/trilium-core/src/test/fixtures/document.db and b/packages/trilium-core/src/test/fixtures/document.db differ