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: improve test coverage
Adorian Doran78665e37fa5a
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex c9164df5c1..cfc9384260 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -2,15 +2,18 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import FAttribute from "../../../entities/fattribute";import branches from "../../../services/branches";+import attributes from "../../../services/attributes";import { executeBulkActions } from "../../../services/bulk_action";import dialog from "../../../services/dialog";import FNote from "../../../entities/fnote";import froca from "../../../services/froca";+import note_create from "../../../services/note_create";import noteAttributeCache from "../../../services/note_attribute_cache";import server from "../../../services/server";import { buildNote } from "../../../test/easy-froca";import { BoardViewData } from ".";import BoardApi from "./api";+import { ColumnMap } from "./data";import { BOARD_TEMPLATE_ID, getStatusDefinition } from "./columns";vi.mock("../../../services/bulk_action", () => ({@@ -23,7 +26,15 @@ function failNextBulkAction() {}vi.mock("../../../services/branches", () => ({- default: { cloneNoteToParentNote: vi.fn(async () => {}) }+ default: {+ cloneNoteToParentNote: vi.fn(async () => {}),+ moveBeforeBranch: vi.fn(async () => {}),+ moveAfterBranch: vi.fn(async () => {})+ }+}));++vi.mock("../../../services/note_create", () => ({+ default: { createNote: vi.fn(async () => ({ note: null, branch: null })) }}));vi.mock("../../../services/dialog", () => ({@@ -40,23 +51,25 @@ function createApi(viewConfig: BoardViewData,columns: string[],parentNote?: FNote,- statusAttribute = "status"+ statusAttribute = "status",+ byColumn: ColumnMap = new Map()) {const board = parentNote ?? buildNote({ title: "Board" });const saved: BoardViewData[] = [];+ const editing: (string | undefined)[] = [];const pendingRenames = new Map<string, string | undefined>();const api = new BoardApi(- new Map(),+ byColumn,columns,board,statusAttribute,viewConfig,(newConfig) => saved.push(newConfig),- () => {},+ (branchId) => editing.push(branchId),pendingRenames,getStatusDefinition(board, statusAttribute));- return { api, saved, pendingRenames };+ return { api, saved, editing, pendingRenames };}describe("BoardApi column mutations", () => {@@ -345,6 +358,158 @@ describe("BoardApi column mutations", () => {* `_template_board` no longer defines the status label, so a board created afterwards has no* definition at all until the board view writes one from the columns it resolved.*/+describe("BoardApi card operations", () => {+ beforeEach(() => {+ vi.mocked(branches.moveBeforeBranch).mockClear();+ vi.mocked(branches.moveAfterBranch).mockClear();+ vi.mocked(note_create.createNote).mockClear();+ });++ /** A board whose second column holds three cards to move among. */+ function createBoardWithCards() {+ const board = buildNote({+ title: "Board",+ children: [+ { title: "First", "#status": "Done" },+ { title: "Second", "#status": "Done" },+ { title: "Third", "#status": "Done" }+ ]+ });++ const items = board.getChildBranches().flatMap(branch => {+ const note = froca.getNoteFromCache(branch.noteId);+ return note ? [ { branch, note } ] : [];+ });+ const byColumn: ColumnMap = new Map([ [ "To Do", [] ], [ "Done", items ] ]);++ return { ...createApi({}, [ "To Do", "Done" ], board, "status", byColumn), items };+ }++ it("files a card moved to another column before the one it was dropped on", async () => {+ const { api, items } = createBoardWithCards();+ const [ first ] = items;++ // The target column is empty, so there is nothing to place it against.+ await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 1, "Done", "To Do");+ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();++ await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 1, "To Do", "Done");+ expect(branches.moveBeforeBranch)+ .toHaveBeenCalledWith([ first.branch.branchId ], items[1].branch.branchId);+ });++ it("reorders within a column, and places past the last card after it", async () => {+ const { api, items } = createBoardWithCards();+ const [ first, , third ] = items;++ await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 2, "Done", "Done");+ expect(branches.moveBeforeBranch)+ .toHaveBeenCalledWith([ first.branch.branchId ], third.branch.branchId);++ await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 3, "Done", "Done");+ expect(branches.moveAfterBranch)+ .toHaveBeenCalledWith([ first.branch.branchId ], third.branch.branchId);+ });++ it("moves nothing for a card dropped where it is, or one it cannot find", async () => {+ const { api, items } = createBoardWithCards();+ const [ first ] = items;++ await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 1, 1, "Done", "Done");+ await api.moveWithinBoard("missingNote", "missingBranch", 0, 2, "Done", "Done");++ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();+ });++ it("takes a card off the board by removing the value it is grouped by", async () => {+ const { api, items } = createBoardWithCards();+ const removeLabel = vi.spyOn(attributes, "removeOwnedLabelByName").mockReturnValue(true);++ await api.removeFromBoard(items[0].note.noteId);+ expect(removeLabel).toHaveBeenCalledWith(items[0].note, "status");++ // A note the cache has never heard of is left alone rather than throwing.+ await api.removeFromBoard("missingNote");+ expect(removeLabel).toHaveBeenCalledTimes(1);+ });++ it("takes a card off a relation board by removing that relation", async () => {+ const board = buildNote({ title: "Board", children: [ { title: "Card" } ] });+ const { api } = createApi({}, [], board, "~status");+ const removeRelation = vi.spyOn(attributes, "removeOwnedRelationByName")+ .mockReturnValue(true);++ await api.removeFromBoard(board.getChildNoteIds()[0]);+ expect(removeRelation).toHaveBeenCalledWith(expect.anything(), "status");+ });++ it("trims the title it renames a card to", async () => {+ const { api, items } = createBoardWithCards();+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);++ await api.renameCard(items[0].note.noteId, " Fresh title ");++ expect(put).toHaveBeenCalledWith(+ "notes/" + items[0].note.noteId + "/title", { title: "Fresh title" });+ });++ it("inserts a card beside another and opens its title for editing", async () => {+ const { api, editing, items } = createBoardWithCards();+ const created = buildNote({ title: "Created" });+ vi.spyOn(server, "put").mockResolvedValue(undefined);+ vi.mocked(note_create.createNote).mockResolvedValue({+ note: created, branch: { branchId: "createdBranch" }+ } as never);++ const note = await api.insertRowAtPosition("Done", items[0].branch.branchId, "after");++ expect(note).toBe(created);+ expect(note_create.createNote).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ targetBranchId: items[0].branch.branchId, target: "after" }));+ expect(editing).toEqual([ "createdBranch" ]);+ });++ it("reports a card it could not create rather than filing nothing", async () => {+ const { api, items } = createBoardWithCards();+ vi.mocked(note_create.createNote).mockResolvedValue({ note: null, branch: null } as never);++ await expect(api.insertRowAtPosition("Done", items[0].branch.branchId, "after"))+ .rejects.toThrow("Failed to create note");+ });++ it("creates a card in a column, and reports a failure without throwing", async () => {+ const { api } = createBoardWithCards();+ const created = buildNote({ title: "Created" });+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);+ vi.mocked(note_create.createNote).mockResolvedValue({+ note: created, branch: { branchId: "createdBranch" }+ } as never);++ await api.createNewItem("Done", "Created");+ expect(put).toHaveBeenCalledWith(+ "notes/" + created.noteId + "/set-attribute",+ expect.objectContaining({ name: "status", value: "Done" }),+ undefined);++ // The board has already drawn the card, so a failure here is logged rather than thrown.+ const logged = vi.spyOn(console, "error").mockImplementation(() => {});+ vi.mocked(note_create.createNote).mockRejectedValueOnce(new Error("offline"));+ await expect(api.createNewItem("Done", "Another")).resolves.toBeUndefined();+ expect(logged).toHaveBeenCalled();+ });++ it("hands the editing state straight through to the board", () => {+ const { api, editing } = createBoardWithCards();++ api.startEditing("someBranch");+ api.dismissEditingTitle();++ expect(editing).toEqual([ "someBranch", undefined ]);+ });+});+describe("BoardApi.addExistingItem", () => {let put: ReturnType<typeof vi.spyOn>;diff --git a/apps/client/src/widgets/collections/board/card.spec.tsx b/apps/client/src/widgets/collections/board/card.spec.tsxindex 613fe53929..94b2fc6b7f 100644--- a/apps/client/src/widgets/collections/board/card.spec.tsx+++ b/apps/client/src/widgets/collections/board/card.spec.tsx@@ -4,23 +4,33 @@*/import { render } from "preact";import { act } from "preact/test-utils";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import appContext from "../../../components/app_context";import Component from "../../../components/component";+import contextMenu from "../../../menus/context_menu";import FAttribute from "../../../entities/fattribute";import froca from "../../../services/froca";import LoadResults from "../../../services/load_results";import noteAttributeCache from "../../../services/note_attribute_cache";+import server from "../../../services/server";import utils from "../../../services/utils";import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";import BoardView from ".";+// The card menu opens with the shared link items, which reach for the active note context.+vi.mock("../../../menus/link_context_menu", () => ({+ default: { getItems: () => [], handleLinkContextMenuItem: () => {} }+}));+describe("Board card", () => {let container: HTMLElement | undefined;/** froca is module-level, so ids are kept distinct rather than reset between tests. */let idSeed = 0;+ beforeEach(() => vi.restoreAllMocks());+afterEach(() => {if (container) {render(null, container);@@ -53,6 +63,88 @@ describe("Board card", () => {expect(cardIcon(first)).toContain("bx-bug");});+ it("opens the note it stands for, by click and by Enter", async () => {+ const { first } = await renderBoard();+ const openInPopup = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);++ await act(async () => { card(first).click(); });+ expect(openInPopup)+ .toHaveBeenCalledWith("openInPopup", { noteIdOrPath: first });++ await act(async () => { press(card(first), "Enter"); });+ expect(openInPopup).toHaveBeenCalledTimes(2);+ });++ it("puts its title into the editor from its button and from F2, and saves it", async () => {+ const { first } = await renderBoard();+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);+ // Held on to: the editor takes the place of the title the lookup goes by.+ const element = card(first);++ await act(async () => { press(element, "F2"); });+ const editor = element.querySelector<HTMLTextAreaElement>("textarea");+ if (!editor) throw new Error("expected the title editor");++ await act(async () => {+ editor.focus();+ editor.value = " Renamed ";+ editor.blur();+ });+ expect(put).toHaveBeenCalledWith(`notes/${first}/title`, { title: "Renamed" });++ // The pencil opens the same editor, without also opening the note underneath it.+ const openInPopup = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);+ await act(async () => { element.querySelector<HTMLElement>(".edit-icon")?.click(); });+ expect(element.querySelector("textarea")).toBeTruthy();+ expect(openInPopup).not.toHaveBeenCalled();+ });++ it("carries its own id and column in the clipboard when a drag starts", async () => {+ const { first } = await renderBoard();+ const clipboard: Record<string, string> = {};+ const dataTransfer = {+ effectAllowed: "",+ setData: (type: string, value: string) => { clipboard[type] = value; }+ };++ await act(async () => { fireDrag(card(first), "dragstart", dataTransfer); });++ expect(JSON.parse(clipboard["trilium/board-card"]))+ .toMatchObject({ noteId: first, fromColumn: "To Do", index: 0 });+ expect(dataTransfer.effectAllowed).toBe("move");++ // Dropping it anywhere clears the drag, which is what un-hides the card.+ await act(async () => { fireDrag(card(first), "dragend", dataTransfer); });+ expect(card(first).className).not.toContain("dragging");+ });++ it("offers the card menu on a right click", async () => {+ const { first } = await renderBoard();+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});++ await act(async () => {+ card(first).dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));+ });++ expect(show).toHaveBeenCalled();+ });++ /** Presses a key on a card, which listens for them to open and to rename. */+ function press(target: HTMLElement, key: string) {+ target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));+ }++ /**+ * happy-dom defines no `ondragstart` on elements, so Preact registers the handler under the+ * prop's own casing rather than the DOM event name (see drag.spec).+ */+ function fireDrag(target: HTMLElement, type: "dragstart" | "dragend", dataTransfer: unknown) {+ const cased = type === "dragstart" ? "DragStart" : "DragEnd";+ const event = new Event(`on${type}` in target ? type : cased, { bubbles: true });+ Object.defineProperty(event, "dataTransfer", { value: dataTransfer, configurable: true });+ target.dispatchEvent(event);+ }+/** Renders a board of two cards and hands back the component their subscriptions register on. */async function renderBoard() {const first = `card${idSeed++}`;@@ -119,7 +211,7 @@ describe("Board card", () => {function card(noteId: string) {const title = froca.notes[noteId]?.title;- const element = [ ...(container?.querySelectorAll(".board-note") ?? []) ]+ const element = [ ...(container?.querySelectorAll<HTMLElement>(".board-note") ?? []) ].find((el) => el.querySelector(".title")?.textContent?.includes(title));if (!element) throw new Error(`no card rendered for ${noteId} ("${title}")`);diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex 0ba51f1640..6d2c512cec 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -3,6 +3,7 @@ import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import contextMenu, { ContextMenuEvent } from "../../../menus/context_menu";+import branches from "../../../services/branches";import dialog from "../../../services/dialog";import FNote from "../../../entities/fnote";import { buildNote } from "../../../test/easy-froca";@@ -160,6 +161,23 @@ describe("Board column context menu", () => {expect(api.addExistingItem).not.toHaveBeenCalled();});+ it("asks before deleting a column, and drops it only once agreed", async () => {+ const api = { removeColumn: vi.fn(async () => {}) } as unknown as BoardApi;+ const confirm = vi.spyOn(dialog, "confirm").mockResolvedValue(false);++ const entry = openMenu(api)+ .find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-trash");+ if (!entry || !("handler" in entry)) throw new Error("expected a delete entry");++ await entry.handler?.(entry, {} as never);+ expect(confirm).toHaveBeenCalled();+ expect(api.removeColumn).not.toHaveBeenCalled();++ confirm.mockResolvedValue(true);+ await entry.handler?.(entry, {} as never);+ expect(api.removeColumn).toHaveBeenCalledWith("To Do");+ });+it("shows the column's own colour as the selected one", async () => {const api = { setColumnColor: vi.fn() } as unknown as BoardApi;const picker = await openPicker(api, "#4d99e6");@@ -187,12 +205,67 @@ describe("Board column context menu", () => {describe("Board item context menu", () => {afterEach(() => vi.restoreAllMocks());- it("marks the archived columns it offers to move a card to", () => {- const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});++ it("inserts a card on either side of the one it was opened on", () => {+ const api = {+ columns: [],+ isColumnArchived: () => false,+ insertRowAtPosition: vi.fn(async () => {})+ } as unknown as BoardApi;+ const items = openItemMenu(api);++ for (const icon of [ "bx bx-list-plus", "bx bx-empty" ]) {+ const entry = items.find(item => item && "uiIcon" in item && item.uiIcon === icon);+ if (!entry || !("handler" in entry)) throw new Error(`expected a ${icon} entry`);+ entry.handler?.(entry, {} as never);+ }++ expect(vi.mocked(api.insertRowAtPosition).mock.calls.map(call => call[2]))+ .toEqual([ "before", "after" ]);+ });++ it("moves the card to the column picked, leaving the one it is in unselectable", () => {const api = {columns: [ "To Do", "Done" ],- isColumnArchived: (column: string) => column === "Done"+ isColumnArchived: () => false,+ changeColumn: vi.fn(async () => {})} as unknown as BoardApi;++ const moveTo = openItemMenu(api)+ .find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-transfer");+ if (!moveTo || !("items" in moveTo)) throw new Error("expected a move-to entry");++ const sides = moveTo.items ?? [];+ expect(sides.map(item => item && "enabled" in item ? item.enabled : undefined))+ .toEqual([ false, true ]);++ const done = sides[1];+ if (done && "handler" in done) done.handler?.(done, {} as never);+ expect(api.changeColumn).toHaveBeenCalledWith(expect.any(String), "Done");+ });++ it("takes the card off the board, and deletes it outright", () => {+ const api = {+ columns: [],+ isColumnArchived: () => false,+ removeFromBoard: vi.fn()+ } as unknown as BoardApi;+ const deleteNotes = vi.spyOn(branches, "deleteNotes").mockResolvedValue(false);++ for (const icon of [ "bx bx-task-x", "bx bx-trash" ]) {+ const entry = openItemMenu(api)+ .find(item => item && "uiIcon" in item && item.uiIcon === icon);+ if (!entry || !("handler" in entry)) throw new Error(`expected a ${icon} entry`);+ entry.handler?.(entry, {} as never);+ }++ expect(api.removeFromBoard).toHaveBeenCalled();+ expect(deleteNotes).toHaveBeenCalledWith([ "branchId" ], false, false);+ });++ /** Opens the menu a card offers, and hands back what it was given to show. */+ function openItemMenu(api: BoardApi) {+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});const event = {preventDefault: () => {},stopPropagation: () => {},@@ -202,8 +275,16 @@ describe("Board item context menu", () => {openNoteContextMenu(api, event, buildNote({ title: "Card" }) as FNote, "branchId", "To Do");- const items = show.mock.calls.at(-1)?.[0].items ?? [];- const moveTo = items.find(item =>+ return show.mock.calls.at(-1)?.[0].items ?? [];+ }++ it("marks the archived columns it offers to move a card to", () => {+ const api = {+ columns: [ "To Do", "Done" ],+ isColumnArchived: (column: string) => column === "Done"+ } as unknown as BoardApi;++ const moveTo = openItemMenu(api).find(item =>item && "uiIcon" in item && item.uiIcon === "bx bx-transfer");if (!moveTo || !("items" in moveTo)) throw new Error("expected a move-to entry");diff --git a/apps/client/src/widgets/collections/board/drag.spec.tsx b/apps/client/src/widgets/collections/board/drag.spec.tsxnew file mode 100644index 0000000000..c232741af2--- /dev/null+++ b/apps/client/src/widgets/collections/board/drag.spec.tsx@@ -0,0 +1,393 @@+/**+ * The board's drag and drop, which is hand-rolled on the HTML5 events rather than a library: a card+ * moved within the board, and a note dragged in from the tree, which is cloned or moved depending on+ * whether the board already holds it.+ */+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../../components/component";+import branches from "../../../services/branches";+import server from "../../../services/server";+import { buildNote } from "../../../test/easy-froca";+import { TREE_CLIPBOARD_TYPE } from "../../note_tree";+import { ParentComponent } from "../../react/react_utils";+import BoardView, { BoardViewData } from ".";+import { CARD_CLIPBOARD_TYPE } from "./card";++vi.mock("../../../services/branches", () => ({+ default: {+ cloneNoteToParentNote: vi.fn(async () => {}),+ cloneNoteAfter: vi.fn(async () => {}),+ moveAfterBranch: vi.fn(async () => {}),+ moveBeforeBranch: vi.fn(async () => {})+ }+}));++/** What Preact registers each handler as where the DOM knows no property of that name. */+const PREACT_DRAG_EVENTS = {+ dragover: "DragOver",+ dragleave: "DragLeave",+ drop: "Drop"+} as const;++describe("Board drag and drop", () => {+ let container: HTMLElement | undefined;++ beforeEach(() => {+ vi.restoreAllMocks();+ vi.mocked(branches.cloneNoteToParentNote).mockClear();+ vi.mocked(branches.cloneNoteAfter).mockClear();+ vi.mocked(branches.moveAfterBranch).mockClear();+ vi.mocked(branches.moveBeforeBranch).mockClear();+ vi.spyOn(server, "put").mockResolvedValue(undefined);+ });++ afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ it("marks the card a drop would land before, from where the pointer is", async () => {+ const { columns } = await renderBoard();++ // Above the middle of the second card, so the drop lands between the two.+ await drag(columns[0], "dragover", { types: [ CARD_CLIPBOARD_TYPE ] }, 120);++ const placeholders = [ ...columns[0].querySelectorAll(".board-column-content > *") ]+ .map(child => child.className);+ expect(placeholders[1]).toContain("board-drop-placeholder");+ });++ it("clears the mark once the pointer leaves the column altogether", async () => {+ const { columns } = await renderBoard();++ await drag(columns[0], "dragover", { types: [ CARD_CLIPBOARD_TYPE ] }, 120);+ expect(columns[0].querySelector(".board-drop-placeholder")).toBeTruthy();++ await drag(columns[0], "dragleave", { types: [] });+ expect(columns[0].querySelector(".board-drop-placeholder")).toBeNull();+ });++ it("ignores a drag carrying something the board has no use for", async () => {+ const { columns } = await renderBoard();++ await drag(columns[0], "dragover", { types: [ "text/uri-list" ] }, 120);++ expect(columns[0].querySelector(".board-drop-placeholder")).toBeNull();+ });++ it("moves a card dropped from another column of the same board", async () => {+ const { columns, cards } = await renderBoard();+ const payload = {+ noteId: cards[0].noteId,+ branchId: cards[0].branchId,+ fromColumn: "To Do",+ index: 0+ };++ await drag(columns[0], "dragover", { types: [ CARD_CLIPBOARD_TYPE ] }, 120);+ await drag(columns[0], "drop", {+ types: [ CARD_CLIPBOARD_TYPE ],+ data: { [CARD_CLIPBOARD_TYPE]: JSON.stringify(payload) }+ });++ expect(branches.moveBeforeBranch)+ .toHaveBeenCalledWith([ cards[0].branchId ], cards[1].branchId);+ });++ it("clones a note dragged in from the tree, which the board does not hold", async () => {+ const { columns } = await renderBoard();+ const stranger = buildNote({ title: "Stranger" });++ await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 0);+ await drag(columns[0], "drop", {+ types: [ TREE_CLIPBOARD_TYPE ],+ data: { text: JSON.stringify([ { noteId: stranger.noteId, branchId: "strangerBranch" } ]) }+ });++ // Dropped above every card, so it goes in as the first rather than after one.+ expect(branches.cloneNoteToParentNote).toHaveBeenCalledWith(stranger.noteId, expect.any(String));+ expect(branches.cloneNoteAfter).not.toHaveBeenCalled();+ });++ it("clones it after the card it was dropped below", async () => {+ const { columns } = await renderBoard();+ const stranger = buildNote({ title: "Stranger" });++ await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 120);+ await drag(columns[0], "drop", {+ types: [ TREE_CLIPBOARD_TYPE ],+ data: { text: JSON.stringify([ { noteId: stranger.noteId, branchId: "strangerBranch" } ]) }+ });++ expect(branches.cloneNoteAfter).toHaveBeenCalled();+ expect(branches.cloneNoteToParentNote).not.toHaveBeenCalled();+ });++ it("moves rather than clones a note the board already holds", async () => {+ const { columns, cards } = await renderBoard();++ await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 120);+ await drag(columns[0], "drop", {+ types: [ TREE_CLIPBOARD_TYPE ],+ data: { text: JSON.stringify([ { noteId: cards[0].noteId, branchId: cards[0].branchId } ]) }+ });++ expect(branches.moveAfterBranch).toHaveBeenCalled();+ expect(branches.cloneNoteToParentNote).not.toHaveBeenCalled();+ expect(branches.cloneNoteAfter).not.toHaveBeenCalled();+ });++ it("does nothing for a drop carrying nothing it can read", async () => {+ const { columns } = await renderBoard();++ await drag(columns[0], "dragover", { types: [ CARD_CLIPBOARD_TYPE ] }, 120);+ await drag(columns[0], "drop", {+ types: [ CARD_CLIPBOARD_TYPE ],+ data: { [CARD_CLIPBOARD_TYPE]: "not json at all" }+ });+ await drag(columns[0], "drop", { types: [ CARD_CLIPBOARD_TYPE ], data: {} });++ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();+ });++ /** A board of one column holding two cards, each given a height the pointer can be placed in. */+ async function renderBoard() {+ const note = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "First", "#status": "To Do" },+ { title: "Second", "#status": "To Do" }+ ]+ });++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ await act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <BoardView+ note={note}+ notePath={`root/${note.noteId}`}+ noteIds={[ ...note.getChildNoteIds() ]}+ highlightedTokens={null}+ viewConfig={{ columns: [ { value: "To Do" } ] }}+ saveConfig={() => {}}+ media="screen"+ onReady={() => {}}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await settle();++ const columns = [ ...mountPoint.querySelectorAll<HTMLElement>(".board-column") ];+ // happy-dom lays nothing out, so the cards are given the geometry the drop maths reads.+ for (const [ index, card ] of [ ...columns[0].querySelectorAll(".board-note") ].entries()) {+ card.getBoundingClientRect = () => ({+ top: index * 100, height: 100+ }) as DOMRect;+ }++ const cards = note.getChildBranches()+ .map(branch => ({ noteId: branch.noteId, branchId: branch.branchId }));++ return { note, columns, cards };+ }++ /** Dispatches one of the drag events, with the clipboard the board reads its payload from. */+ async function drag(+ target: HTMLElement,+ type: "dragover" | "dragleave" | "drop",+ clipboard: { types: string[], data?: Record<string, string> },+ clientY = 0+ ) {+ // happy-dom defines no `ondragover`/`ondrop` on elements, and Preact falls back to the prop's+ // own casing when the DOM does not know the lowercase one. A `dragover` would reach nothing.+ const known = `on${type}` in document.createElement("div");+ const event = new Event(known ? type : PREACT_DRAG_EVENTS[type], {+ bubbles: true,+ cancelable: true+ });+ // Defined rather than assigned: these are accessors on the event, which a plain assignment+ // does not get past.+ for (const [ name, value ] of Object.entries({+ clientY,+ relatedTarget: null,+ dataTransfer: {+ types: clipboard.types,+ getData: (dataType: string) => clipboard.data?.[dataType] ?? ""+ }+ })) {+ Object.defineProperty(event, name, { value, configurable: true });+ }++ await act(async () => {+ target.dispatchEvent(event);+ await settle();+ });+ }++ function settle() {+ return new Promise((resolve) => setTimeout(resolve));+ }+});++describe("Board column reordering", () => {+ let container: HTMLElement | undefined;+ const saved: BoardViewData[] = [];++ beforeEach(() => {+ saved.length = 0;+ vi.spyOn(server, "put").mockResolvedValue(undefined);+ });++ afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ it("drops a column to the right of the one it was let go over", async () => {+ const { columns, board } = await renderColumns();++ await dragColumn(columns[0], "dragstart");+ // Past the middle of the last column, which spans 200 to 300, so it lands after it.+ await dragColumn(columns[2], "dragover", 280);+ await dragColumn(board, "drop");++ expect(saved.at(-1)?.columns?.map(column => column.value))+ .toEqual([ "Doing", "Done", "To Do" ]);+ });++ it("drops it to the left when let go over the first half of a column", async () => {+ const { columns, board } = await renderColumns();++ await dragColumn(columns[2], "dragstart");+ // Short of the middle of the second column, which spans 100 to 200.+ await dragColumn(columns[1], "dragover", 120);+ await dragColumn(board, "drop");++ expect(saved.at(-1)?.columns?.map(column => column.value))+ .toEqual([ "To Do", "Done", "Doing" ]);+ });++ it("hides the column being dragged, and shows it again once let go", async () => {+ const { columns } = await renderColumns();++ await dragColumn(columns[0], "dragstart");+ expect(columns[0].style.display).toBe("none");++ await dragColumn(columns[0], "dragend");+ expect(columns[0].style.display).not.toBe("none");+ });++ it("saves nothing for a column let go where it already was", async () => {+ const { columns, board } = await renderColumns();++ await dragColumn(columns[1], "dragstart");+ await dragColumn(columns[1], "dragover", 120);+ await dragColumn(board, "drop");++ expect(saved).toHaveLength(0);+ });++ /** A board of three columns, each given the geometry the drop maths reads. */+ async function renderColumns() {+ const note = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "First", "#status": "To Do" },+ { title: "Second", "#status": "Doing" },+ { title: "Third", "#status": "Done" }+ ]+ });++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ await act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <BoardView+ note={note}+ notePath={`root/${note.noteId}`}+ noteIds={[ ...note.getChildNoteIds() ]}+ highlightedTokens={null}+ viewConfig={{+ columns: [ { value: "To Do" }, { value: "Doing" }, { value: "Done" } ]+ }}+ saveConfig={(config) => saved.push(config)}+ media="screen"+ onReady={() => {}}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await settle();++ const columns = [ ...mountPoint.querySelectorAll<HTMLElement>(".board-column") ];+ for (const [ index, column ] of columns.entries()) {+ column.getBoundingClientRect = () => ({+ left: index * 100, width: 100+ }) as DOMRect;+ }++ const board = mountPoint.querySelector<HTMLElement>(".board-view-container");+ if (!board) throw new Error("expected the board container");++ return { columns, board };+ }++ /** Drags by the header, which is the handle, and drops on the board the columns stand in. */+ async function dragColumn(+ target: HTMLElement,+ type: "dragstart" | "dragover" | "dragend" | "drop",+ clientX = 0+ ) {+ const cased = {+ dragstart: "DragStart", dragover: "DragOver", dragend: "DragEnd", drop: "Drop"+ }[type];+ const event = new Event(`on${type}` in target ? type : cased, {+ bubbles: true,+ cancelable: true+ });++ for (const [ name, value ] of Object.entries({+ clientX,+ dataTransfer: { effectAllowed: "", types: [], setData: () => {}, getData: () => "" }+ })) {+ Object.defineProperty(event, name, { value, configurable: true });+ }++ const from = type === "dragstart" || type === "dragend"+ ? target.querySelector("h3") ?? target+ : target;++ await act(async () => {+ from.dispatchEvent(event);+ await settle();+ });+ }++ function settle() {+ return new Promise((resolve) => setTimeout(resolve));+ }+});