Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/collections/board: fix some issues
Adorian Dorane66ff9226ad7
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 65ad2abc8e..dd2478f250 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -27,6 +27,19 @@ function failNextBulkAction() {vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));}+/** The same for a column rename, which the server makes in one write of its own. */+function failNextRename() {+ vi.spyOn(server, "put").mockRejectedValueOnce(new Error("offline"));+}++/** Holds the next rename open, answering it only once the returned function is called. */+function holdNextRename() {+ let release = () => {};+ vi.spyOn(server, "put").mockImplementationOnce(+ () => new Promise<void>((resolve) => { release = resolve; }));+ return () => release();+}+vi.mock("../../../services/branches", () => ({default: {cloneNoteToParentNote: vi.fn(async () => {}),@@ -86,18 +99,16 @@ describe("BoardApi column mutations", () => {const { api, saved } = createApi(viewConfig, [ "To Do", "Done" ]);await api.addNewColumn("In Progress");- await api.renameColumn("Done", "Shipped");await api.removeColumn("To Do");- expect(saved).toHaveLength(3);+ expect(saved).toHaveLength(2);for (const config of saved) {expect(config).not.toBe(viewConfig);expect(config.columns).not.toBe(viewConfig.columns);}expect(saved.map(config => config.columns?.map(col => col.value))).toEqual([[ "To Do", "Done", "In Progress" ],- [ "To Do", "Shipped", "In Progress" ],- [ "Shipped", "In Progress" ]+ [ "Done", "In Progress" ]]);});@@ -228,13 +239,24 @@ describe("BoardApi column mutations", () => {expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", icon: "bx bx-list-ul" } ]);});- it("keeps the icon of a column it renames", async () => {+ /**+ * What the column is drawn with is kept by the server, which renames it in the stored columns+ * as well as in the cards and the definition. Checked there; asked for here.+ */+ it("asks the server to rename the column, rather than writing each place itself", async () => {+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);const { api, saved } = createApi({ columns: [ { value: "Done", icon: "bx bx-check" } ] }, [ "Done" ]);+ // Cleared: the mock outlives the test that first stood it up, and its calls with it.+ vi.mocked(executeBulkActions).mockClear();await api.renameColumn("Done", "Shipped");- expect(saved.at(-1)?.columns).toEqual([ { value: "Shipped", icon: "bx bx-check" } ]);+ expect(put).toHaveBeenCalledWith(expect.stringMatching(/board\/rename-column$/), {+ attribute: "status", isRelation: false, oldValue: "Done", newValue: "Shipped"+ });+ expect(saved).toEqual([]);+ expect(executeBulkActions).not.toHaveBeenCalled();});it("records what each column it renames away or deletes became", async () => {@@ -265,7 +287,7 @@ describe("BoardApi column mutations", () => {[ "To Do", "Done" ]);- failNextBulkAction();+ failNextRename();await expect(api.renameColumn("Done", "Shipped")).rejects.toThrow("offline");failNextBulkAction();@@ -281,7 +303,7 @@ describe("BoardApi column mutations", () => {await api.renameColumn("Done", "Shipped");// The refused rename re-pointed the first one on its way in, which has to be put back.- failNextBulkAction();+ failNextRename();await expect(api.renameColumn("Shipped", "Delivered")).rejects.toThrow("offline");expect([ ...pendingRenames ]).toEqual([ [ "Done", "Shipped" ] ]);@@ -299,7 +321,7 @@ describe("BoardApi column mutations", () => {);// Both start before either finishes, and both are refused.- failNextBulkAction();+ failNextRename();failNextBulkAction();const first = api.renameColumn("Done", "Shipped");const second = api.removeColumn("To Do");@@ -316,7 +338,7 @@ describe("BoardApi column mutations", () => {);let releaseSecond = () => {};- vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));+ failNextRename();vi.mocked(executeBulkActions).mockImplementationOnce(() => new Promise<void>((resolve) => { releaseSecond = resolve; }));@@ -339,9 +361,8 @@ describe("BoardApi column mutations", () => {const { api, pendingRenames } = createApi({ columns: [ { value: "Done" } ] }, [ "Done" ]);let releaseSecond = () => {};- vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));- vi.mocked(executeBulkActions).mockImplementationOnce(- () => new Promise<void>((resolve) => { releaseSecond = resolve; }));+ failNextRename();+ releaseSecond = holdNextRename();const failing = api.renameColumn("Done", "Shipped");const running = api.renameColumn("Shipped", "Delivered");@@ -364,8 +385,8 @@ describe("BoardApi column mutations", () => {const { api, pendingRenames } = createApi({ columns: [ { value: "Done" } ] }, [ "Done" ]);let failSecond = (_: Error) => {};- vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));- vi.mocked(executeBulkActions).mockImplementationOnce(+ failNextRename();+ vi.spyOn(server, "put").mockImplementationOnce(() => new Promise<void>((_, reject) => { failSecond = reject; }));const first = api.renameColumn("Done", "Shipped");@@ -446,6 +467,8 @@ describe("BoardApi card operations", () => {beforeEach(() => {// Spies outlive a test otherwise, and one standing in for a write is read by the next.vi.restoreAllMocks();+ // Every write the api makes over the wire, answered rather than attempted.+ vi.spyOn(server, "put").mockResolvedValue(undefined);vi.mocked(branches.moveBeforeBranch).mockClear();vi.mocked(branches.moveAfterBranch).mockClear();vi.mocked(note_create.createNote).mockClear();@@ -1221,11 +1244,12 @@ describe("renaming a column that names itself", () => {it("renames any other column by the value its cards carry", async () => {const { api } = createApi({ columns: [ { value: "" }, { value: "To Do" } ] }, [ "", "To Do" ]);- vi.mocked(executeBulkActions).mockClear();+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);await api.setColumnTitle("To Do", "Doing");- expect(executeBulkActions).toHaveBeenCalled();+ expect(put).toHaveBeenCalledWith(expect.stringMatching(/board\/rename-column$/),+ expect.objectContaining({ oldValue: "To Do", newValue: "Doing" }));});it("leaves either kind alone when given nothing", async () => {diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex ac6db6b9d4..27214da9ec 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -356,18 +356,26 @@ export default class BoardApi {return;}- const noteIds = this.byColumn?.get(oldValue)?.map(item => item.note.noteId) || [];-- // Change the value in the notes.- const action: BulkAction = this.isRelationMode- ? { name: "updateRelationTarget", relationName: this.statusAttribute, targetNoteId: newValue }- : { name: "updateLabelValue", labelName: this.statusAttribute, labelValue: newValue };- await this.retiredWhile(oldValue, newValue,- () => executeBulkActions(noteIds, [ action ], { silent: true }));-- // Rename the column in the persisted data.- this.storeColumns((this.viewConfig?.columns ?? [])- .map(col => col.value === oldValue ? { ...col, value: newValue } : col));+ // One write, which the server makes over the cards, the stored columns and the definition+ // together. Renaming them from here one at a time leaves a window in which they disagree,+ // and another client reading the board during it resolves the old name back from whichever+ // of them still carries it and writes that back, undoing the rename.+ const renamed = await this.retiredWhile(oldValue, newValue, () =>+ server.put<{ config?: BoardViewData }>(+ `notes/${this.parentNote.noteId}/board/rename-column`, {+ attribute: this.statusAttribute,+ isRelation: this.isRelationMode,+ oldValue,+ newValue+ }));++ // Taken from the answer rather than waited for: until the change arrives, this still holds+ // the configuration it read before the rename, and a refresh landing in between would write+ // that back and bring the old name with it.+ if (renamed?.config) {+ this.viewConfig = renamed.config;+ this.viewConfigSource = renamed.config;+ }}/** Stores the icon a column shows, or clears it back to the default when given nothing. */diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex 60f37e6dd2..d51075a727 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -10,6 +10,7 @@ import { ContextMenuEvent } from "../../../menus/context_menu";import { openNoteContextMenu } from "./context_menu";import { t } from "../../../services/i18n";import UserAttributesDisplay from "../../attribute_widgets/UserAttributesList";+import { FLIP_SETTLE_MS } from "../../react/flip";import {useNoteColorClass, useNoteIcon, useNoteLabelBoolean, useTriliumEvent} from "../../react/hooks";@@ -134,11 +135,20 @@ function Card({return;}- if (card.nextElementSibling) {- card.scrollIntoView?.({ block: "nearest" });- } else {- content.scrollTop = content.scrollHeight;- }+ const bring = () => {+ if (card.nextElementSibling) {+ card.scrollIntoView?.({ block: "nearest" });+ } else {+ content.scrollTop = content.scrollHeight;+ }+ };++ bring();+ // And again once it has opened out: a card asked for while it is still growing is measured+ // against a column shorter than the one it ends up in, which leaves it over the edge.+ const settled = window.setTimeout(bring, FLIP_SETTLE_MS);++ return () => window.clearTimeout(settled);}, [ isNew ]);return (diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 410f37a853..af4e756b0e 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -18,8 +18,11 @@ import ActionButton from "../../react/ActionButton";import Icon from "../../react/Icon";import { IconPickerButton } from "../../react/IconPicker";import { useStaticTooltip } from "../../react/hooks";-import { useFlip } from "../../react/flip";+import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";import { useScrollFade } from "../../react/scroll_fade";++/** How long a column stays quiet for a card the footer is making, if the write never answers. */+const FOOTER_QUIET_MS = 5000;import NoteLink from "../../react/NoteLink";import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";import BoardApi from "./api";@@ -85,14 +88,26 @@ export default function Column({// The column stays the one just added until another is, so what has already been shown is// remembered here rather than played again by every redraw of the board.const [ isRevealed, setIsRevealed ] = useState(false);- /** The card the footer made, which arrives without opening out. */- const quietlyAdded = created?.takesFocus === false ? created.noteId : undefined;+ /**+ * When a card the footer is making may still arrive.+ *+ * Naming the card itself is not enough: the write answers with its id, and the refresh that+ * draws it can land first, so the card is on the board before there is anything to say it came+ * from the footer. The column is quiet from the moment the footer is asked instead.+ */+ const footerQuietUntil = useRef(0);// A card inserted next to another one is where the reader is working, so it is left focused; one// made in the footer is not, or every card would take focus from the editor still being typed in.const cardInserted = useCallback((noteId: string | undefined) => setCreated({ noteId, takesFocus: true }), []);- const cardAdded = useCallback(- (noteId: string | undefined) => setCreated({ noteId, takesFocus: false }), []);+ const addingFromFooter = useCallback(() => {+ // Long enough to cover a write that never answers, and cut short by the one that does.+ footerQuietUntil.current = Date.now() + FOOTER_QUIET_MS;+ }, []);+ const cardAdded = useCallback((noteId: string | undefined) => {+ footerQuietUntil.current = Date.now() + FLIP_SETTLE_MS;+ setCreated({ noteId, takesFocus: false });+ }, []);const { setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn } =useContext(BoardActionsContext);const { branchIdToEdit, columnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardDragStateContext);@@ -106,7 +121,7 @@ export default function Column({// to its end, and opening out on top of those is one movement too many.useFlip(contentRef, {selector: ".board-note",- grow: (card) => card.dataset.noteId !== quietlyAdded+ grow: () => Date.now() > footerQuietUntil.current});const { handleDragOver, handleDragLeave, handleDrop } = useDragging({column, columnIndex, columnItems, isEditing, api, parentNote@@ -360,6 +375,7 @@ export default function Column({isCreating={isCreatingNewItem}setIsCreating={setIsCreatingNewItem}onCreated={cardAdded}+ onCreating={addingFromFooter}/>}</div>);@@ -369,13 +385,15 @@ export default function Column({* The editor a new card is named in, opened by the button below the column or by its menu. The* state is the column's rather than this component's, since the menu is raised from the header.*/-function AddNewItem({ column, api, isCreating, setIsCreating, onCreated }: {+function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreating }: {column: string,api: BoardApi,isCreating: boolean,setIsCreating: (isCreating: boolean) => void,/** Names the card just made, which the column reveals once the board has drawn it. */- onCreated: (noteId: string | undefined) => void+ onCreated: (noteId: string | undefined) => void,+ /** Said before the write, which the card can be drawn by the board ahead of. */+ onCreating: () => void}) {// What the editor opens with: empty to begin with, then whatever was typed into it and left// unsaved, so that reaching for something else and coming back does not cost the title.@@ -419,7 +437,10 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated }: {<TitleEditorcurrentValue={initialTitle}placeholder={t("board_view.new-item-placeholder")}- save={async (title) => onCreated(await api.createNewItem(column, title))}+ save={async (title) => {+ onCreating();+ onCreated(await api.createNewItem(column, title));+ }}dismiss={() => setIsCreating(false)}mode="multiline" isNewItemselectOnFocus={false}diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 7b846b08ea..a86034aeec 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -695,31 +695,40 @@ describe("Board column rename", () => {* which a board that cannot write its own definition does for good. The board still has to* bring what it can reach into line, so only a running write holds persistence back.*/- it("persists again once the write has landed, even with its record left standing", async () => {+ /**+ * A board that keeps a column list is left to keep it: written on every refresh instead, a+ * client reading the board while another changes it resolves a name the change has already+ * taken away and writes it back as a column of its own.+ */+ it("leaves a stored column list alone, and writes one only for a board with none", async () => {const { note } = await setup();saved.length = 0;- // The record stands, and no write is running.- getPendingWrites(`${note.noteId}|status`).renames.set("Done", undefined);+ const draw = async (initialConfig: BoardViewData) => {+ const mountPoint = document.createElement("div");+ document.body.appendChild(mountPoint);+ await act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <Harness+ note={note}+ noteIds={[ ...note.getChildNoteIds() ]}+ initialConfig={initialConfig}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await act(async () => { await flush(); });+ mountPoint.remove();+ };- const second = document.createElement("div");- document.body.appendChild(second);- await act(async () => {- render(- <ParentComponent.Provider value={new Component()}>- <Harness- note={note}- noteIds={[ ...note.getChildNoteIds() ]}- initialConfig={DEFAULT_CONFIG}- />- </ParentComponent.Provider>,- second- );- });- await act(async () => { await flush(); });+ await draw(DEFAULT_CONFIG);+ expect(saved).toEqual([]);- expect(saved.at(-1)?.columns?.map(column => column.value)).toEqual([ "To Do", "Doing" ]);- second.remove();+ await draw({});+ expect(saved.at(-1)?.columns?.map(column => column.value))+ .toEqual([ "To Do", "Doing", "Done" ]);});it("offers its keys as contextual shortcut hints", async () => {@@ -1026,15 +1035,23 @@ describe("Board column rename", () => {await act(async () => { await flush(); });}- it("does not leave the old name behind as an empty column", async () => {+ /**+ * The cards, the stored columns and the definition are renamed together by the server, so that+ * no client reads the board while they disagree and writes the old name back. What the board+ * does from here is ask for that, and write none of the three itself.+ */+ it("asks the server to rename the column, and writes nothing of its own", async () => {const { container } = await setup();+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);expect(columnTitles(container)).toEqual([ "To Do", "Doing", "Done" ]);await renameSecondColumn(container, "In Progress");- expect(columnTitles(container)).toEqual([ "To Do", "In Progress", "Done" ]);- expect(saved.at(-1)?.columns?.map(c => c.value))- .toEqual([ "To Do", "In Progress", "Done" ]);+ expect(put).toHaveBeenCalledWith(expect.stringMatching(/board\/rename-column$/),+ expect.objectContaining({+ attribute: "status", oldValue: "Doing", newValue: "In Progress"+ }));+ expect(saved).toEqual([]);});/**@@ -1582,7 +1599,7 @@ describe("Board column rename", () => {it("says so when what was typed could not be saved", async () => {const { container } = await setup();const error = vi.spyOn(toast, "showError").mockImplementation(() => {});- vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));+ vi.spyOn(server, "put").mockRejectedValueOnce(new Error("offline"));await renameSecondColumn(container, "Renamed");await act(async () => { await flush(); });diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 726d9afa15..da6451a862 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -27,7 +27,7 @@ import NoteAutocomplete from "../../react/NoteAutocomplete";import ShortcutHintButton from "../../shortcut_hints/shortcut_hint_button";import { onWheelHorizontalScroll } from "../../widget_utils";import { useDragPan } from "../../react/drag_pan";-import { useFlip } from "../../react/flip";+import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";import { ViewModeProps } from "../interface";import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";import { useBoardDrag } from "./board_drag";@@ -302,6 +302,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC[ usableColumns, storedColumns, includeArchived ]);const containerRef = useRef<HTMLDivElement>(null);+ /** When a column the reader moved may still be settling, which is what a slide is drawn for. */+ const columnMovedUntil = useRef(0);const boardDragState = useMemo<BoardDragState>(() => ({branchIdToEdit,@@ -360,17 +362,34 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCreturn;}- if (newPersistedData) {+ // 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+ // whichever source it has not heard about yet, and writes it back as a column.+ // What this board itself changes is written where it is changed.+ if (newPersistedData && !viewConfig?.columns?.length) {viewConfig = { ...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.+ // The columns the board settled on are the options its definition should offer,+ // which is what gives a board created after migration 0240 ran a definition at all.+ // Only a board without one of its own: a client reading the board while another is+ // changing it resolves a name the change has already taken away, and writing that+ // into the definition puts the column back for everyone. What this board changes+ // itself is written where it is changed.// 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.+ // Only a board that has no definition of its own. One that has is kept in step by+ // whatever writes its columns: the server for a rename, `storeColumns` for+ // everything the board itself changes. Writing it from here as well means a client+ // reading the board while another changes it puts its own view of the columns on+ // disk, which is how a renamed column loses its place or comes back under its old+ // name.+ if (statusDefinition?.isOwned) {+ return;+ }+api.syncColumnsToDefinition(columns).catch((e) => console.error("Failed to sync the board columns to the attribute definition:", e));});@@ -455,12 +474,19 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// jump to. Two are left out: the copy being carried, whose transform the gesture writes every// frame, and the add-column button, which a new column moves at the same moment as the scroll// that keeps it in view, so sliding it as well reads as a stumble rather than as movement.+ //+ // Columns are moved, never opened out. A column is its grouping value, so it is drawn afresh+ // whenever that value changes, and a rename is indistinguishable from an arrival to anything+ // watching the page. The one column that really does arrive is the one just added, and the fade+ // and the board running to its end already say so.useFlip(containerRef, {selector: ".board-column:not(.board-drag-preview)",axis: "horizontal",- // Except the one just added: it is already announced by the fade and by the board running- // to its end, and opening out on top of those is one movement too many.- grow: (column) => column.dataset.column !== createdColumn+ // Only for a move the reader made. A column is its grouping value, so the board redraws+ // its columns whenever a value changes, and the order churns for a moment as the three+ // places that name a column catch up with one another; following that draws a slide for a+ // rename nobody moved.+ disabled: !draggedColumn && Date.now() > columnMovedUntil.current});/**@@ -518,6 +544,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// landed among them all once some are archived and hidden. Translated here so a reorder leaves// every hidden column where it was rather than herding them to the end.const handleColumnDrop = useCallback((fromIndex: number, toIndex: number) => {+ columnMovedUntil.current = Date.now() + FLIP_SETTLE_MS;// The list the api holds, which is also the one it reorders. A column the board is not// showing is in neither, so indexing into `columns` would be off by one.const allColumns = api.columns;@@ -852,9 +879,18 @@ export function TitleEditor({if (target instanceof HTMLElement) {shouldDismiss.current = (e.key === "Escape");target.focus();- } else {- dismiss();+ return;}++ // Nothing to hand focus back to, and it is the blur of handing it back that saves. An+ // editor opened by a press on the thing it edits, rather than from something focused,+ // has nowhere to send it, so Enter says here what that blur would have said.+ const typed = inputRef.current?.value ?? "";+ if (e.key === "Enter" && typed.trim() && (typed !== currentValue || isNewItem)) {+ commit(typed);+ }++ dismiss();}};diff --git a/apps/client/src/widgets/react/flip.ts b/apps/client/src/widgets/react/flip.tsindex db2cdc6611..173640cc80 100644--- a/apps/client/src/widgets/react/flip.ts+++ b/apps/client/src/widgets/react/flip.ts@@ -121,6 +121,14 @@ export function useFlip(slide(child, by, axis);}+ if (moved.length) {+ // Read once, to make the browser work out the styles just written before the frame that+ // takes them away. Without it a child moved in the page can be set back and let go+ // inside one recalculation, which leaves the transition nothing to start from and the+ // move is drawn where it lands with nothing in between.+ void container.offsetHeight;+ }+if (!arrived.length) {return;}@@ -130,6 +138,8 @@ export function useFlip(open(child, size, axis);}+ void container.offsetHeight;+// Read again once the growth is over, so what follows is measured against where its// neighbours came to rest rather than against wherever it caught them.window.clearTimeout(settled.current);diff --git a/apps/client/src/widgets/react/scroll_fade.ts b/apps/client/src/widgets/react/scroll_fade.tsindex d2ab502a35..cc4809c649 100644--- a/apps/client/src/widgets/react/scroll_fade.ts+++ b/apps/client/src/widgets/react/scroll_fade.ts@@ -87,7 +87,21 @@ export function useScrollFade(ref: RefObject<HTMLElement>, options: ScrollFadeOp// and shrinks without either, which no resize reports.const resize = new ResizeObserver(request);resize.observe(element);- const mutations = new MutationObserver(request);++ // The children too: one of them growing changes how much there is to scroll while the box+ // it grows inside keeps its size, and an animated height is not a change to the page that+ // anything else here would hear about.+ const watchChildren = () => {+ for (const child of element.children) {+ resize.observe(child);+ }+ };+ watchChildren();++ const mutations = new MutationObserver(() => {+ watchChildren();+ request();+ });mutations.observe(element, { childList: true, subtree: true, characterData: true });element.addEventListener("scroll", measure, { passive: true });diff --git a/packages/trilium-core/src/routes/api/board.spec.ts b/packages/trilium-core/src/routes/api/board.spec.tsnew file mode 100644index 0000000000..676296251d--- /dev/null+++ b/packages/trilium-core/src/routes/api/board.spec.ts@@ -0,0 +1,135 @@+import { beforeAll, describe, expect, it } from "vitest";++import becca from "../../becca/becca";+import { createTextNote } from "../../test/api_fixtures";+import { CoreApiTester } from "../../test/api_tester";++let api: CoreApiTester;++describe("Board API (core)", () => {+ beforeAll(() => {+ api = CoreApiTester.build();+ });++ it("renames a column in the cards, the definition and the stored configuration at once", async () => {+ const board = await buildBoard([ "Alpha", "Alpha", "Beta" ]);++ const res = await api.put<{ cards: number }>(+ `/api/notes/${board.noteId}/board/rename-column`,+ { body: { attribute: "status", oldValue: "Alpha", newValue: "Gamma" } });++ expect(res.status).toBe(200);+ expect(res.body.cards).toBe(2);+ expect(statuses(board.noteId)).toEqual([ "Gamma", "Gamma", "Beta" ]);+ // In place in both, so the column keeps the position it is drawn in.+ expect(definitionOptions(board.noteId)).toEqual([ "Gamma", "Beta" ]);+ expect(storedColumns(board.noteId)).toEqual([ "Gamma", "Beta" ]);+ });++ it("keeps what a column is drawn with, and leaves the other columns alone", async () => {+ const board = await buildBoard([ "Alpha", "Beta" ]);++ await api.put(`/api/notes/${board.noteId}/board/rename-column`,+ { body: { attribute: "status", oldValue: "Beta", newValue: "Delta" } });++ const columns = configOf(board.noteId).columns;+ expect(columns.map(column => column.value)).toEqual([ "Alpha", "Delta" ]);+ expect(columns[1].color).toBe("#ff0000");+ expect(columns[0].color).toBeUndefined();+ });++ it("refuses a blank name, and says so rather than writing anything", async () => {+ const board = await buildBoard([ "Alpha" ]);++ const res = await api.put(`/api/notes/${board.noteId}/board/rename-column`,+ { body: { attribute: "status", oldValue: "Alpha", newValue: " " } });++ expect(res.status).toBe(400);+ expect(statuses(board.noteId)).toEqual([ "Alpha" ]);+ });++ it("does nothing at all for a column renamed to the name it already has", async () => {+ const board = await buildBoard([ "Alpha" ]);++ const res = await api.put<{ cards: number }>(+ `/api/notes/${board.noteId}/board/rename-column`,+ { body: { attribute: "status", oldValue: "Alpha", newValue: "Alpha" } });++ expect(res.status).toBe(200);+ expect(res.body.cards).toBe(0);+ expect(statuses(board.noteId)).toEqual([ "Alpha" ]);+ });++ it("renames a column of a board grouped by a relation", async () => {+ const board = await buildBoard([]);+ const target = await createTextNote(api, { title: "Target" });+ const other = await createTextNote(api, { title: "Other" });+ const card = await createTextNote(api, { parentNoteId: board.noteId, title: "Card" });+ await api.put(`/api/notes/${card.noteId}/set-attribute`, {+ body: { type: "relation", name: "status", value: target.noteId }+ });++ const res = await api.put<{ cards: number }>(+ `/api/notes/${board.noteId}/board/rename-column`, {+ body: {+ attribute: "status", isRelation: true,+ oldValue: target.noteId, newValue: other.noteId+ }+ });++ expect(res.status).toBe(200);+ expect(res.body.cards).toBe(1);+ expect(becca.getNoteOrThrow(card.noteId).getOwnedRelationValue("status")).toBe(other.noteId);+ });++ /** A board with one card per value given, the second column carrying a colour of its own. */+ async function buildBoard(values: string[]) {+ const board = await createTextNote(api, { title: "Board" });+ const columns = [ ...new Set(values) ];++ await api.put(`/api/notes/${board.noteId}/set-attribute`, {+ body: {+ type: "label", name: "label:status", isInheritable: true,+ value: `promoted,single,select,options=${columns.join(";")}`+ }+ });++ for (const value of values) {+ const card = await createTextNote(api,+ { parentNoteId: board.noteId, title: `Card ${value}` });+ await api.put(`/api/notes/${card.noteId}/set-attribute`,+ { body: { type: "label", name: "status", value } });+ }++ await api.post(`/api/notes/${board.noteId}/attachments`, {+ body: {+ title: "board.json", role: "viewConfig", mime: "application/json",+ content: JSON.stringify({+ columns: columns.map((value, index) =>+ index === 1 ? { value, color: "#ff0000" } : { value })+ })+ }+ });++ return board;+ }++ function statuses(boardId: string) {+ return becca.getNoteOrThrow(boardId).getChildNotes()+ .map(card => card.getOwnedLabelValue("status"));+ }++ function definitionOptions(boardId: string) {+ const definition = becca.getNoteOrThrow(boardId).getOwnedLabelValue("label:status") ?? "";+ return definition.split("options=")[1]?.split(";") ?? [];+ }++ function configOf(boardId: string): { columns: { value: string, color?: string }[] } {+ const attachment = becca.getNoteOrThrow(boardId).getAttachmentByTitle("board.json");+ return JSON.parse(attachment?.getContent().toString() ?? "{}");+ }++ function storedColumns(boardId: string) {+ return configOf(boardId).columns.map(column => column.value);+ }+});diff --git a/packages/trilium-core/src/routes/api/board.ts b/packages/trilium-core/src/routes/api/board.tsnew file mode 100644index 0000000000..ee50bf98e4--- /dev/null+++ b/packages/trilium-core/src/routes/api/board.ts@@ -0,0 +1,142 @@+import { promotedAttributeDefinitionParser } from "@triliumnext/commons";+import type { Request } from "express";++import becca from "../../becca/becca.js";+import type BNote from "../../becca/entities/bnote.js";+import { ValidationError } from "../../errors.js";++/** The title of the attachment a collection keeps its view configuration in. */+const CONFIG_ATTACHMENT = "board.json";++interface RenameColumnRequest {+ /** The label or relation the board groups by, without the `#` or `~` it is written with. */+ attribute: string;+ /** Whether the board groups by a relation, whose value is a note rather than a name. */+ isRelation?: boolean;+ oldValue: string;+ newValue: string;+}++/** One column as the board stores it, which holds what it is drawn with as well as its value. */+interface StoredColumn {+ value: string;+ [key: string]: unknown;+}++/**+ * Renames a board column, everywhere it is named, in one write.+ *+ * A column is three things at once: the value its cards carry, an entry in the board's stored+ * configuration, and an option of the definition the board groups by. Renaming them one at a time+ * leaves a window in which they disagree, and a client that reads the board during it resolves the+ * old name back from whichever of the three still carries it and writes that back. Written together+ * under one transaction, there is no such window for anyone to read.+ */+function renameColumn(req: Request<{ noteId: string }>) {+ const noteId = req.params.noteId;+ const { attribute, isRelation, oldValue, newValue } = req.body as RenameColumnRequest;++ if (!attribute?.trim()) {+ throw new ValidationError("The attribute the board groups by is required.");+ }++ // A column is its value, so a blank name would leave its cards with nothing to group by.+ if (!newValue?.trim()) {+ throw new ValidationError("A column's new name cannot be empty.");+ }++ if (oldValue === newValue) {+ return { cards: 0 };+ }++ const board = becca.getNoteOrThrow(noteId);+ const type = isRelation ? "relation" : "label";++ let cards = 0;+ for (const note of board.getSubtree({ includeArchived: true }).notes) {+ for (const owned of note.getOwnedAttributes(type, attribute)) {+ if (owned.value === oldValue) {+ owned.value = newValue;+ owned.save();+ cards++;+ }+ }+ }++ renameInDefinition(board, attribute, oldValue, newValue);++ // Answered with, so the client that asked has the configuration as it now stands rather than+ // the one it read before the rename. Writing that stale one back is what used to bring the old+ // name to the board again a moment after it left.+ return { cards, config: renameInConfig(board, oldValue, newValue) };+}++/**+ * Renames the column in the list of values the board's own definition offers.+ *+ * Only its own: a definition the board merely inherits describes every board under that note, and+ * is not this board's to rewrite.+ */+function renameInDefinition(board: BNote, attribute: string, oldValue: string, newValue: string) {+ const definition = board.getOwnedAttributes("label", `label:${attribute}`)[0];+ if (!definition) {+ return;+ }++ const parsed = promotedAttributeDefinitionParser.parse(definition.value);+ if (parsed.labelType !== "select" || !parsed.selectOptions?.includes(oldValue)) {+ return;+ }++ definition.value = promotedAttributeDefinitionParser.serialize({+ ...parsed,+ // In place, so the column keeps the position it is drawn in.+ selectOptions: parsed.selectOptions.map(option => option === oldValue ? newValue : option)+ }, "label");+ definition.save();+}++/**+ * Renames the column in the board's stored configuration, keeping everything else it holds.+ *+ * @returns the configuration as it now stands, or nothing where the board keeps none.+ */+function renameInConfig(board: BNote, oldValue: string, newValue: string) {+ const attachment = board.getAttachmentByTitle(CONFIG_ATTACHMENT);+ if (!attachment) {+ return undefined;+ }++ let config: { columns?: StoredColumn[] };+ try {+ config = JSON.parse(attachment.getContent().toString());+ } catch {+ // A configuration that cannot be read is left as it is: the cards and the definition+ // already name the column, and the board writes this one out again as it draws.+ return undefined;+ }++ if (!config.columns?.some(column => column.value === oldValue)) {+ return config;+ }++ const renamed = {+ ...config,+ columns: config.columns.map(column =>+ column.value === oldValue ? { ...column, value: newValue } : column)+ };++ board.saveAttachment({+ title: CONFIG_ATTACHMENT,+ role: attachment.role,+ mime: attachment.mime,+ position: attachment.position,+ content: JSON.stringify(renamed)+ }, "title");++ return renamed;+}++export default {+ renameColumn+};diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 622d7232f3..96678a947e 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -18,6 +18,7 @@ import revisionsApiRoute from "./api/revisions";import relationMapApiRoute from "./api/relation-map";import recentChangesApiRoute from "./api/recent_changes";import deletedNotesApiRoute from "./api/deleted_notes";+import boardRoute from "./api/board";import bulkActionRoute from "./api/bulk_action";import searchRoute from "./api/search";import specialNotesRoute from "./api/special_notes";@@ -295,6 +296,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransapiRoute(GET, "/api/sql/schema", sqlRoute.getSchema);apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);+ apiRoute(PUT, "/api/notes/:noteId/board/rename-column", boardRoute.renameColumn);+apiRoute(PST, "/api/bulk-action/execute", bulkActionRoute.execute);apiRoute(PST, "/api/bulk-action/affected-notes", bulkActionRoute.getAffectedNoteCount);