Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: implement a custom drag and drop mechanism for cards and columns

Adorian Doran088cc8b6704e
diff --git a/apps/client/src/widgets/collections/board/board_drag.spec.tsx b/apps/client/src/widgets/collections/board/board_drag.spec.tsx
new file mode 100644
index 0000000000..f6069aa649
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/board_drag.spec.tsx
@@ -0,0 +1,657 @@
+import { render } from "preact";
+import { useRef } from "preact/hooks";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { type BoardDragCallbacks, type DropPosition, useBoardDrag } from "./board_drag";
+
+describe("useBoardDrag, carrying a card", () => {
+ let container: HTMLElement | undefined;
+ let board: HTMLElement;
+ let calls: {
+ start: unknown[],
+ move: { position: unknown | null, inside: boolean }[],
+ end: { card: unknown, position: unknown }[],
+ columnStart: { column: string, index: number, size: unknown }[],
+ columnMove: (number | null)[],
+ columnEnd: { from: number, to: number | null }[]
+ };
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ calls = {
+ start: [], move: [], end: [], columnStart: [], columnMove: [], columnEnd: []
+ };
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ it("takes hold once the mouse has moved, and not before", () => {
+ setup();
+
+ press(card("n1"), 50, 60);
+ expect(calls.start).toHaveLength(0);
+
+ // Within the threshold: still a click, not a drag.
+ move(52, 60);
+ expect(calls.start).toHaveLength(0);
+
+ move(70, 60);
+ expect(calls.start)
+ .toEqual([ { noteId: "n1", fromColumn: "To Do", index: 0, height: 50 } ]);
+ });
+
+ it("carries a copy under the pointer without redrawing the board", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 50, 60);
+ move(90, 90);
+ act(() => { vi.advanceTimersByTime(20); });
+
+ // Shrunk as it is carried, written with the movement so neither can overwrite the other.
+ expect(preview()?.style.transform).toBe("translate3d(40px, 30px, 0) scale(0.9)");
+ // The card itself is left where it stands, and is not the thing being moved.
+ expect(element.style.transform).toBe("");
+ });
+
+ /**
+ * The copy stands inside the board, so the board's own styling reaches it, and is placed
+ * against the window, which the column's scrolling cannot cut off.
+ */
+ it("lifts the copy out of the column and hides the card behind it", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 50, 60);
+ move(90, 90);
+
+ const copy = preview();
+ // In the layer, not among the board's own children, which Preact places.
+ expect(copy?.parentElement).toBe(layer());
+ expect(copy?.className).toContain("board-note");
+ expect(copy?.style.width).toBe("100px");
+ expect(copy?.style.left).toBe("0px");
+ // Only one card answers to the id, so nothing looking one up finds the copy.
+ expect(copy?.getAttribute("data-note-id")).toBeNull();
+ // What the card offers is left behind with it.
+ expect(copy?.querySelector(".edit-icon")).toBeNull();
+ expect(element.querySelector(".edit-icon")).not.toBeNull();
+ expect(element.style.display).toBe("none");
+ });
+
+ it("puts the card back and takes the copy away once the gesture is over", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 50, 60);
+ move(90, 90);
+ release(90, 90);
+
+ expect(preview()).toBeNull();
+ expect(element.style.display).toBe("");
+ });
+
+ it("reports where the card would land, and only when that changes", () => {
+ setup();
+
+ press(card("n1"), 50, 60);
+ // Taken 20 below its own top edge, so its top stands at 80 on the page, which is 40 into
+ // the card area: past the first card's middle at 25 and above the second's at 85.
+ move(120, 100);
+ act(() => { vi.advanceTimersByTime(20); });
+ expect(calls.move.at(-1)?.position).toEqual({ column: "To Do", index: 1 });
+
+ // Still over the same place: nothing is reported again.
+ const reported = calls.move.length;
+ move(122, 102);
+ act(() => { vi.advanceTimersByTime(20); });
+ expect(calls.move).toHaveLength(reported);
+
+ // Over the second column, below its only card's middle.
+ move(320, 200);
+ act(() => { vi.advanceTimersByTime(20); });
+ expect(calls.move.at(-1)?.position).toEqual({ column: "Doing", index: 1 });
+ });
+
+ /**
+ * The columns run 0 to 100 and 200 to 300, so 100 to 200 is between them and is answered for by
+ * the nearer of the two without the card standing on either. Only resting on one opens a
+ * collapsed column, which is why the two are told apart.
+ */
+ it("says whether the card stands on the column or merely nearest to it", () => {
+ setup();
+ const reported = () => calls.move.at(-1);
+
+ press(card("n1"), 50, 60);
+
+ // Between them, nearer the second.
+ move(170, 100);
+ act(() => { vi.advanceTimersByTime(600); });
+ expect(reported()).toMatchObject({ position: { column: "Doing" }, inside: false });
+
+ // Past the last column, which still answers for it so the card has somewhere to go.
+ move(320, 100);
+ act(() => { vi.advanceTimersByTime(600); });
+ expect(reported()).toMatchObject({ position: { column: "Doing" }, inside: false });
+
+ // Standing on it at last, once it has rested there.
+ move(250, 100);
+ act(() => { vi.advanceTimersByTime(600); });
+ expect(reported()).toMatchObject({ position: { column: "Doing" }, inside: true });
+ });
+
+ /** Crossing a column on the way somewhere else leaves it as it was found. */
+ it("counts a rest on the column, not a passage over it", () => {
+ setup();
+
+ press(card("n1"), 50, 60);
+ move(250, 100);
+ act(() => { vi.advanceTimersByTime(200); });
+ expect(calls.move.at(-1)).toMatchObject({ inside: false });
+
+ // Off again before the rest was long enough, so the column it crossed was never stood on.
+ // Where it came to rest instead is its own affair, and does count.
+ move(50, 100);
+ act(() => { vi.advanceTimersByTime(600); });
+ expect(calls.move.filter(call =>
+ call.inside && (call.position as DropPosition | null)?.column === "Doing")).toEqual([]);
+ expect(calls.move.at(-1)).toMatchObject({ position: { column: "To Do" }, inside: true });
+ });
+
+ /** The empty space below a collapsed column's heading is not the column. */
+ it("does not count the space below a column that is shorter than the board", () => {
+ setup();
+ // A strip, as a collapsed column is drawn: only as tall as its heading.
+ const strip = board.querySelectorAll<HTMLElement>(".board-column")[1];
+ strip.getBoundingClientRect = () => ({
+ left: 200, top: 0, width: 100, height: 80, right: 300, bottom: 80
+ }) as DOMRect;
+
+ press(card("n1"), 50, 60);
+ // Held over it, but below where it ends: still the column it would land in, not stood on.
+ move(250, 300);
+ act(() => { vi.advanceTimersByTime(600); });
+ expect(calls.move.at(-1)).toMatchObject({ position: { column: "Doing" }, inside: false });
+
+ // Brought up onto the heading itself.
+ move(250, 60);
+ act(() => { vi.advanceTimersByTime(600); });
+ expect(calls.move.at(-1)).toMatchObject({ inside: true });
+ });
+
+ /**
+ * The reader takes hold of a card wherever they press, and it is the card's own top edge the
+ * gap opens at. Held low in a tall card, the pointer is well below where the card's top sits.
+ */
+ it("places the card by its top edge, not by where it was taken hold of", () => {
+ setup();
+
+ // Taken by its very bottom, so its top stands 48 above the pointer from here on.
+ press(card("n1"), 50, 88);
+ move(50, 150);
+ act(() => { vi.advanceTimersByTime(20); });
+ const heldLow = calls.move.at(-1)?.position;
+
+ release(50, 150);
+ calls.move.length = 0;
+
+ // Taken by its very top: the same pointer place leaves its top far lower down.
+ press(card("n1"), 50, 42);
+ move(50, 150);
+ act(() => { vi.advanceTimersByTime(20); });
+
+ // One pointer place, two grips, and the card lands where the card is rather than where the
+ // pointer is: taken by its foot it sits a place higher than taken by its head.
+ expect(heldLow).toEqual({ column: "To Do", index: 1 });
+ expect(calls.move.at(-1)?.position).toEqual({ column: "To Do", index: 2 });
+ });
+
+ /** Held at the board's edge, the board walks along under what is carried. */
+ it("walks the board along while a card is held at its edge", () => {
+ setup();
+ // The board runs to 500 on screen and holds twice that.
+ Object.defineProperty(board, "clientWidth", { value: 500, configurable: true });
+ Object.defineProperty(board, "scrollWidth", { value: 1000, configurable: true });
+ board.scrollLeft = 100;
+
+ press(card("n1"), 50, 60);
+ move(490, 100);
+ act(() => { vi.advanceTimersByTime(200); });
+
+ expect(board.scrollLeft).toBeGreaterThan(100);
+ });
+
+ it("stops walking it once the gesture is over", () => {
+ setup();
+ Object.defineProperty(board, "clientWidth", { value: 500, configurable: true });
+ Object.defineProperty(board, "scrollWidth", { value: 1000, configurable: true });
+ board.scrollLeft = 100;
+
+ press(card("n1"), 50, 60);
+ move(490, 100);
+ act(() => { vi.advanceTimersByTime(100); });
+ release(490, 100);
+
+ const reached = board.scrollLeft;
+ act(() => { vi.advanceTimersByTime(500); });
+ expect(board.scrollLeft).toBe(reached);
+ });
+
+ it("hands the last place it reported to the drop", () => {
+ setup();
+
+ press(card("n1"), 50, 60);
+ move(320, 200);
+ act(() => { vi.advanceTimersByTime(20); });
+ release(320, 200);
+
+ expect(calls.end).toEqual([ {
+ card: { noteId: "n1", fromColumn: "To Do", index: 0, height: 50 },
+ position: { column: "Doing", index: 1 }
+ } ]);
+ });
+
+ /** A finger resting is a drag; a finger moving off is the column being scrolled. */
+ it("waits for a finger to rest before carrying anything", () => {
+ setup();
+
+ press(card("n1"), 100, 100, "touch");
+ expect(calls.start).toHaveLength(0);
+
+ act(() => { vi.advanceTimersByTime(399); });
+ expect(calls.start).toHaveLength(0);
+
+ act(() => { vi.advanceTimersByTime(2); });
+ expect(calls.start).toHaveLength(1);
+ });
+
+ it("lets a finger that moves off scroll instead of carrying the card", () => {
+ setup();
+
+ press(card("n1"), 100, 100, "touch");
+ move(100, 140);
+ act(() => { vi.advanceTimersByTime(1000); });
+
+ expect(calls.start).toHaveLength(0);
+ expect(calls.end).toHaveLength(0);
+ });
+
+ /** The same press carries the card, so the menu it would otherwise open is left out. */
+ /** A press that never became a drag is a click, and the click has to reach what was pressed. */
+ it("takes the pointer only once something is being carried", () => {
+ setup();
+ const captured: number[] = [];
+ board.setPointerCapture = (id: number) => { captured.push(id); };
+
+ press(card("n1"), 50, 60);
+ expect(captured).toEqual([]);
+
+ move(90, 90);
+ expect(captured).toEqual([ 1 ]);
+ });
+
+ /** A tap asks for the menu, the long press being how a finger picks a card up instead. */
+ it("asks a card for its menu when it is tapped", () => {
+ setup();
+ const element = card("n1");
+ const menus: string[] = [];
+ element.addEventListener("contextmenu", () => menus.push("card"));
+
+ press(element, 50, 60, "touch");
+ release(50, 62, "touch");
+
+ expect(menus).toEqual([ "card" ]);
+ });
+
+ /** The heading answers for a column's menu, the column itself holding no handler. */
+ it("asks a column's heading for its menu when it is tapped", () => {
+ setup();
+ const heading = board.querySelector<HTMLElement>(".board-column h3");
+ if (!heading) throw new Error("expected a heading");
+ const menus: string[] = [];
+ heading.addEventListener("contextmenu", () => menus.push("heading"));
+
+ press(heading, 10, 10, "touch");
+ release(11, 11, "touch");
+
+ expect(menus).toEqual([ "heading" ]);
+ });
+
+ it("leaves the click a tap also lands unanswered", () => {
+ setup();
+ const element = card("n1");
+ const clicks: boolean[] = [];
+ board.addEventListener("click", (event) => clicks.push(event.defaultPrevented));
+
+ press(element, 50, 60, "touch");
+ release(50, 62, "touch");
+ act(() => {
+ element.dispatchEvent(new Event("click", { bubbles: true, cancelable: true }));
+ });
+
+ expect(clicks).toEqual([]);
+ });
+
+ /**
+ * A browser follows a tap with mouse events for pages that know nothing of touch. They land on
+ * the menu the tap just opened, right under the finger, and the first of them takes it back off
+ * again. They are made from `touchend`, so that is where they are refused.
+ */
+ it("refuses the mouse events a browser would make from a tap", () => {
+ setup();
+
+ press(card("n1"), 50, 60, "touch");
+ release(50, 62, "touch");
+
+ const followed = new Event("touchend", { bubbles: true, cancelable: true });
+ act(() => { document.dispatchEvent(followed); });
+ expect(followed.defaultPrevented).toBe(true);
+
+ // Once only: the next touch of the reader's own is theirs to have.
+ const later = new Event("touchend", { bubbles: true, cancelable: true });
+ act(() => { document.dispatchEvent(later); });
+ expect(later.defaultPrevented).toBe(false);
+ });
+
+ /** A press that became a drag is not a tap, and its `touchend` is the browser's to answer. */
+ it("leaves the touch that carried a card alone", () => {
+ setup();
+
+ press(card("n1"), 50, 60, "touch");
+ act(() => { vi.advanceTimersByTime(500); });
+ move(250, 100);
+ release(250, 100, "touch");
+
+ const followed = new Event("touchend", { bubbles: true, cancelable: true });
+ act(() => { document.dispatchEvent(followed); });
+ expect(followed.defaultPrevented).toBe(false);
+ });
+
+ it("leaves a mouse click alone, which is not a tap", () => {
+ setup();
+ const element = card("n1");
+ const menus: string[] = [];
+ element.addEventListener("contextmenu", () => menus.push("card"));
+
+ press(element, 50, 60);
+ release(50, 60);
+
+ expect(menus).toEqual([]);
+ });
+
+ it("keeps a finger's press from opening the menu as well", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 100, 100, "touch");
+ const swallowed = new Event("contextmenu", { bubbles: true, cancelable: true });
+ act(() => { element.dispatchEvent(swallowed); });
+ expect(swallowed.defaultPrevented).toBe(true);
+ });
+
+ it("leaves a right click's menu alone", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 50, 60);
+ const allowed = new Event("contextmenu", { bubbles: true, cancelable: true });
+ act(() => { element.dispatchEvent(allowed); });
+ expect(allowed.defaultPrevented).toBe(false);
+ });
+
+ /** A column heading's menu is the only way to reach what it offers on a touch screen. */
+ it("leaves a press away from a card with its menu", () => {
+ setup();
+ const heading = board.querySelector<HTMLElement>(".board-column");
+ if (!heading) throw new Error("expected a column");
+
+ press(heading, 50, 60, "touch");
+ const allowed = new Event("contextmenu", { bubbles: true, cancelable: true });
+ act(() => { heading.dispatchEvent(allowed); });
+ expect(allowed.defaultPrevented).toBe(false);
+ });
+
+ it("calls the gesture off on Escape, with nowhere to land", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 50, 60);
+ move(320, 200);
+ act(() => { vi.advanceTimersByTime(20); });
+
+ act(() => {
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ });
+
+ expect(calls.end).toEqual([ {
+ card: { noteId: "n1", fromColumn: "To Do", index: 0, height: 50 },
+ position: null
+ } ]);
+ expect(element.style.transform).toBe("");
+ });
+
+ it("calls the gesture off when the pointer is taken away", () => {
+ setup();
+
+ press(card("n1"), 50, 60);
+ move(320, 200);
+ act(() => { vi.advanceTimersByTime(20); });
+ act(() => { board.dispatchEvent(pointer("pointercancel", 320, 200, "mouse")); });
+
+ expect(calls.end.at(-1)).toMatchObject({ position: null });
+ });
+
+ it("says nothing at all for a press that never became a drag", () => {
+ setup();
+
+ press(card("n1"), 50, 60);
+ release(100, 100);
+
+ expect(calls.start).toHaveLength(0);
+ expect(calls.end).toHaveLength(0);
+ });
+
+ /** The card's own controls keep their press: an editor is not a handle. */
+ it("leaves a press on something the card offers alone", () => {
+ setup();
+ const element = card("n1");
+ const button = document.createElement("button");
+ element.appendChild(button);
+
+ press(button, 50, 60);
+ move(200, 100);
+
+ expect(calls.start).toHaveLength(0);
+ });
+
+ it("offers nothing while it is switched off", () => {
+ setup({ disabled: true });
+
+ press(card("n1"), 50, 60);
+ move(200, 100);
+
+ expect(calls.start).toHaveLength(0);
+ });
+
+ describe("carrying a column", () => {
+ it("takes hold of it by its heading, and says what it measures", () => {
+ setup();
+
+ press(heading(0), 10, 10);
+ move(120, 10);
+
+ expect(calls.columnStart)
+ .toEqual([ { column: "To Do", index: 0, size: { width: 100, height: 400 } } ]);
+ // Nothing was taken for a card, the press having landed on the heading.
+ expect(calls.start).toHaveLength(0);
+ });
+
+ it("cuts the copy it carries to a set height", () => {
+ setup();
+ const column = board.querySelector<HTMLElement>(".board-column");
+
+ press(heading(0), 10, 10);
+ move(120, 10);
+
+ const copy = board.querySelector<HTMLElement>(".board-column.board-drag-preview");
+ expect(copy?.style.height).toBe("150px");
+ expect(copy?.style.width).toBe("100px");
+ expect(column?.style.display).toBe("none");
+ });
+
+ it("reports the place it would take, counting the columns as they stand", () => {
+ setup();
+
+ press(heading(0), 10, 10);
+ // The column's middle stands 40 right of the pointer, and short of the second
+ // column's own middle at 250.
+ move(200, 10);
+ act(() => { vi.advanceTimersByTime(20); });
+ expect(calls.columnMove.at(-1)).toBe(1);
+
+ move(280, 10);
+ act(() => { vi.advanceTimersByTime(20); });
+ expect(calls.columnMove.at(-1)).toBe(2);
+
+ release(280, 10);
+ expect(calls.columnEnd).toEqual([ { from: 0, to: 2 } ]);
+ });
+
+ it("hands back nothing for a gesture called off", () => {
+ setup();
+
+ press(heading(0), 10, 10);
+ move(280, 10);
+ act(() => {
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ });
+
+ expect(calls.columnEnd).toEqual([ { from: 0, to: null } ]);
+ expect(board.querySelector(".board-drag-preview")).toBeNull();
+ });
+
+ function heading(index: number) {
+ const element = [ ...board.querySelectorAll<HTMLElement>(".board-column h3") ][index];
+ if (!element) throw new Error(`no heading ${index}`);
+ return element;
+ }
+ });
+
+ /**
+ * Two 100px columns, 200 apart, each card 50 tall. The first holds two cards, the second one.
+ * happy-dom lays nothing out, so every box is declared.
+ */
+ function setup({ disabled = false } = {}) {
+ const mountPoint = document.createElement("div");
+ container = mountPoint;
+ document.body.appendChild(mountPoint);
+
+ const callbacks: BoardDragCallbacks = {
+ onCardStart: (card) => calls.start.push(card),
+ onCardMove: (position, inside) => calls.move.push({ position, inside }),
+ onCardEnd: (card, position) => calls.end.push({ card, position }),
+ onColumnStart: (column, index, size) => calls.columnStart.push({ column, index, size }),
+ onColumnMove: (index) => calls.columnMove.push(index),
+ onColumnEnd: (from, to) => calls.columnEnd.push({ from, to })
+ };
+
+ function Harness() {
+ const ref = useRef<HTMLDivElement>(null);
+ useBoardDrag(ref, callbacks, disabled);
+ return <div ref={ref} className="board-view-container" />;
+ }
+
+ act(() => { render(<Harness />, mountPoint); });
+ board = mountPoint.firstElementChild as HTMLElement;
+ board.appendChild(Object.assign(document.createElement("div"), {
+ className: "board-drag-layer"
+ }));
+ place(board, 0, 0, 500, 400);
+ // Writable: the board walks itself along while something is held at its edge.
+ Object.defineProperty(board, "scrollLeft", { value: 0, configurable: true, writable: true });
+
+ for (const [ index, cards ] of [ [ "n1", "n2" ], [ "n3" ] ].entries()) {
+ const column = document.createElement("div");
+ column.className = "board-column";
+ column.dataset.column = [ "To Do", "Doing" ][index];
+ board.appendChild(column);
+ place(column, index * 200, 0, 100, 400);
+
+ const heading = document.createElement("h3");
+ column.appendChild(heading);
+ place(heading, index * 200, 0, 100, 40);
+
+ const area = document.createElement("div");
+ area.className = "board-column-content";
+ column.appendChild(area);
+ place(area, index * 200, 40, 100, 360);
+ Object.defineProperty(area, "scrollTop", {
+ value: 0, configurable: true, writable: true
+ });
+
+ for (const [ position, noteId ] of cards.entries()) {
+ const note = document.createElement("div");
+ note.className = "board-note";
+ note.dataset.noteId = noteId;
+ note.appendChild(Object.assign(document.createElement("span"), {
+ className: "edit-icon"
+ }));
+ area.appendChild(note);
+ place(note, index * 200, 40 + position * 60, 100, 50);
+ }
+ }
+
+ // Attached from an effect, which Preact defers past the render.
+ act(() => { vi.advanceTimersByTime(20); });
+ }
+
+ function preview() {
+ return board.querySelector<HTMLElement>(".board-drag-preview");
+ }
+
+ function layer() {
+ return board.querySelector<HTMLElement>(".board-drag-layer");
+ }
+
+ function card(noteId: string) {
+ const element = board.querySelector<HTMLElement>(`.board-note[data-note-id="${noteId}"]`);
+ if (!element) throw new Error(`no card ${noteId}`);
+ return element;
+ }
+
+ function place(element: HTMLElement, left: number, top: number, width: number, height: number) {
+ element.getBoundingClientRect = () => ({
+ left, top, width, height, right: left + width, bottom: top + height
+ }) as DOMRect;
+ }
+
+ function pointer(type: string, clientX: number, clientY: number, pointerType: string) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ for (const [ name, value ] of Object.entries({
+ clientX, clientY, pointerId: 1, button: 0, pointerType
+ })) {
+ Object.defineProperty(event, name, { value, configurable: true });
+ }
+ return event;
+ }
+
+ function press(target: HTMLElement, x: number, y: number, pointerType = "mouse") {
+ act(() => { target.dispatchEvent(pointer("pointerdown", x, y, pointerType)); });
+ }
+
+ function move(x: number, y: number, pointerType = "mouse") {
+ act(() => { board.dispatchEvent(pointer("pointermove", x, y, pointerType)); });
+ }
+
+ function release(x: number, y: number, pointerType = "mouse") {
+ act(() => { board.dispatchEvent(pointer("pointerup", x, y, pointerType)); });
+ }
+});
diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.ts
new file mode 100644
index 0000000000..fafb8b2b19
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/board_drag.ts
@@ -0,0 +1,553 @@
+import { RefObject } from "preact";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+import { useTrackedElement } from "../../react/hooks";
+import { cardInsertionIndex, columnAt, columnCovers, columnInsertionIndex } from "./drag_geometry";
+import { type BoardMeasurement, measureBoard, toAreaY, toBoardX } from "./drag_measure";
+import { createEdgeScroller, type ScrollTarget } from "./edge_scroll";
+
+/** How far a pointer travels before a press with a button held is taken for a drag. */
+const MOUSE_THRESHOLD = 4;
+
+/** How long a finger rests before its press is taken for a drag. */
+const TOUCH_DELAY_MS = 400;
+
+/** How far a finger may stray in that time and still be resting rather than scrolling. */
+const TOUCH_TOLERANCE = 8;
+
+/** How much a carried card shrinks. Written with the movement, a class could not add to it. */
+const DRAG_SCALE = 0.9;
+
+/** How tall a carried column stands, whatever it holds, so it can be seen past. */
+const COLUMN_DRAG_HEIGHT = 150;
+
+/** How long a card rests on a column's heading before it counts as standing there. */
+const DWELL_MS = 500;
+
+/** How long the mouse events a browser makes from a tap can take to arrive. */
+const COMPATIBILITY_WINDOW_MS = 700;
+
+/** Which card is being carried, named the way the board's own moves are. */
+export interface DraggedCard {
+ noteId: string;
+ fromColumn: string;
+ index: number;
+ /** How tall it stands, so the gap held open for it is the size it will fill. */
+ height: number;
+}
+
+/** Where the card would land. */
+export interface DropPosition {
+ column: string;
+ index: number;
+}
+
+export interface BoardDragCallbacks {
+ /** A card has been taken hold of, and is now being carried. */
+ onCardStart(card: DraggedCard): void;
+ /**
+ * Where the card would land has changed, or it is over nowhere it could land.
+ *
+ * @param inside whether the card has come to rest on the column itself, rather than merely
+ * being nearest to it or passing over it. A column claims the gap beside it so that a card held
+ * there still has somewhere to go, and a collapsed one claims the empty space below its
+ * heading; neither is reason enough to open it, and nor is crossing the heading on the way
+ * somewhere else.
+ */
+ onCardMove(position: DropPosition | null, inside: boolean): void;
+ /**
+ * The gesture is over. A position means let go somewhere; nothing means it was called off, by
+ * Escape or by the pointer being taken away.
+ */
+ onCardEnd(card: DraggedCard, position: DropPosition | null): void;
+ /**
+ * A column has been taken hold of by its heading.
+ *
+ * @param size what it measures, so the gap held open for it is the size it will land in.
+ */
+ onColumnStart(column: string, index: number, size: { width: number, height: number }): void;
+ /** Which place among the columns it would take, counting them as they stand. */
+ onColumnMove(index: number | null): void;
+ /** As {@link onCardEnd}, for a column: a place means let go, nothing means called off. */
+ onColumnEnd(from: number, to: number | null): void;
+}
+
+/**
+ * Carries a card or a column around the board under the pointer.
+ *
+ * A mouse takes hold as soon as it moves with a button down; a finger has to rest first, so that a
+ * swipe still scrolls the column it started in. Everything the gesture needs is measured when it
+ * starts, so a move reads two rectangles rather than one for every card on the board.
+ *
+ * What is carried is a copy, placed against the window: a card is carried past the edges of the
+ * column holding it, which scrolls, and would be cut off at them.
+ *
+ * @param containerRef the board's scrolling container.
+ * @param callbacks what to do as the gesture opens, moves and closes.
+ * @param disabled whether to leave presses alone.
+ */
+export function useBoardDrag(
+ containerRef: RefObject<HTMLElement>,
+ callbacks: BoardDragCallbacks,
+ disabled = false
+) {
+ const [ isDragging, setDragging ] = useState(false);
+ // Held in a ref rather than in state: every move reads them, and none of them draw anything.
+ const gesture = useRef<Gesture | null>(null);
+ const latest = useRef(callbacks);
+ latest.current = callbacks;
+ // The board draws its container only once the notes have loaded, and filling a ref triggers no
+ // render, so an effect reading the ref alone would never hear it arrive.
+ const container = useTrackedElement(containerRef);
+
+ useEffect(() => {
+ if (!container || disabled) return;
+
+ // Walks the board along, and the column's cards up and down, while what is carried is held
+ // near an edge. Each frame that moves anything reads the point again, since what is under
+ // the pointer has changed without the pointer itself moving.
+ const scroller = createEdgeScroller({
+ onScroll: () => {
+ const held = gesture.current;
+ if (held?.active) {
+ resolve(held);
+ }
+ }
+ });
+
+ const close = (cancelled: boolean) => {
+ const held = gesture.current;
+ gesture.current = null;
+ if (!held) return;
+
+ window.clearTimeout(held.timer);
+ window.clearTimeout(held.dwell);
+ scroller.stop();
+ container.classList.remove("board-dragging");
+ held.preview?.remove();
+ held.element.style.display = "";
+ if (held.frame !== undefined) {
+ cancelAnimationFrame(held.frame);
+ }
+ if (!held.active) return;
+
+ setDragging(false);
+ if (held.kind === "card") {
+ latest.current.onCardEnd(held.card, cancelled ? null : held.position);
+ } else {
+ latest.current.onColumnEnd(held.index, cancelled ? null : held.target);
+ }
+ };
+
+ const activate = () => {
+ const held = gesture.current;
+ if (!held || held.active) return;
+
+ held.active = true;
+ // Measured before what is carried is taken out of the flow, so the places it can land
+ // are the ones the board is showing.
+ held.measurement = measureBoard(container);
+ // Held from here on, so the gesture keeps the pointer wherever it goes. Taken at the
+ // press instead, it would carry the click away from what was pressed.
+ container.setPointerCapture?.(held.pointerId);
+ const lifted = lift(held, container);
+ held.preview = lifted.preview;
+ held.grab = lifted.grab;
+ container.classList.add("board-dragging");
+ setDragging(true);
+
+ if (held.kind === "card") {
+ latest.current.onCardStart(held.card);
+ } else {
+ latest.current.onColumnStart(held.column, held.index, lifted.size);
+ }
+ resolve(held);
+ };
+
+ const resolve = (held: Gesture) => {
+ const measurement = held.measurement;
+ const grab = held.grab;
+ if (!measurement || !grab) return;
+
+ // Read from what is being carried, not from the pointer: the reader took hold of it
+ // wherever they happened to press, and it is the card they are placing. Across, its
+ // middle says which column it is over; down, its top edge says which place it takes,
+ // that being the edge the gap opens at. Scrolling still follows the pointer, which is
+ // what the reader steers with.
+ const middleX = held.lastX - grab.x + grab.width / 2;
+ const topY = held.lastY - grab.y;
+
+ const x = toBoardX(container, middleX);
+ if (held.kind === "column") {
+ scroller.update([ { element: container, axis: "x" } ], held.lastX, held.lastY);
+ const target = columnInsertionIndex(measurement.columns, x);
+ if (target !== held.target) {
+ held.target = target;
+ latest.current.onColumnMove(target);
+ }
+ return;
+ }
+
+ const column = columnAt(measurement.columns, x);
+ const area = column && measurement.areas.get(column.value);
+ const edges: ScrollTarget[] = [ { element: container, axis: "x" } ];
+ if (area) {
+ edges.push({ element: area, axis: "y" });
+ }
+ scroller.update(edges, held.lastX, held.lastY);
+
+
+ // A collapsed column draws no card area and holds no cards on screen, so a card carried
+ // over it goes to the front of whatever it holds.
+ const position = column
+ ? {
+ column: column.value,
+ index: area ? cardInsertionIndex(column.cards, toAreaY(area, topY)) : 0
+ }
+ : null;
+ // Standing on the column itself, which for a collapsed one is its heading alone: the
+ // empty space under it belongs to no column the reader can see.
+ const on = column && columnCovers(column, x, topY) ? column.value : undefined;
+ if (on !== held.on) {
+ window.clearTimeout(held.dwell);
+ held.on = on;
+ held.inside = false;
+ if (on) {
+ // Rested on rather than crossed: a card carried over a heading on its way
+ // somewhere else leaves the column as it found it.
+ held.dwell = window.setTimeout(() => {
+ held.inside = true;
+ report(held);
+ }, DWELL_MS);
+ }
+ }
+
+ report(held, position);
+ };
+
+ /** Says where the card would land, and whether it has come to rest on that column. */
+ const report = (held: Gesture, next?: DropPosition | null) => {
+ if (held.kind !== "card") return;
+
+ const position = next === undefined ? held.position : next;
+ if (position?.column !== held.position?.column
+ || position?.index !== held.position?.index
+ || held.inside !== held.reported) {
+ held.position = position;
+ held.reported = held.inside;
+ latest.current.onCardMove(position, held.inside);
+ }
+ };
+
+ const onPointerDown = (event: PointerEvent) => {
+ if (event.button !== 0 || gesture.current) return;
+
+ const target = event.target as HTMLElement | null;
+ // Anything the card or the heading offers in its own right keeps its press.
+ if (!target || target.closest("input, textarea, button, a")) return;
+
+ const started = startCard(target) ?? startColumn(target, container);
+ if (!started) return;
+
+ gesture.current = {
+ ...started,
+ pointerId: event.pointerId,
+ startX: event.clientX,
+ startY: event.clientY,
+ lastX: event.clientX,
+ lastY: event.clientY,
+ touch: event.pointerType !== "mouse",
+ active: false,
+ preview: undefined,
+ measurement: undefined,
+ frame: undefined,
+ timer: 0
+ };
+
+ if (gesture.current.touch) {
+ gesture.current.timer = window.setTimeout(activate, TOUCH_DELAY_MS);
+ }
+ };
+
+ const onPointerMove = (event: PointerEvent) => {
+ const held = gesture.current;
+ if (!held || event.pointerId !== held.pointerId) return;
+
+ held.lastX = event.clientX;
+ held.lastY = event.clientY;
+
+ if (!held.active) {
+ const travelled = Math.hypot(event.clientX - held.startX, event.clientY - held.startY);
+ if (held.touch) {
+ // Straying this far before the press has ripened means the finger is scrolling.
+ if (travelled > TOUCH_TOLERANCE) close(true);
+ return;
+ }
+
+ if (travelled <= MOUSE_THRESHOLD) return;
+ // Carried on into the move below, so what is picked up takes its place under the
+ // pointer on the move that picked it up rather than on the one after.
+ activate();
+ }
+
+ // Written in a frame of its own, and only the transform: a move that redrew the board
+ // would redraw every card on it.
+ if (held.frame === undefined) {
+ held.frame = requestAnimationFrame(() => {
+ held.frame = undefined;
+ if (!gesture.current || !held.preview) return;
+
+ const dx = held.lastX - held.startX;
+ const dy = held.lastY - held.startY;
+ const scale = held.kind === "card" ? ` scale(${DRAG_SCALE})` : "";
+ held.preview.style.transform = `translate3d(${dx}px, ${dy}px, 0)${scale}`;
+ resolve(held);
+ });
+ }
+ };
+
+ const onPointerUp = (event: PointerEvent) => {
+ const held = gesture.current;
+ if (!held || event.pointerId !== held.pointerId) return;
+
+ // A tap is a press that never became a drag: it asks for the menu, the long press that
+ // would have opened one being how a finger picks a card up instead.
+ const tapped = held.touch && !held.active && event.type === "pointerup"
+ && Math.hypot(event.clientX - held.startX, event.clientY - held.startY)
+ <= TOUCH_TOLERANCE;
+ const target = held.menuTarget;
+
+ close(event.type === "pointercancel");
+
+ if (tapped) {
+ // The browser follows a tap with mouse events for pages that know nothing of touch,
+ // and they land on the menu this is about to open, right under the finger: the
+ // first of them takes the menu straight back off again. Refused at `touchend`,
+ // which is what the browser makes them from, and which has yet to be sent.
+ justTapped = true;
+ // The click is left out as well, for a browser that sends one regardless. Given up
+ // after a moment so a later click of the reader's own is never the one taken.
+ container.addEventListener("click", swallow, { capture: true, once: true });
+ window.setTimeout(
+ () => container.removeEventListener("click", swallow, { capture: true }),
+ COMPATIBILITY_WINDOW_MS);
+ askForMenu(target, event.clientX, event.clientY);
+ }
+ };
+
+ /** Set between a tap and the `touchend` the browser would make mouse events from. */
+ let justTapped = false;
+
+ const onTouchEnd = (event: TouchEvent) => {
+ if (justTapped) {
+ justTapped = false;
+ event.preventDefault();
+ }
+ };
+
+ const swallow = (event: Event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape" && gesture.current?.active) {
+ close(true);
+ }
+ };
+
+ // A long press is how a finger picks something up, so the menu the same press would
+ // otherwise open is left out. Taken while the event is on its way down, the card's own
+ // handler standing between this and the menu.
+ const onContextMenu = (event: MouseEvent) => {
+ if (gesture.current?.touch) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ };
+
+ // Non-passive, and at the document: the page decides whether a touch scrolls from the first
+ // move it sees, so refusing it has to happen there rather than once the board hears of it.
+ const onTouchMove = (event: TouchEvent) => {
+ if (gesture.current?.active) {
+ event.preventDefault();
+ }
+ };
+
+ container.addEventListener("contextmenu", onContextMenu, { capture: true });
+ container.addEventListener("pointerdown", onPointerDown);
+ container.addEventListener("pointermove", onPointerMove);
+ container.addEventListener("pointerup", onPointerUp);
+ container.addEventListener("pointercancel", onPointerUp);
+ document.addEventListener("keydown", onKeyDown);
+ document.addEventListener("touchmove", onTouchMove, { passive: false });
+ document.addEventListener("touchend", onTouchEnd, { passive: false });
+
+ return () => {
+ close(true);
+ container.removeEventListener("contextmenu", onContextMenu, { capture: true });
+ container.removeEventListener("pointerdown", onPointerDown);
+ container.removeEventListener("pointermove", onPointerMove);
+ container.removeEventListener("pointerup", onPointerUp);
+ container.removeEventListener("pointercancel", onPointerUp);
+ document.removeEventListener("keydown", onKeyDown);
+ document.removeEventListener("touchmove", onTouchMove);
+ document.removeEventListener("touchend", onTouchEnd);
+ container.removeEventListener("click", swallow, { capture: true });
+ };
+ }, [ container, disabled ]);
+
+ /**
+ * Measures the board again, for a drag the board has redrawn under: a collapsed column opened
+ * to take the card moves every column after it.
+ */
+ const remeasure = useCallback(() => {
+ const held = gesture.current;
+ if (held?.active && container) {
+ held.measurement = measureBoard(container);
+ }
+ }, [ container ]);
+
+ return { isDragging, remeasure };
+}
+
+/** Asks an element for its menu the way a right click does, at the place the tap landed. */
+function askForMenu(element: HTMLElement, clientX: number, clientY: number) {
+ element.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, clientX, clientY }));
+}
+
+/** What a press on a card starts, or nothing where the press was not on one. */
+function startCard(target: HTMLElement): CardSubject | null {
+ const element = target.closest<HTMLElement>(".board-note");
+ const columnElement = element?.closest<HTMLElement>(".board-column");
+ const noteId = element?.dataset.noteId;
+ if (!element || !columnElement || !noteId) return null;
+
+ const cards = [ ...columnElement.querySelectorAll(".board-note") ];
+ return {
+ kind: "card",
+ element,
+ menuTarget: element,
+ card: {
+ noteId,
+ fromColumn: columnElement.dataset.column ?? "",
+ index: cards.indexOf(element),
+ height: element.getBoundingClientRect().height
+ },
+ position: null,
+ inside: false,
+ reported: false
+ };
+}
+
+/**
+ * What a press on a column heading starts. The heading is the handle, as it was when the browser
+ * carried the column; a press anywhere else in the column belongs to what stands there.
+ */
+function startColumn(target: HTMLElement, container: HTMLElement): ColumnSubject | null {
+ const heading = target.closest<HTMLElement>(".board-column h3");
+ const element = heading?.closest<HTMLElement>(".board-column");
+ if (!heading || !element || heading.classList.contains("editing")) return null;
+
+ const columns = [ ...container.querySelectorAll(".board-column") ];
+ return {
+ kind: "column",
+ element,
+ menuTarget: heading,
+ column: element.dataset.column ?? "",
+ index: columns.indexOf(element),
+ target: null
+ };
+}
+
+/**
+ * Takes a copy of what is being carried out of the board's flow and hands it back.
+ *
+ * The copy is positioned against the window, which no ancestor's overflow can clip, and stands
+ * inside the board so that the board's own styling still reaches it. A column is cut to a set
+ * height, so that a tall one does not cover the board it is being placed on.
+ */
+function lift(held: Gesture, container: HTMLElement) {
+ const rect = held.element.getBoundingClientRect();
+ const preview = held.element.cloneNode(true) as HTMLElement;
+
+ preview.classList.add("board-drag-preview");
+ preview.removeAttribute("data-note-id");
+ preview.removeAttribute("data-column");
+ // A copy can be used for nothing, and the copy stands outside the column its controls are
+ // styled from, so what it offers is taken out rather than left showing.
+ preview.querySelector(".edit-icon")?.remove();
+
+ for (const [ property, value ] of Object.entries({
+ left: `${rect.left}px`,
+ top: `${rect.top}px`,
+ width: `${rect.width}px`,
+ height: held.kind === "column" ? `${COLUMN_DRAG_HEIGHT}px` : `${rect.height}px`
+ })) {
+ preview.style.setProperty(property, value);
+ }
+
+ // Into the layer rather than the board itself: the board's children are Preact's to place, and
+ // a node put among them by hand is one it has to reckon with when it next draws.
+ (container.querySelector(".board-drag-layer") ?? container).appendChild(preview);
+ held.element.style.display = "none";
+ return {
+ preview,
+ size: { width: rect.width, height: rect.height },
+ // Where inside it the reader took hold, so the middle can be found from the pointer.
+ grab: {
+ x: held.startX - rect.left,
+ y: held.startY - rect.top,
+ width: rect.width,
+ height: rect.height
+ }
+ };
+}
+
+interface CardSubject {
+ kind: "card";
+ element: HTMLElement;
+ /** What a tap asks for the menu, which for a column is its heading rather than the column. */
+ menuTarget: HTMLElement;
+ card: DraggedCard;
+ position: DropPosition | null;
+ /** The column the card stands on, if any, which resting there opens. */
+ on?: string;
+ /** Whether it has rested there long enough to count. */
+ inside: boolean;
+ /** What was last said about that, so nothing is said twice. */
+ reported: boolean;
+}
+
+interface ColumnSubject {
+ kind: "column";
+ element: HTMLElement;
+ menuTarget: HTMLElement;
+ column: string;
+ /** Where it stands among the columns, counting them as they are drawn. */
+ index: number;
+ /** The place it would take, as last reported. */
+ target: number | null;
+}
+
+/** One press, from the moment it lands until it is let go or called off. */
+type Gesture = (CardSubject | ColumnSubject) & {
+ pointerId: number;
+ startX: number;
+ startY: number;
+ lastX: number;
+ lastY: number;
+ /** Whether the press has to ripen before it carries anything. */
+ touch: boolean;
+ /** Whether it has, and something is being carried. */
+ active: boolean;
+ /** The copy that follows the pointer, what it stands for staying where it is. */
+ preview?: HTMLElement;
+ /** Where the press landed inside it, and how big it is, for finding its middle. */
+ grab?: { x: number, y: number, width: number, height: number };
+ measurement?: BoardMeasurement;
+ frame?: number;
+ timer: number;
+ /** Counts down the rest on a column's heading, which is what opens a collapsed one. */
+ dwell?: number;
+};
diff --git a/apps/client/src/widgets/collections/board/card.spec.tsx b/apps/client/src/widgets/collections/board/card.spec.tsx
index 85930c399a..0fe61e5e1c 100644
--- a/apps/client/src/widgets/collections/board/card.spec.tsx
+++ b/apps/client/src/widgets/collections/board/card.spec.tsx
@@ -129,25 +129,6 @@ describe("Board card", () => {
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 () => {});
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index 5868239e7e..899aee52ba 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -10,15 +10,6 @@ import { t } from "../../../services/i18n";
import UserAttributesDisplay from "../../attribute_widgets/UserAttributesList";
import { useNoteIcon, useNoteLabelBoolean, useTriliumEvent } from "../../react/hooks";
-export const CARD_CLIPBOARD_TYPE = "trilium/board-card";
-
-export interface CardDragData {
- noteId: string;
- branchId: string;
- index: number;
- fromColumn: string;
-}
-
function Card({
api,
note,
@@ -43,11 +34,10 @@ function Card({
/** Puts focus back on this card once a change of column has drawn it under another one. */
onFocusCard: (noteId: string) => void
}) {
- const { setBranchIdToEdit, setDraggedCard } = useContext(BoardActionsContext);
+ const { setBranchIdToEdit } = useContext(BoardActionsContext);
const colorClass = note.getColorClass() || '';
const editorRef = useRef<HTMLInputElement>(null);
const [ isArchived ] = useNoteLabelBoolean(note, "archived");
- const [ isVisible, setVisible ] = useState(true);
const [ title, setTitle ] = useState(note.title);
// Tracks the `iconClass` label, which an attribute change carries and the note row never does.
const icon = useNoteIcon(note);
@@ -61,17 +51,6 @@ function Card({
}
});
- const handleDragStart = useCallback((e: DragEvent) => {
- e.dataTransfer!.effectAllowed = 'move';
- const data: CardDragData = { noteId: note.noteId, branchId: branch.branchId, fromColumn: column, index };
- setDraggedCard(data);
- e.dataTransfer!.setData(CARD_CLIPBOARD_TYPE, JSON.stringify(data));
- }, [note.noteId, branch.branchId, column, index]);
-
- const handleDragEnd = useCallback((e: DragEvent) => {
- setDraggedCard(null);
- }, [setDraggedCard]);
-
const handleContextMenu = useCallback((e: ContextMenuEvent) => {
openNoteContextMenu(api, e, note, branch.branchId, column, onFocusCard);
}, [ api, note, branch, column, onFocusCard ]);
@@ -108,23 +87,13 @@ function Card({
setTitle(note.title);
}, [ note ]);
- useEffect(() => {
- setVisible(!isDragging);
- }, [ isDragging ]);
-
return (
<div
className={`board-note ${colorClass} ${isDragging ? 'dragging' : ''} ${isEditing ? "editing" : ""} ${isArchived ? "archived" : ""}`}
data-note-id={note.noteId}
- draggable
- onDragStart={handleDragStart}
- onDragEnd={handleDragEnd}
onContextMenu={handleContextMenu}
onClick={!isEditing ? handleOpen : undefined}
onKeyDown={handleKeyDown}
- style={{
- display: !isVisible ? "none" : undefined
- }}
tabIndex={300}
>
{!isEditing ? (
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 85e2b74967..7d3376f71d 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -21,7 +21,7 @@ import { useScrollFade } from "../../react/scroll_fade";
import NoteLink from "../../react/NoteLink";
import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";
import BoardApi from "./api";
-import Card, { CARD_CLIPBOARD_TYPE, CardDragData } from "./card";
+import Card from "./card";
import { DEFAULT_COLUMN_ICON, INBOX_COLUMN } from "./columns";
import { openColumnContextMenu } from "./context_menu";
@@ -45,12 +45,9 @@ export default function Column({
isActive,
nested,
limit,
- isDraggingColumn,
columnItems,
api,
parentNote,
- onColumnHover,
- isAnyColumnDragging,
isInRelationMode
}: {
columnItems?: { note: FNote, branch: FBranch }[];
@@ -68,11 +65,8 @@ export default function Column({
nested?: boolean,
/** The note limit, absent if disabled. */
limit?: number,
- isDraggingColumn: boolean,
api: BoardApi,
parentNote: FNote,
- onColumnHover?: (index: number, mouseX: number, rect: DOMRect) => void,
- isAnyColumnDragging?: boolean,
isInRelationMode: boolean,
/** The columns as drawn, which is what the menu offers to place this one among. */
columns: string[],
@@ -81,7 +75,6 @@ export default function Column({
onFocusColumn: (column: string) => void,
onFocusCard: (noteId: string) => void
} & DragContext) {
- const [ isVisible, setVisible ] = useState(true);
const [ isCreatingNewItem, setIsCreatingNewItem ] = useState(false);
const { setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn } =
useContext(BoardActionsContext);
@@ -90,10 +83,17 @@ export default function Column({
const editorRef = useRef<HTMLInputElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const scrollFade = useScrollFade(contentRef);
- const { handleColumnDragStart, handleColumnDragEnd, handleDragOver, handleDragLeave, handleDrop } = useDragging({
+ const { handleDragOver, handleDragLeave, handleDrop } = useDragging({
column, columnIndex, columnItems, isEditing, api, parentNote
});
+ // Measured rather than styled: the gap stands for the card being carried, which is whatever
+ // height its own content gave it. A drag from the note tree carries no card, so the stock
+ // height stands.
+ const gapStyle = draggedCard?.height
+ ? { height: `${draggedCard.height}px` }
+ : undefined;
+
// Read here rather than in the badge: the column body shows an outline as well.
const isOverLimit = limit !== undefined && (columnItems?.length ?? 0) > limit;
const isCollapsed = !!collapsed && !isActive;
@@ -174,17 +174,6 @@ export default function Column({
editorRef.current?.focus();
}, [ isEditing ]);
- useEffect(() => {
- setVisible(!isDraggingColumn);
- }, [ isDraggingColumn ]);
-
- const handleColumnDragOver = useCallback((e: DragEvent) => {
- if (!isAnyColumnDragging || !onColumnHover) return;
- e.preventDefault();
- const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
- onColumnHover(columnIndex, e.clientX, rect);
- }, [isAnyColumnDragging, onColumnHover, columnIndex]);
-
return (
<div
data-column={column}
@@ -200,13 +189,10 @@ export default function Column({
// A click and not a press: a press may be the start of a drag, which must leave the
// column as it is, and a drag produces no click.
onClick={select}
- onDragOver={isAnyColumnDragging ? handleColumnDragOver : handleDragOver}
+ onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
- style={{
- display: !isVisible ? "none" : undefined,
- "--board-column-custom-hue": hue
- }}
+ style={{ "--board-column-custom-hue": hue }}
>
<h3
className={`${isEditing ? "editing" : ""}`}
@@ -215,9 +201,6 @@ export default function Column({
// nothing, so neither is claimed.
role={isCollapsed ? "button" : undefined}
aria-expanded={isCollapsed ? false : undefined}
- draggable
- onDragStart={handleColumnDragStart}
- onDragEnd={handleColumnDragEnd}
onContextMenu={openMenu}
onKeyDown={handleTitleKeyDown}
tabIndex={300}
@@ -312,7 +295,7 @@ export default function Column({
return (
<Fragment key={note.noteId}>
{showIndicatorBefore && (
- <div className="board-drop-placeholder show" />
+ <div className="board-drop-placeholder show" style={gapStyle} />
)}
<Card
api={api}
@@ -328,7 +311,7 @@ export default function Column({
);
})}
{dropPosition?.column === column && dropPosition.index === (columnItems?.length ?? 0) && (
- <div className="board-drop-placeholder show" />
+ <div className="board-drop-placeholder show" style={gapStyle} />
)}
<AddNewItem
@@ -500,7 +483,8 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentN
const handleDragOver = useCallback((e: DragEvent) => {
if (isEditing || draggedColumn || isDraggingRef.current) return; // Don't handle card drops when dragging columns
- if (!e.dataTransfer?.types.includes(CARD_CLIPBOARD_TYPE) && !e.dataTransfer?.types.includes(TREE_CLIPBOARD_TYPE)) return;
+ // Cards are carried by pointer now; what still arrives this way comes from the note tree.
+ if (!e.dataTransfer?.types.includes(TREE_CLIPBOARD_TYPE)) return;
e.preventDefault();
setDropTarget(column);
@@ -545,19 +529,18 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentN
setDropTarget(null);
setDropPosition(null);
- const data = e.dataTransfer?.getData(CARD_CLIPBOARD_TYPE) || e.dataTransfer?.getData("text");
+ const data = e.dataTransfer?.getData("text");
if (!data) return;
- let draggedCard: CardDragData | DragData[];
+ let dropped: DragData[];
try {
- draggedCard = JSON.parse(data);
+ dropped = JSON.parse(data);
} catch (e) {
return;
}
- if (Array.isArray(draggedCard)) {
- // From note tree.
- const { noteId, branchId } = draggedCard[0];
+ if (Array.isArray(dropped)) {
+ const { noteId, branchId } = dropped[0];
const targetNote = await froca.getNote(noteId, true);
const parentNoteId = parentNote.noteId;
if (!dropPosition) return;
@@ -579,10 +562,7 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentN
} else if (targetBranch) {
await branches.moveAfterBranch([ branchId ], targetBranch.branchId);
}
- } else if (draggedCard && dropPosition) {
- api.moveWithinBoard(draggedCard.noteId, draggedCard.branchId, draggedCard.index, dropPosition.index, draggedCard.fromColumn, column);
}
-
}, [ api, draggedColumn, dropPosition, columnItems, column, setDropTarget, setDropPosition ]);
return { handleColumnDragStart, handleColumnDragEnd, handleDragOver, handleDragLeave, handleDrop };
diff --git a/apps/client/src/widgets/collections/board/drag.spec.tsx b/apps/client/src/widgets/collections/board/drag.spec.tsx
index 50e68822fb..2e7c9eb85e 100644
--- a/apps/client/src/widgets/collections/board/drag.spec.tsx
+++ b/apps/client/src/widgets/collections/board/drag.spec.tsx
@@ -14,7 +14,6 @@ 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: {
@@ -32,6 +31,15 @@ const PREACT_DRAG_EVENTS = {
drop: "Drop"
} as const;
+// Hoisted with the mock, which is lifted above everything a test file declares.
+const layout = vi.hoisted(() => ({ onMobile: false }));
+
+// Spread rather than replaced: the board reads far more of this than the one export a test steers.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ isMobile: () => layout.onMobile
+}));
+
describe("Board drag and drop", () => {
let container: HTMLElement | undefined;
@@ -45,6 +53,7 @@ describe("Board drag and drop", () => {
});
afterEach(() => {
+ (document.activeElement as HTMLElement | null)?.blur?.();
if (container) {
render(null, container);
container.remove();
@@ -56,7 +65,7 @@ describe("Board drag and drop", () => {
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);
+ await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 120);
const placeholders = [ ...columns[0].querySelectorAll(".board-column-content > *") ]
.map(child => child.className);
@@ -66,7 +75,7 @@ describe("Board drag and drop", () => {
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);
+ await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 120);
expect(columns[0].querySelector(".board-drop-placeholder")).toBeTruthy();
await drag(columns[0], "dragleave", { types: [] });
@@ -81,25 +90,6 @@ describe("Board drag and drop", () => {
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" });
@@ -147,12 +137,12 @@ describe("Board drag and drop", () => {
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], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 120);
await drag(columns[0], "drop", {
- types: [ CARD_CLIPBOARD_TYPE ],
- data: { [CARD_CLIPBOARD_TYPE]: "not json at all" }
+ types: [ TREE_CLIPBOARD_TYPE ],
+ data: { text: "not json at all" }
});
- await drag(columns[0], "drop", { types: [ CARD_CLIPBOARD_TYPE ], data: {} });
+ await drag(columns[0], "drop", { types: [ TREE_CLIPBOARD_TYPE ], data: {} });
expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
expect(branches.moveAfterBranch).not.toHaveBeenCalled();
@@ -167,14 +157,156 @@ describe("Board drag and drop", () => {
expect(columns[0].classList.contains("collapsed")).toBe(true);
- await drag(columns[0], "dragover", { types: [ CARD_CLIPBOARD_TYPE ] }, 50);
+ await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 50);
expect(columns[0].classList.contains("collapsed")).toBe(false);
expect(columns[0].querySelectorAll(".board-note")).toHaveLength(2);
- await drag(columns[0], "dragleave", { types: [ CARD_CLIPBOARD_TYPE ] });
+ await drag(columns[0], "dragleave", { types: [ TREE_CLIPBOARD_TYPE ] });
expect(columns[0].classList.contains("collapsed")).toBe(false);
});
+ /**
+ * What the gesture is for: the same move the old clipboard drop made, made by pointer. The
+ * board's own wiring is what this covers, the gesture itself being tested on its own.
+ */
+ it("moves a card carried by pointer to where it was let go", async () => {
+ const { columns, cards } = await renderBoard();
+ const card = columns[0].querySelector<HTMLElement>(".board-note");
+ if (!card) throw new Error("expected a card");
+
+ // The gesture listens from an effect, which Preact defers past the render the board is
+ // drawn by. A reader could not press before that; a test can.
+ await act(async () => { await settle(); });
+
+ // Taken from the first card and let go above the second's middle, so it lands between them.
+ await pointer(card, "pointerdown", 50, 50);
+ await pointer(columns[0], "pointermove", 50, 120);
+ await act(async () => { await settle(); });
+ await pointer(columns[0], "pointerup", 50, 120);
+ await act(async () => { await settle(); });
+
+ expect(branches.moveBeforeBranch)
+ .toHaveBeenCalledWith([ cards[0].branchId ], cards[1].branchId);
+ });
+
+ /**
+ * A board that scrolls one column at a time has its snapping off while something is carried, so
+ * letting go would otherwise leave the reader looking at two half columns.
+ */
+ it("brings the column the card landed in to the middle, on a board that snaps", async () => {
+ layout.onMobile = true;
+ const revealed: { element: Element, options: unknown }[] = [];
+ const original = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = function (this: Element, options: unknown) {
+ revealed.push({ element: this, options });
+ } as typeof original;
+
+ try {
+ const { columns } = await renderBoard();
+ const card = columns[0].querySelector<HTMLElement>(".board-note");
+ if (!card) throw new Error("expected a card");
+ await act(async () => { await settle(); });
+
+ await pointer(card, "pointerdown", 50, 50);
+ await pointer(columns[0], "pointermove", 50, 120);
+ await pointer(columns[0], "pointerup", 50, 120);
+ await act(async () => { await new Promise(requestAnimationFrame); });
+
+ const landed = revealed.at(-1);
+ expect(landed?.element).toBe(columns[0]);
+ expect(landed?.options).toMatchObject({ inline: "center" });
+ } finally {
+ Element.prototype.scrollIntoView = original;
+ layout.onMobile = false;
+ }
+ });
+
+ /** Nothing is brought anywhere on a board the reader scrolls freely. */
+ it("leaves the board where it is when it does not snap", async () => {
+ const revealed: Element[] = [];
+ const original = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = function (this: Element) {
+ revealed.push(this);
+ } as typeof original;
+
+ try {
+ const { columns } = await renderBoard();
+ const card = columns[0].querySelector<HTMLElement>(".board-note");
+ if (!card) throw new Error("expected a card");
+ await act(async () => { await settle(); });
+
+ await pointer(card, "pointerdown", 50, 50);
+ await pointer(columns[0], "pointermove", 50, 120);
+ await pointer(columns[0], "pointerup", 50, 120);
+ await act(async () => { await new Promise(requestAnimationFrame); });
+
+ expect(revealed.filter(element =>
+ element.classList.contains("board-column"))).toEqual([]);
+ } finally {
+ Element.prototype.scrollIntoView = original;
+ }
+ });
+
+ /**
+ * The press focuses the card, the card is then taken out of the page, and a card that crossed
+ * columns is drawn as a new element: whichever happened, the focus has to be put back.
+ */
+ it("focuses the card again once it is let go", async () => {
+ const { columns } = await renderBoard();
+ const card = columns[0].querySelector<HTMLElement>(".board-note");
+ if (!card) throw new Error("expected a card");
+ // Twice: the gesture listens from an effect, and the board redraws once more as its own
+ // first refresh lands, which is what tells the effect the container is there.
+ await act(async () => { await settle(); });
+ await act(async () => { await settle(); });
+
+ await pointer(card, "pointerdown", 50, 50);
+ await pointer(columns[0], "pointermove", 50, 120);
+ await pointer(columns[0], "pointerup", 50, 120);
+ await act(async () => { await settle(); });
+
+ expect(document.activeElement?.getAttribute("data-note-id"))
+ .toBe(card.getAttribute("data-note-id"));
+ });
+
+ /** The gap stands in for the card, so it is the height the card was measured at. */
+ it("holds open a gap the height of the card being carried", async () => {
+ const { columns } = await renderBoard();
+ const card = columns[0].querySelector<HTMLElement>(".board-note");
+ if (!card) throw new Error("expected a card");
+ await act(async () => { await settle(); });
+
+ await pointer(card, "pointerdown", 50, 50);
+ await pointer(columns[0], "pointermove", 50, 120);
+
+ const gap = columns[0].querySelector<HTMLElement>(".board-drop-placeholder");
+ expect(gap?.style.height).toBe("100px");
+ });
+
+ function place(
+ element: HTMLElement | null,
+ box: { left: number, top: number, width: number, height: number }
+ ) {
+ if (element) {
+ element.getBoundingClientRect = () => ({
+ ...box, right: box.left + box.width, bottom: box.top + box.height
+ }) as DOMRect;
+ }
+ }
+
+ async function pointer(target: HTMLElement, type: string, clientX: number, clientY: number) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ for (const [ name, value ] of Object.entries({
+ clientX, clientY, pointerId: 1, button: 0, pointerType: "mouse"
+ })) {
+ Object.defineProperty(event, name, { value, configurable: true });
+ }
+ await act(async () => {
+ target.dispatchEvent(event);
+ await settle();
+ });
+ }
+
/** A board of one column of two cards, each given a height the pointer can be placed in. */
async function renderBoard({ collapsed }: { collapsed?: boolean } = {}) {
const note = buildNote({
@@ -214,10 +346,21 @@ describe("Board drag and drop", () => {
// 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
+ left: 0, top: index * 100, width: 100, height: 100
}) as DOMRect;
}
+ // The pointer gesture measures the board itself, so its boxes are declared as well.
+ const board = mountPoint.querySelector<HTMLElement>(".board-view-container");
+ place(board, { left: 0, top: 0, width: 400, height: 400 });
+ Object.defineProperty(board, "scrollLeft", { value: 0, configurable: true });
+ place(columns[0], { left: 0, top: 0, width: 100, height: 400 });
+ const area = columns[0].querySelector<HTMLElement>(".board-column-content");
+ if (area) {
+ place(area, { left: 0, top: 0, width: 100, height: 400 });
+ Object.defineProperty(area, "scrollTop", { value: 0, configurable: true });
+ }
+
const cards = note.getChildBranches()
.map(branch => ({ noteId: branch.noteId, branchId: branch.branchId }));
@@ -272,6 +415,7 @@ describe("Board column reordering", () => {
});
afterEach(() => {
+ (document.activeElement as HTMLElement | null)?.blur?.();
if (container) {
render(null, container);
container.remove();
@@ -280,24 +424,20 @@ describe("Board column reordering", () => {
});
it("drops a column to the right of the one it was let go over", async () => {
- const { columns, board } = await renderColumns();
+ const { columns } = 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");
+ await carryColumn(columns[0], 280);
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();
+ const { columns } = 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");
+ await carryColumn(columns[2], 120);
expect(saved.at(-1)?.columns?.map(column => column.value))
.toEqual([ "To Do", "Done", "Doing" ]);
@@ -307,41 +447,165 @@ describe("Board column reordering", () => {
* The gap held open while a column is carried stands in for that column, and a collapsed one
* is a strip. A placeholder of the stock width would promise a space the column will not fill.
*/
- it("holds open a gap the size of the column being dragged", async () => {
- const { columns, board } = await renderColumns();
- for (const [ name, value ] of Object.entries({ offsetWidth: 36, offsetHeight: 140 })) {
- Object.defineProperty(columns[0], name, { value, configurable: true });
- }
+ it("holds open a gap the size of the column being carried", async () => {
+ const { columns, board } = await renderColumns({ height: 140 });
- await dragColumn(columns[0], "dragstart");
- await dragColumn(columns[2], "dragover", 280);
+ await carryColumn(columns[0], 280, { release: false });
const placeholder = board.querySelector<HTMLElement>(".column-drop-placeholder");
- expect(placeholder?.style.width).toBe("36px");
+ expect(placeholder?.style.width).toBe("100px");
expect(placeholder?.style.height).toBe("140px");
});
/** happy-dom lays nothing out, which is what an element with no size on screen reports too. */
it("leaves the gap at its stock size when the column measures nothing", async () => {
- const { columns, board } = await renderColumns();
+ const { columns, board } = await renderColumns({ width: 0 });
- await dragColumn(columns[0], "dragstart");
- await dragColumn(columns[2], "dragover", 280);
+ await carryColumn(columns[0], 280, { release: false });
const placeholder = board.querySelector<HTMLElement>(".column-drop-placeholder");
expect(placeholder?.style.width).toBe("");
});
- it("hides the column being dragged, and shows it again once let go", async () => {
- const { columns } = await renderColumns();
+ /** A copy of it is carried, cut to a set height so a tall column does not cover the board. */
+ it("carries a copy, hiding the column until it is let go", async () => {
+ const { columns, board } = await renderColumns();
- await dragColumn(columns[0], "dragstart");
+ await carryColumn(columns[0], 280, { release: false });
+ const copy = board.querySelector<HTMLElement>(".board-column.board-drag-preview");
+ expect(copy).toBeTruthy();
+ expect(copy?.style.height).toBe("150px");
expect(columns[0].style.display).toBe("none");
- await dragColumn(columns[0], "dragend");
- expect(columns[0].style.display).not.toBe("none");
+ await columnPointer(board, "pointerup", 280);
+ expect(board.querySelector(".board-drag-preview")).toBeNull();
+ expect(columns[0].style.display).toBe("");
+ });
+
+ /**
+ * Let go either side of where it stands, a column lands where it started, and the board is not
+ * written to for a move that moves nothing.
+ */
+ it("saves nothing for a column carried back to where it was", async () => {
+ const { columns } = await renderColumns();
+
+ await carryColumn(columns[1], 120);
+
+ expect(saved).toEqual([]);
+ });
+
+ /** The board's row as it is laid out: the columns' wrapper is `display: contents`. */
+ function laidOut(board: HTMLElement) {
+ return [ ...board.children ].flatMap((child) =>
+ child.classList.contains("board-columns") ? [ ...child.children ] : [ child ]);
+ }
+
+ /**
+ * What a drop leads to: the board is drawn again with the columns in a new order. Their
+ * elements are keyed, so Preact moves them, and it places what it moves against the parent's
+ * own children. Anything among them it is not keeping track of can be stepped over.
+ */
+ it("keeps the button after every column once they are drawn in a new order", async () => {
+ const { board } = await renderColumns();
+ const order = () => laidOut(board)
+ .filter(child => child.classList.contains("board-column")
+ || child.classList.contains("board-add-column"))
+ .map(child => child.getAttribute("data-column") ?? "add");
+
+ expect(order()).toEqual([ "To Do", "Doing", "Done", "add" ]);
+
+ await drawColumns([ "Done", "To Do", "Doing" ]);
+ expect(order()).toEqual([ "Done", "To Do", "Doing", "add" ]);
+
+ await drawColumns([ "Doing", "Done", "To Do" ]);
+ expect(order()).toEqual([ "Doing", "Done", "To Do", "add" ]);
+ });
+
+ /**
+ * The drop changes two things at once: the columns take a new order and the gap held open for
+ * the carried one goes. Both land in a single redraw, which is where the button is placed.
+ */
+ it("keeps the button after every column once a carried one is let go", async () => {
+ const { columns, board } = await renderColumns();
+ const order = () => laidOut(board)
+ .filter(child => (child.classList.contains("board-column")
+ && !child.classList.contains("board-drag-preview"))
+ || child.classList.contains("board-add-column"))
+ .map(child => child.getAttribute("data-column") ?? "add");
+
+ // Past the middle of the last column, so it is let go at the end.
+ await carryColumn(columns[0], 280);
+
+ expect(order()).toEqual([ "Doing", "Done", "To Do", "add" ]);
});
+ /** The button that adds a column stands at the end, whatever the gap does among the columns. */
+ it("keeps the button that adds a column at the end while one is carried", async () => {
+ const { columns, board } = await renderColumns();
+
+ /** Whether the button stands after every column, the overlays after it being no columns. */
+ const afterEveryColumn = () => {
+ const children = laidOut(board);
+ const button = children.findIndex(child =>
+ child.classList.contains("board-add-column"));
+ // The copy being carried wears the column's classes so the board's styling reaches it,
+ // and is placed against the window rather than among them.
+ const lastColumn = children.findLastIndex(child =>
+ child.classList.contains("board-column")
+ && !child.classList.contains("board-drag-preview"));
+ return button > lastColumn && button >= 0;
+ };
+
+ expect(afterEveryColumn()).toBe(true);
+
+ // Over each column in turn, so the gap opens at every place among them.
+ await carryColumn(columns[0], 120, { release: false });
+ expect(afterEveryColumn()).toBe(true);
+
+ await columnPointer(board, "pointermove", 220);
+ expect(afterEveryColumn()).toBe(true);
+
+ await columnPointer(board, "pointermove", 280);
+ expect(afterEveryColumn()).toBe(true);
+
+ await columnPointer(board, "pointerup", 280);
+ expect(afterEveryColumn()).toBe(true);
+ });
+
+ /** Takes hold of a column by its heading, carries it to `clientX` and lets it go there. */
+ async function carryColumn(
+ column: HTMLElement,
+ clientX: number,
+ { release = true }: { release?: boolean } = {}
+ ) {
+ const heading = column.querySelector<HTMLElement>("h3");
+ if (!heading) throw new Error("expected a column heading");
+
+ const board = column.closest<HTMLElement>(".board-view-container");
+ if (!board) throw new Error("expected a board");
+
+ // Taken by a point inside the column, so where its middle stands follows the pointer.
+ const { left, width } = column.getBoundingClientRect();
+ await columnPointer(heading, "pointerdown", left + width / 2);
+ await columnPointer(board, "pointermove", clientX);
+ if (release) {
+ await columnPointer(board, "pointerup", clientX);
+ }
+ }
+
+ async function columnPointer(target: HTMLElement, type: string, clientX: number) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ for (const [ name, value ] of Object.entries({
+ clientX, clientY: 0, pointerId: 1, button: 0, pointerType: "mouse"
+ })) {
+ Object.defineProperty(event, name, { value, configurable: true });
+ }
+ await act(async () => {
+ target.dispatchEvent(event);
+ await settle();
+ });
+ }
+
it("saves nothing for a column let go where it already was", async () => {
const { columns, board } = await renderColumns();
@@ -353,7 +617,9 @@ describe("Board column reordering", () => {
});
/** A board of three columns, each given the geometry the drop maths reads. */
- async function renderColumns() {
+ let drawColumns: (order: string[]) => Promise<void> = async () => {};
+
+ async function renderColumns({ width = 100, height = 400 } = {}) {
const note = buildNote({
title: "Board",
"#collection": "",
@@ -369,37 +635,45 @@ describe("Board column reordering", () => {
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();
+ drawColumns = async (order: string[]) => {
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <BoardView
+ note={note}
+ notePath={`root/${note.noteId}`}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ highlightedTokens={null}
+ viewConfig={{ columns: order.map(value => ({ value })) }}
+ saveConfig={(config) => saved.push(config)}
+ media="screen"
+ onReady={() => {}}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ await settle();
+ });
+ await act(async () => { await settle(); });
+ };
+
+ await drawColumns([ "To Do", "Doing", "Done" ]);
const columns = [ ...mountPoint.querySelectorAll<HTMLElement>(".board-column") ];
for (const [ index, column ] of columns.entries()) {
column.getBoundingClientRect = () => ({
- left: index * 100, width: 100
+ left: index * 100, top: 0, width, height
}) as DOMRect;
}
const board = mountPoint.querySelector<HTMLElement>(".board-view-container");
if (!board) throw new Error("expected the board container");
+ board.getBoundingClientRect = () => ({ left: 0, top: 0, width: 400, height }) as DOMRect;
+ Object.defineProperty(board, "scrollLeft", { value: 0, configurable: true });
+ // The gesture listens from an effect, which Preact defers past the render.
+ await act(async () => { await settle(); });
+
return { columns, board };
}
diff --git a/apps/client/src/widgets/collections/board/drag_geometry.spec.ts b/apps/client/src/widgets/collections/board/drag_geometry.spec.ts
new file mode 100644
index 0000000000..8d7e8f99f1
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/drag_geometry.spec.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ type CardBox, cardInsertionIndex, columnAt, type ColumnBox, columnCovers,
+ columnInsertionIndex, movesColumn
+} from "./drag_geometry";
+
+/** Three 100px columns with a 20px gap, standing 400 tall from the top of the page. */
+function columns(cards: Record<string, CardBox[]> = {}): ColumnBox[] {
+ return [ "To Do", "Doing", "Done" ].map((value, index) => ({
+ value,
+ left: index * 120,
+ width: 100,
+ top: 0,
+ height: 400,
+ cards: cards[value] ?? []
+ }));
+}
+
+/** Cards of the given heights, stacked from the top of the card area. */
+function stack(...heights: number[]): CardBox[] {
+ let top = 0;
+ return heights.map((height) => {
+ const card = { top, height };
+ top += height;
+ return card;
+ });
+}
+
+describe("columnAt", () => {
+ it("answers with the column the point stands in", () => {
+ const board = columns();
+
+ expect(columnAt(board, 0)?.value).toBe("To Do");
+ expect(columnAt(board, 99)?.value).toBe("To Do");
+ expect(columnAt(board, 120)?.value).toBe("Doing");
+ expect(columnAt(board, 299)?.value).toBe("Done");
+ });
+
+ /** The board leaves a gap between columns, which a drag passes through. */
+ it("answers with the nearer column for a point in the gap between two", () => {
+ const board = columns();
+
+ expect(columnAt(board, 104)?.value).toBe("To Do");
+ expect(columnAt(board, 116)?.value).toBe("Doing");
+ });
+
+ /** Held past an end while the board scrolls itself, the drag still has somewhere to go. */
+ it("answers with the end column for a point beyond the board", () => {
+ const board = columns();
+
+ expect(columnAt(board, -500)?.value).toBe("To Do");
+ expect(columnAt(board, 5000)?.value).toBe("Done");
+ });
+
+ it("answers with nothing for a board of no columns", () => {
+ expect(columnAt([], 50)).toBeUndefined();
+ });
+});
+
+describe("columnCovers", () => {
+ /** The gap beside a column is answered for by it, and is not part of it. */
+ it("tells standing on a column from being nearest to it", () => {
+ const [ first, second ] = columns();
+
+ expect(columnCovers(first, 0, 200)).toBe(true);
+ expect(columnCovers(first, 99, 200)).toBe(true);
+ expect(columnCovers(first, 100, 200)).toBe(false);
+ expect(columnCovers(first, 104, 200)).toBe(false);
+ expect(columnAt(columns(), 104)?.value).toBe("To Do");
+
+ expect(columnCovers(second, 120, 200)).toBe(true);
+ expect(columnCovers(second, -5000, 200)).toBe(false);
+ });
+
+ /**
+ * A collapsed column is only as tall as its heading, and the empty space below it belongs to
+ * no column the reader can see.
+ */
+ it("tells the column from the empty space below a short one", () => {
+ const strip: ColumnBox = {
+ value: "Parked", left: 0, width: 36, top: 0, height: 90, cards: []
+ };
+
+ expect(columnCovers(strip, 18, 0)).toBe(true);
+ expect(columnCovers(strip, 18, 89)).toBe(true);
+ expect(columnCovers(strip, 18, 90)).toBe(false);
+ expect(columnCovers(strip, 18, 300)).toBe(false);
+ // Still the nearest column, so a card held there has somewhere to go.
+ expect(columnAt([ strip ], 18)?.value).toBe("Parked");
+ });
+});
+
+describe("cardInsertionIndex", () => {
+ it("places the card before the one it is held over the top half of", () => {
+ const cards = stack(50, 50, 50);
+
+ expect(cardInsertionIndex(cards, 0)).toBe(0);
+ expect(cardInsertionIndex(cards, 24)).toBe(0);
+ // Past the first card's middle, so it goes after it.
+ expect(cardInsertionIndex(cards, 26)).toBe(1);
+ expect(cardInsertionIndex(cards, 74)).toBe(1);
+ expect(cardInsertionIndex(cards, 76)).toBe(2);
+ });
+
+ it("places the card at the end when it is held below them all", () => {
+ expect(cardInsertionIndex(stack(50, 50, 50), 500)).toBe(3);
+ expect(cardInsertionIndex(stack(50), 40)).toBe(1);
+ });
+
+ it("places the card first in a column holding none", () => {
+ expect(cardInsertionIndex([], 0)).toBe(0);
+ expect(cardInsertionIndex([], 500)).toBe(0);
+ });
+
+ /** Cards are not all one height: a tall one's middle is further down than its neighbour's. */
+ it("counts each card's own middle rather than a shared height", () => {
+ const cards = stack(20, 200, 20);
+
+ expect(cardInsertionIndex(cards, 9)).toBe(0);
+ expect(cardInsertionIndex(cards, 11)).toBe(1);
+ // The tall card runs from 20 to 220, so its middle is at 120.
+ expect(cardInsertionIndex(cards, 119)).toBe(1);
+ expect(cardInsertionIndex(cards, 121)).toBe(2);
+ });
+
+ /** A point above the first card is still a point above its middle. */
+ it("places the card first when it is held above the card area", () => {
+ expect(cardInsertionIndex(stack(50, 50), -80)).toBe(0);
+ });
+});
+
+describe("columnInsertionIndex", () => {
+ it("places the column before the one it is held over the left half of", () => {
+ const board = columns();
+
+ expect(columnInsertionIndex(board, 0)).toBe(0);
+ expect(columnInsertionIndex(board, 49)).toBe(0);
+ expect(columnInsertionIndex(board, 51)).toBe(1);
+ expect(columnInsertionIndex(board, 169)).toBe(1);
+ expect(columnInsertionIndex(board, 171)).toBe(2);
+ });
+
+ it("places the column at the end when it is held past them all", () => {
+ expect(columnInsertionIndex(columns(), 5000)).toBe(3);
+ });
+
+ it("places the column first on a board holding none", () => {
+ expect(columnInsertionIndex([], 50)).toBe(0);
+ });
+
+ /** The gap belongs to whichever half of a column it borders, as any other point does. */
+ it("counts the gap between two columns as past the left one", () => {
+ expect(columnInsertionIndex(columns(), 110)).toBe(1);
+ });
+});
+
+describe("movesColumn", () => {
+ /** A column dropped either side of where it stands lands where it started. */
+ it("knows the two places that leave a column where it is", () => {
+ expect(movesColumn(1, 1)).toBe(false);
+ expect(movesColumn(1, 2)).toBe(false);
+
+ expect(movesColumn(1, 0)).toBe(true);
+ expect(movesColumn(1, 3)).toBe(true);
+ });
+
+ it("knows the ends", () => {
+ expect(movesColumn(0, 0)).toBe(false);
+ expect(movesColumn(0, 1)).toBe(false);
+ expect(movesColumn(0, 2)).toBe(true);
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/drag_geometry.ts b/apps/client/src/widgets/collections/board/drag_geometry.ts
new file mode 100644
index 0000000000..0d04752ad1
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/drag_geometry.ts
@@ -0,0 +1,126 @@
+/**
+ * Where a dragged card or column would land.
+ *
+ * Pure arithmetic over boxes measured once at the start of a drag, so a move costs no layout reads.
+ * Two coordinate spaces are used, each chosen so that scrolling does not invalidate the measurement:
+ * columns are placed along the board's content space, which the board's horizontal scrolling does
+ * not move them in, and cards along their own column's card-area content space, which that column's
+ * vertical scrolling does not move them in.
+ */
+
+/** A card, in the content space of the card area holding it. */
+export interface CardBox {
+ top: number;
+ height: number;
+}
+
+/** A column, placed across in the board's content space and down in the page's. */
+export interface ColumnBox {
+ /** The grouping value identifying the column. */
+ value: string;
+ left: number;
+ width: number;
+ /**
+ * Where it stands down the page, and how tall it is. The board does not scroll this way, so
+ * these hold for the length of a drag. A collapsed column is only as tall as its heading, which
+ * is what tells standing on it from standing in the empty space under it.
+ */
+ top: number;
+ height: number;
+ /**
+ * The cards as drawn, in order, the dragged one included. Counting it keeps the index in the
+ * same terms as the list the board holds, which is what a move is expressed in.
+ */
+ cards: CardBox[];
+}
+
+/**
+ * The column a point falls in, or the nearest one where it falls between columns or past an end.
+ *
+ * Nearest rather than nothing, so a drag carried into the gap between two columns, or held past the
+ * last one while the board scrolls itself, still has somewhere to go.
+ *
+ * @param columns the columns as drawn, in order.
+ * @param x in the board's content space.
+ */
+export function columnAt(columns: ColumnBox[], x: number): ColumnBox | undefined {
+ let nearest: ColumnBox | undefined;
+ let shortest = Infinity;
+
+ for (const column of columns) {
+ if (x >= column.left && x < column.left + column.width) {
+ return column;
+ }
+
+ const distance = x < column.left
+ ? column.left - x
+ : x - (column.left + column.width);
+
+ if (distance < shortest) {
+ shortest = distance;
+ nearest = column;
+ }
+ }
+
+ return nearest;
+}
+
+/**
+ * Whether a point stands on a column itself, rather than merely being nearest to it or standing in
+ * the empty space below it.
+ *
+ * @param x in the board's content space, and @param y down the page.
+ */
+export function columnCovers(column: ColumnBox, x: number, y: number): boolean {
+ return x >= column.left && x < column.left + column.width
+ && y >= column.top && y < column.top + column.height;
+}
+
+/**
+ * Where a card would be inserted in a column: before the first card the point is above the middle
+ * of, or at the end.
+ *
+ * @param cards the column's cards, in order.
+ * @param y in the content space of the card area holding them.
+ */
+export function cardInsertionIndex(cards: CardBox[], y: number): number {
+ for (const [ index, card ] of cards.entries()) {
+ if (y < card.top + card.height / 2) {
+ return index;
+ }
+ }
+
+ return cards.length;
+}
+
+/**
+ * Where a dragged column would be inserted: before the column the point is left of the middle of,
+ * or after it.
+ *
+ * The answer counts the columns as they stand, the dragged one included, so it names a place in the
+ * list rather than a place in the list without it.
+ *
+ * @param columns the columns as drawn, in order.
+ * @param x in the board's content space.
+ */
+export function columnInsertionIndex(columns: ColumnBox[], x: number): number {
+ if (!columns.length) {
+ return 0;
+ }
+
+ for (const [ index, column ] of columns.entries()) {
+ if (x < column.left + column.width / 2) {
+ return index;
+ }
+ }
+
+ return columns.length;
+}
+
+/**
+ * Whether inserting at the given place would move the column at all. A column dropped just before
+ * or just after where it already stands lands where it started.
+ */
+export function movesColumn(from: number, to: number): boolean {
+ return to !== from && to !== from + 1;
+}
diff --git a/apps/client/src/widgets/collections/board/drag_measure.spec.ts b/apps/client/src/widgets/collections/board/drag_measure.spec.ts
new file mode 100644
index 0000000000..2643f72047
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/drag_measure.spec.ts
@@ -0,0 +1,153 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import { cardInsertionIndex, columnAt } from "./drag_geometry";
+import { measureBoard, toAreaY, toBoardX } from "./drag_measure";
+
+let container: HTMLElement | undefined;
+
+afterEach(() => {
+ container?.remove();
+ container = undefined;
+});
+
+/**
+ * happy-dom lays nothing out, so every box is declared. The board is placed 50px into the page and
+ * scrolled 200px along, which is what tells a content-space measurement from a viewport one.
+ */
+function buildBoard({ scrollLeft = 200, areaScrollTop = 20, cardCounts = [ 2, 1 ] } = {}) {
+ container = document.createElement("div");
+ container.className = "board-view-container";
+ document.body.appendChild(container);
+ place(container, { left: 50, top: 0, width: 500, height: 400 });
+ Object.defineProperty(container, "scrollLeft", { value: scrollLeft, configurable: true });
+
+ for (const [ index, cards ] of cardCounts.entries()) {
+ const column = document.createElement("div");
+ column.className = "board-column";
+ column.dataset.column = [ "To Do", "Doing", "Done" ][index];
+ container.appendChild(column);
+ // On screen the columns have already been scrolled 200px to the left.
+ place(column, { left: 50 + index * 120 - scrollLeft, top: 0, width: 100, height: 400 });
+
+ const area = document.createElement("div");
+ area.className = "board-column-content";
+ column.appendChild(area);
+ place(area, { left: 0, top: 40, width: 100, height: 360 });
+ Object.defineProperty(area, "scrollTop", { value: areaScrollTop, configurable: true });
+
+ for (let card = 0; card < cards; card++) {
+ const note = document.createElement("div");
+ note.className = "board-note";
+ area.appendChild(note);
+ // Stated where the card stands in the area's content, then drawn where that leaves it
+ // on screen once the area has been scrolled.
+ place(note, {
+ left: 0,
+ top: 40 + cardContentTop(card) - areaScrollTop,
+ width: 100,
+ height: 50
+ });
+ }
+ }
+
+ return container;
+}
+
+/** Where card `index` stands in its area's content, whatever the area is scrolled to. */
+function cardContentTop(index: number) {
+ return 10 + index * 60;
+}
+
+function place(element: HTMLElement, box: { left: number, top: number, width: number, height: number }) {
+ element.getBoundingClientRect = () => ({
+ left: box.left,
+ top: box.top,
+ width: box.width,
+ height: box.height,
+ right: box.left + box.width,
+ bottom: box.top + box.height
+ }) as DOMRect;
+}
+
+describe("measureBoard", () => {
+ it("places the columns past the board's own scrolling", () => {
+ const board = buildBoard();
+
+ const { columns } = measureBoard(board);
+
+ // On screen the first column starts at -150; in the board's content space it starts at 0.
+ expect(columns.map((column) => ({ value: column.value, left: column.left })))
+ .toEqual([ { value: "To Do", left: 0 }, { value: "Doing", left: 120 } ]);
+ });
+
+ it("places the cards past their own column's scrolling", () => {
+ const expected = [ { top: 10, height: 50 }, { top: 70, height: 50 } ];
+
+ // The same cards, drawn at different places on screen, measure to the same content.
+ expect(measureBoard(buildBoard({ areaScrollTop: 0 })).columns[0].cards).toEqual(expected);
+ container?.remove();
+ expect(measureBoard(buildBoard({ areaScrollTop: 90 })).columns[0].cards).toEqual(expected);
+ });
+
+ it("hands back each column's card area, and counts a column holding none", () => {
+ const board = buildBoard({ cardCounts: [ 0, 1 ] });
+
+ const { columns, areas } = measureBoard(board);
+
+ expect(columns[0].cards).toEqual([]);
+ expect(areas.get("To Do")).toBe(board.querySelector(".board-column-content"));
+ });
+
+ /** A collapsed column draws no card area at all. */
+ it("counts a column with no card area as holding no cards", () => {
+ const board = buildBoard();
+ board.querySelector(".board-column-content")?.remove();
+
+ const { columns, areas } = measureBoard(board);
+
+ expect(columns[0].cards).toEqual([]);
+ expect(areas.has("To Do")).toBe(false);
+ });
+
+ it("measures nothing for a board with no columns", () => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ place(container, { left: 0, top: 0, width: 100, height: 100 });
+
+ expect(measureBoard(container).columns).toEqual([]);
+ });
+});
+
+describe("reading a point against a measurement", () => {
+ /** What a move does: two rectangles read, whatever the board holds. */
+ it("finds the column and the place a card would take", () => {
+ const board = buildBoard();
+ const { columns, areas } = measureBoard(board);
+
+ // Over the second column on screen, which starts at -30 and runs 100 wide.
+ const column = columnAt(columns, toBoardX(board, 20));
+ expect(column?.value).toBe("Doing");
+
+ const area = areas.get("Doing");
+ if (!area) throw new Error("expected a card area");
+
+ // Its one card stands at 10 in the area's content and is 50 tall, so its middle is at 35.
+ // The area is 20 scrolled and starts 40 down the page, so that middle is at 55 on screen.
+ expect(cardInsertionIndex(column?.cards ?? [], toAreaY(area, 50))).toBe(0);
+ expect(cardInsertionIndex(column?.cards ?? [], toAreaY(area, 60))).toBe(1);
+ });
+
+ it("reads a point over the same column the same way however far the board is scrolled", () => {
+ for (const scrollLeft of [ 0, 200, 640 ]) {
+ const board = buildBoard({ scrollLeft });
+ const { columns } = measureBoard(board);
+
+ // Where the first column is drawn moves with the scrolling; what it measures to does
+ // not, which is what leaves a measurement good for the whole gesture.
+ const onScreen = 50 - scrollLeft + 10;
+ expect(toBoardX(board, onScreen)).toBe(10);
+ expect(columnAt(columns, toBoardX(board, onScreen))?.value).toBe("To Do");
+ board.remove();
+ }
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/drag_measure.ts b/apps/client/src/widgets/collections/board/drag_measure.ts
new file mode 100644
index 0000000000..d35db7c97f
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/drag_measure.ts
@@ -0,0 +1,74 @@
+import { type ColumnBox } from "./drag_geometry";
+
+/** What a drag measures once at its start, and reads for the rest of the gesture. */
+export interface BoardMeasurement {
+ /** The columns as drawn, in order, for {@link columnAt} and {@link columnInsertionIndex}. */
+ columns: ColumnBox[];
+ /** Each column's card area, which a point has to be read against to place a card in it. */
+ areas: Map<string, HTMLElement>;
+}
+
+/**
+ * Measures every column and card on the board.
+ *
+ * Called once when a drag starts. A gesture reads two rectangles per move afterwards, whatever the
+ * board holds, where measuring per move would read one for every card on it.
+ */
+export function measureBoard(container: HTMLElement): BoardMeasurement {
+ const origin = container.getBoundingClientRect().left - container.scrollLeft;
+ const columns: ColumnBox[] = [];
+ const areas = new Map<string, HTMLElement>();
+
+ for (const element of container.querySelectorAll<HTMLElement>(".board-column")) {
+ const value = element.dataset.column ?? "";
+ const rect = element.getBoundingClientRect();
+ const area = element.querySelector<HTMLElement>(".board-column-content");
+
+ if (area) {
+ areas.set(value, area);
+ }
+
+ columns.push({
+ value,
+ left: rect.left - origin,
+ width: rect.width,
+ top: rect.top,
+ height: rect.height,
+ cards: measureCards(area)
+ });
+ }
+
+ return { columns, areas };
+}
+
+/** A point in the board's content space, which its horizontal scrolling does not move columns in. */
+export function toBoardX(container: HTMLElement, clientX: number): number {
+ return clientX - container.getBoundingClientRect().left + container.scrollLeft;
+}
+
+/**
+ * A point in a card area's content space, which that column's vertical scrolling does not move its
+ * cards in.
+ */
+export function toAreaY(area: HTMLElement, clientY: number): number {
+ return clientY - area.getBoundingClientRect().top + area.scrollTop;
+}
+
+/**
+ * The cards of one column, in the area's content space.
+ *
+ * The dragged card is measured with the rest: the index this leads to names a place in the list the
+ * board holds, which is the list a move is expressed against.
+ */
+function measureCards(area: HTMLElement | null) {
+ if (!area) {
+ return [];
+ }
+
+ const top = area.getBoundingClientRect().top - area.scrollTop;
+
+ return [ ...area.querySelectorAll<HTMLElement>(".board-note") ].map((card) => {
+ const rect = card.getBoundingClientRect();
+ return { top: rect.top - top, height: rect.height };
+ });
+}
diff --git a/apps/client/src/widgets/collections/board/edge_scroll.spec.ts b/apps/client/src/widgets/collections/board/edge_scroll.spec.ts
new file mode 100644
index 0000000000..6092be6b5d
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/edge_scroll.spec.ts
@@ -0,0 +1,178 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { canScroll, createEdgeScroller, edgePull } from "./edge_scroll";
+
+describe("edgePull", () => {
+ /** A box from 100 to 500, with the pull reaching 50 in from each edge. */
+ const pull = (position: number) => edgePull(100, 500, position, 50);
+
+ it("pulls at nothing while the point stands clear of both edges", () => {
+ expect(pull(300)).toBe(0);
+ expect(pull(151)).toBe(0);
+ expect(pull(449)).toBe(0);
+ });
+
+ it("pulls harder the nearer the point comes to an edge", () => {
+ expect(pull(125)).toBeCloseTo(-0.5);
+ expect(pull(475)).toBeCloseTo(0.5);
+ expect(Math.abs(pull(110))).toBeGreaterThan(Math.abs(pull(140)));
+ });
+
+ it("pulls at full strength from the edge outwards", () => {
+ expect(pull(100)).toBe(-1);
+ expect(pull(-500)).toBe(-1);
+ expect(pull(500)).toBe(1);
+ expect(pull(5000)).toBe(1);
+ });
+
+ /** Both margins would meet, and every point would be pulled two ways at once. */
+ it("pulls at nothing in a box no wider than its own margins", () => {
+ expect(edgePull(0, 100, 10, 50)).toBe(0);
+ expect(edgePull(0, 100, 50, 50)).toBe(0);
+ });
+});
+
+describe("canScroll", () => {
+ function box({ offset = 50, size = 100, content = 400 } = {}) {
+ const element = document.createElement("div");
+ for (const [ name, value ] of Object.entries({
+ scrollLeft: offset, clientWidth: size, scrollWidth: content,
+ scrollTop: offset, clientHeight: size, scrollHeight: content
+ })) {
+ Object.defineProperty(element, name, { value, configurable: true, writable: true });
+ }
+ return element;
+ }
+
+ it("knows there is more to reach in either direction", () => {
+ expect(canScroll(box(), "x", -1)).toBe(true);
+ expect(canScroll(box(), "x", 1)).toBe(true);
+ expect(canScroll(box(), "y", -1)).toBe(true);
+ });
+
+ it("knows an end when it reaches one", () => {
+ expect(canScroll(box({ offset: 0 }), "x", -1)).toBe(false);
+ expect(canScroll(box({ offset: 0 }), "x", 1)).toBe(true);
+ expect(canScroll(box({ offset: 300 }), "y", 1)).toBe(false);
+ expect(canScroll(box({ offset: 300 }), "y", -1)).toBe(true);
+ });
+
+ it("knows a container with nothing to scroll", () => {
+ const fits = box({ offset: 0, size: 400, content: 400 });
+ expect(canScroll(fits, "x", 1)).toBe(false);
+ expect(canScroll(fits, "x", -1)).toBe(false);
+ });
+});
+
+describe("createEdgeScroller", () => {
+ let scroller: ReturnType<typeof createEdgeScroller> | undefined;
+
+ beforeEach(() => vi.useFakeTimers());
+
+ afterEach(() => {
+ scroller?.stop();
+ scroller = undefined;
+ vi.useRealTimers();
+ });
+
+ /** A 400x400 box on screen at 0,0 holding content four times its size. */
+ function container() {
+ const element = document.createElement("div");
+ element.getBoundingClientRect = () => ({
+ left: 0, top: 0, right: 400, bottom: 400, width: 400, height: 400
+ }) as DOMRect;
+ for (const [ name, value ] of Object.entries({
+ clientWidth: 400, scrollWidth: 1600, clientHeight: 400, scrollHeight: 1600
+ })) {
+ Object.defineProperty(element, name, { value, configurable: true });
+ }
+ element.scrollLeft = 200;
+ element.scrollTop = 200;
+ return element;
+ }
+
+ it("walks a container along while the pointer is held at its edge", () => {
+ const element = container();
+ scroller = createEdgeScroller();
+
+ scroller.update([ { element, axis: "x" } ], 395, 200);
+ vi.advanceTimersByTime(200);
+
+ expect(element.scrollLeft).toBeGreaterThan(200);
+ expect(element.scrollTop).toBe(200);
+ });
+
+ it("walks it the other way at the other edge", () => {
+ const element = container();
+ scroller = createEdgeScroller();
+
+ scroller.update([ { element, axis: "x" } ], 5, 200);
+ vi.advanceTimersByTime(200);
+
+ expect(element.scrollLeft).toBeLessThan(200);
+ });
+
+ it("leaves it alone while the pointer stands clear of the edges", () => {
+ const element = container();
+ scroller = createEdgeScroller();
+
+ scroller.update([ { element, axis: "x" } ], 200, 200);
+ vi.advanceTimersByTime(500);
+
+ expect(element.scrollLeft).toBe(200);
+ });
+
+ /** A card carried into a corner walks the board along and the column down at once. */
+ it("walks every container it is given", () => {
+ const board = container();
+ const column = container();
+ scroller = createEdgeScroller();
+
+ scroller.update([ { element: board, axis: "x" }, { element: column, axis: "y" } ], 395, 395);
+ vi.advanceTimersByTime(200);
+
+ expect(board.scrollLeft).toBeGreaterThan(200);
+ expect(column.scrollTop).toBeGreaterThan(200);
+ });
+
+ it("says so after each frame that moved something", () => {
+ const element = container();
+ const onScroll = vi.fn();
+ scroller = createEdgeScroller({ onScroll });
+
+ scroller.update([ { element, axis: "x" } ], 395, 200);
+ vi.advanceTimersByTime(100);
+ expect(onScroll).toHaveBeenCalled();
+
+ // Back to the middle: nothing moves, so nothing is reported.
+ onScroll.mockClear();
+ scroller.update([ { element, axis: "x" } ], 200, 200);
+ vi.advanceTimersByTime(100);
+ expect(onScroll).not.toHaveBeenCalled();
+ });
+
+ it("stops when it is told to, and stays stopped", () => {
+ const element = container();
+ scroller = createEdgeScroller();
+
+ scroller.update([ { element, axis: "x" } ], 395, 200);
+ vi.advanceTimersByTime(100);
+ const reached = element.scrollLeft;
+
+ scroller.stop();
+ vi.advanceTimersByTime(500);
+ expect(element.scrollLeft).toBe(reached);
+ });
+
+ it("stops at the end rather than counting past it", () => {
+ const element = container();
+ element.scrollLeft = 1200;
+ Object.defineProperty(element, "scrollLeft", { value: 1200, configurable: true });
+ scroller = createEdgeScroller();
+
+ scroller.update([ { element, axis: "x" } ], 395, 200);
+ vi.advanceTimersByTime(300);
+
+ expect(element.scrollLeft).toBe(1200);
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/edge_scroll.ts b/apps/client/src/widgets/collections/board/edge_scroll.ts
new file mode 100644
index 0000000000..357a796316
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/edge_scroll.ts
@@ -0,0 +1,121 @@
+/**
+ * Scrolls a container while something is carried near its edge.
+ *
+ * The board scrolls sideways and a column's cards scroll up and down, so a target names which of the
+ * two axes it answers for. Several can be pulled at once: a card carried into the bottom corner of
+ * the last column walks the board along and the column down together.
+ */
+
+/** How near an edge the pointer comes before the container starts to move, in pixels. */
+const MARGIN = 60;
+
+/** How fast it moves with the pointer at the very edge, in pixels a second. */
+const SPEED = 1350;
+
+export interface ScrollTarget {
+ element: HTMLElement;
+ axis: "x" | "y";
+}
+
+export interface EdgeScrollOptions {
+ margin?: number;
+ speed?: number;
+ /** Called after each frame that moved something, the places on screen having changed. */
+ onScroll?: () => void;
+}
+
+/**
+ * How hard a point pulls a box towards one of its edges.
+ *
+ * Answers -1 at the near edge and +1 at the far one, easing off to 0 at the inner limit of the
+ * margin, so the pull grows as the pointer closes on the edge rather than switching on at it. A
+ * point outside the box pulls at full strength, which is what carries something held beyond the
+ * board along.
+ *
+ * @param near the box's near edge, and @param far its far one, along the axis in question.
+ * @param position the point, in the same terms.
+ * @param margin how far in from each edge the pull reaches.
+ */
+export function edgePull(near: number, far: number, position: number, margin: number): number {
+ if (far - near <= margin * 2) {
+ return 0;
+ }
+
+ if (position < near + margin) {
+ return -Math.min(1, (near + margin - position) / margin);
+ }
+
+ if (position > far - margin) {
+ return Math.min(1, (position - (far - margin)) / margin);
+ }
+
+ return 0;
+}
+
+/** Whether a container has anywhere left to go in the given direction. */
+export function canScroll(element: HTMLElement, axis: "x" | "y", pull: number): boolean {
+ const [ offset, size, content ] = axis === "x"
+ ? [ element.scrollLeft, element.clientWidth, element.scrollWidth ]
+ : [ element.scrollTop, element.clientHeight, element.scrollHeight ];
+
+ return pull < 0 ? offset > 0 : offset < content - size;
+}
+
+export function createEdgeScroller({
+ margin = MARGIN, speed = SPEED, onScroll
+}: EdgeScrollOptions = {}) {
+ let targets: ScrollTarget[] = [];
+ let point = { x: 0, y: 0 };
+ let frame: number | undefined;
+ let previous = 0;
+
+ const step = (now: number) => {
+ const elapsed = Math.min(now - previous, 50);
+ previous = now;
+ let moved = false;
+
+ for (const { element, axis } of targets) {
+ const box = element.getBoundingClientRect();
+ const pull = axis === "x"
+ ? edgePull(box.left, box.right, point.x, margin)
+ : edgePull(box.top, box.bottom, point.y, margin);
+
+ if (!pull || !canScroll(element, axis, pull)) continue;
+
+ const distance = pull * speed * elapsed / 1000;
+ if (axis === "x") {
+ element.scrollLeft += distance;
+ } else {
+ element.scrollTop += distance;
+ }
+ moved = true;
+ }
+
+ if (moved) {
+ onScroll?.();
+ }
+
+ frame = targets.length ? requestAnimationFrame(step) : undefined;
+ };
+
+ return {
+ /** Points it at the containers to walk along, and at where the pointer stands. */
+ update(next: ScrollTarget[], clientX: number, clientY: number) {
+ targets = next;
+ point = { x: clientX, y: clientY };
+
+ if (targets.length && frame === undefined) {
+ previous = performance.now();
+ frame = requestAnimationFrame(step);
+ }
+ },
+
+ stop() {
+ targets = [];
+ if (frame !== undefined) {
+ cancelAnimationFrame(frame);
+ frame = undefined;
+ }
+ }
+ };
+}
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index 09b51ddd8e..9bbbc83770 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -36,6 +36,12 @@
--card-padding: 0.6em;
}
+/* Lays nothing out: the columns stay the board's own flex items, and Preact has a parent of its own
+ to move them within. */
+.board-view-container .board-columns {
+ display: contents;
+}
+
.board-view-container {
height: 100%;
display: flex;
@@ -55,7 +61,7 @@
cursor: grabbing;
}
-.board-view-container.pannable > .board-column,
+.board-view-container.pannable .board-column,
.board-view-container.pannable > .board-add-column {
cursor: auto;
}
@@ -66,6 +72,15 @@ body.mobile .board-view-container {
scroll-behavior: smooth;
}
+/* Both of the above fight a scroll written a frame at a time, which is how the board walks itself
+ along while something is carried to its edge: smooth turns each step into an animation the next
+ step restarts, and snapping pulls the board back to the nearest column. The column's own cards
+ scroll either way, having neither. */
+body.mobile .board-view-container.board-dragging {
+ scroll-snap-type: none;
+ scroll-behavior: auto;
+}
+
.board-view-container .board-column {
width: 250px;
flex-shrink: 0;
@@ -373,14 +388,57 @@ body.mobile .board-view-container .board-add-column {
cursor: pointer;
}
-.board-view-container .board-note.dragging {
- cursor: move;
- opacity: 0.5;
- transform: rotate(5deg);
+/* The copy that follows the pointer. Positioned against the window, so the column's own scrolling
+ cannot cut it off, and left out of hit testing so it never stands in front of what it is over.
+ No `transform` here: the gesture writes the movement and the shrink together, and a rule of its
+ own would replace both. */
+/* A carried column is cut to a set height by the gesture, so a tall one does not cover the board
+ it is being placed on; what it holds is clipped rather than reflowed. */
+/* Takes no room and lays nothing out: what it holds is placed against the window, and it stands
+ inside the board so that the board's own styling still reaches it. */
+.board-view-container .board-drag-layer {
+ position: fixed;
+ top: 0;
+ inset-inline-start: 0;
+ width: 0;
+ height: 0;
+}
+
+.board-view-container .board-column.board-drag-preview {
+ overflow: hidden;
+}
+
+/* The card is focused by the press that picks it up and then taken out of the page, which drops the
+ focus; the copy carries the ring on so what is being moved still reads as what is focused. */
+.board-view-container .board-note.board-drag-preview {
+ outline: 3px solid var(--board-focus-outline-color, var(--board-focus-outline-plain-color));
+ outline-offset: 0;
+}
+
+.board-view-container .board-note.board-drag-preview,
+.board-view-container .board-column.board-drag-preview {
+ position: fixed;
+ margin: 0;
+ /* The card's own transition would animate towards each frame's position instead of taking it. */
+ transition: none;
+ will-change: transform;
z-index: 1000;
+ pointer-events: none;
+ cursor: move;
+ opacity: 0.85;
box-shadow: 4px 8px 16px rgba(0, 0, 0, 0.5);
}
+/* While a card is carried, so the page does not take the touch for a scroll. */
+.board-view-container.board-dragging {
+ touch-action: none;
+}
+
+/* A long press on a card is how it is picked up, not how it is selected or looked up. */
+.board-view-container .board-note {
+ -webkit-touch-callout: none;
+}
+
.board-view-container .board-note.editing,
.board-view-container .board-new-item.editing {
box-shadow: 2px 4px 8px rgba(0, 0, 0, 0.2);
@@ -497,22 +555,6 @@ body.mobile .board-view-container .board-add-column {
text-align: center;
}
-.board-drag-preview {
- position: fixed;
- z-index: 10000;
- pointer-events: none;
- opacity: 0.8;
- transform: rotate(5deg);
- box-shadow: 4px 8px 16px rgba(0, 0, 0, 0.5);
- background-color: var(--main-background-color);
- border: 1px solid var(--main-border-color);
- border-radius: 5px;
- padding: 0.5em;
- font-size: 0.9em;
- max-width: 200px;
- word-wrap: break-word;
-}
-
/* The menu is drawn outside the board, so the columns it lists are named rather than reached
through `.board-view`. */
.dropdown-item.board-current-column {
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index d881906b97..00d6d97acf 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -311,12 +311,9 @@ describe("Collapsed board columns", () => {
expect(isCollapsed(mountPoint, 0)).toBe(false);
});
- it("keeps the collapsed column movable and stored as collapsed", async () => {
+ it("opens a collapsed column without writing anything", async () => {
const { mountPoint } = await setup();
- // The header is the drag handle whether or not the column is drawn as a strip.
- expect(columnAt(mountPoint, 0).querySelector("h3")?.getAttribute("draggable"))
- .toBe("true");
// Opening it by selection is not a change to the config, so nothing is written at all.
await select(mountPoint, 0);
expect(isCollapsed(mountPoint, 0)).toBe(false);
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index d00006ba47..8e024bf475 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -2,9 +2,11 @@ import "./index.css";
import clsx from "clsx";
-import { createContext, TargetedKeyboardEvent } from "preact";
+import { createContext, Fragment, TargetedKeyboardEvent } from "preact";
import { createPortal } from "preact/compat";
-import { Dispatch, StateUpdater, useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+import {
+ Dispatch, StateUpdater, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState
+} from "preact/hooks";
import FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
@@ -26,6 +28,8 @@ import { onWheelHorizontalScroll } from "../../widget_utils";
import { useDragPan } from "../../react/drag_pan";
import { ViewModeProps } from "../interface";
import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";
+import { useBoardDrag } from "./board_drag";
+import { movesColumn } from "./drag_geometry";
import BoardApi from "./api";
import { DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN } from "./columns";
import Column from "./column";
@@ -69,6 +73,8 @@ interface CardDrag {
branchId: string;
fromColumn: string;
index: number;
+ /** How tall the card stands, absent for a drag from the note tree, which carries no card. */
+ height?: number;
}
interface ColumnDrag {
@@ -197,12 +203,11 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const [ byColumn, setByColumn ] = useState<ColumnMap>();
const [ columns, setColumns ] = useState<string[]>();
const [ isInRelationMode, setIsRelationMode ] = useState(false);
- const [ draggedCard, setDraggedCard ] = useState<{ noteId: string, branchId: string, fromColumn: string, index: number } | null>(null);
+ const [ draggedCard, setDraggedCard ] = useState<CardDrag | null>(null);
const [ dropTarget, setDropTarget ] = useState<string | null>(null);
const [ dropPosition, setDropPosition ] = useState<{ column: string, index: number } | null>(null);
const [ draggedColumn, setDraggedColumn ] = useState<ColumnDrag | null>(null);
const [ columnDropPosition, setColumnDropPosition ] = useState<number | null>(null);
- const [ columnHoverIndex, setColumnHoverIndex ] = useState<number | null>(null);
const [ branchIdToEdit, setBranchIdToEdit ] = useState<string>();
const [ columnNameToEdit, setColumnNameToEdit ] = useState<string>();
const [ columnLimitToEdit, setColumnLimitToEdit ] = useState<string>();
@@ -333,9 +338,86 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
});
}
+ // The gesture drives the same state a drag from the note tree does, so the placeholders and the
+ // card's own dimming are drawn from one place whichever brought the card here.
+ const { isDragging: isDraggingItem, remeasure } = useBoardDrag(containerRef, {
+ onCardStart: (card) => setDraggedCard({
+ noteId: card.noteId,
+ branchId: byColumn?.get(card.fromColumn)?.[card.index]?.branch.branchId ?? "",
+ fromColumn: card.fromColumn,
+ index: card.index,
+ height: card.height
+ }),
+ onCardMove: (position, inside) => {
+ setDropTarget(position?.column ?? null);
+ setDropPosition(position);
+ // Answers for what a `dragover` did, for a collapsed column the card is actually over:
+ // one merely passed near keeps to itself, and one already opened stays open, since
+ // closing it under a drag would move every column after it.
+ if (position && inside && storedColumns.get(position.column)?.collapsed) {
+ setActiveColumn(position.column);
+ }
+ },
+ onCardEnd: (card, position) => {
+ const branchId = byColumn?.get(card.fromColumn)?.[card.index]?.branch.branchId;
+ if (position && branchId) {
+ api.moveWithinBoard(
+ card.noteId, branchId, card.index, position.index,
+ card.fromColumn, position.column);
+ }
+ setDraggedCard(null);
+ setDropTarget(null);
+ setDropPosition(null);
+ // Asked for by name: the card is drawn again where it landed, and a card that crossed
+ // columns is drawn as a new element, so the one that was focused is gone.
+ focusCard(card.noteId);
+ if (position) {
+ revealColumn(position.column);
+ }
+ },
+ onColumnStart: (column, index, size) => setDraggedColumn({ column, index, size }),
+ onColumnMove: setColumnDropPosition,
+ onColumnEnd: (from, to) => {
+ if (to !== null && movesColumn(from, to)) {
+ handleColumnDrop(from, to);
+ }
+ setDraggedColumn(null);
+ setColumnDropPosition(null);
+ }
+ });
+
+ // A column opened to take the card moves every column after it, which the measurement predates.
+ useLayoutEffect(() => {
+ if (isDraggingItem) {
+ remeasure();
+ }
+ }, [ isDraggingItem, remeasure, activeColumn, shownColumns ]);
+
// Only the board's own background, so a press on a column, a card or the button that adds one
- // is left to whatever it belongs to.
- const { isPannable, isPanning } = useDragPan(containerRef);
+ // is left to whatever it belongs to. Suppressed while a card is carried: the gesture owns the
+ // pointer, and the board must not slide under it.
+ const { isPannable, isPanning } = useDragPan(containerRef, { disabled: isDraggingItem });
+
+ /**
+ * Brings a column to the middle of the screen, for a board that scrolls one column at a time.
+ *
+ * Snapping is off while something is carried, so letting go leaves the board wherever the
+ * gesture took it and the reader looking at two half-columns. Asked for on the next frame: the
+ * board is drawn again around the card that landed, and the column moves with it.
+ */
+ const revealColumn = useCallback((column: string) => {
+ if (!isMobile()) return;
+
+ requestAnimationFrame(() => {
+ const columns = containerRef.current?.querySelectorAll<HTMLElement>(".board-column");
+ for (const element of columns ?? []) {
+ if (element.dataset.column === column) {
+ element.scrollIntoView({ inline: "center", block: "nearest" });
+ return;
+ }
+ }
+ });
+ }, []);
// The board is not drawn afresh for another note, so the column opened on one would otherwise
// still be open on the next, over whatever that board stores for a column of the same name.
@@ -389,39 +471,12 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
}
});
- const handleColumnDragOver = useCallback((e: DragEvent) => {
- if (!draggedColumn) return;
- e.preventDefault();
- }, [draggedColumn]);
-
- const handleColumnHover = useCallback((index: number, mouseX: number, columnRect: DOMRect) => {
- if (!draggedColumn) return;
-
- const columnMiddle = columnRect.left + columnRect.width / 2;
-
- // Determine if we should insert before or after this column
- const insertBefore = mouseX < columnMiddle;
-
- // Calculate the target position
- const targetIndex = insertBefore ? index : index + 1;
-
- setColumnDropPosition(targetIndex);
- }, [draggedColumn]);
-
// Measured rather than styled: a collapsed column is a strip, and the placeholder stands in
// for whichever column is being dragged.
const placeholderSize = draggedColumn?.size?.width
? { width: `${draggedColumn.size.width}px`, height: `${draggedColumn.size.height}px` }
: undefined;
- const handleContainerDrop = useCallback((e: DragEvent) => {
- e.preventDefault();
- if (draggedColumn && columnDropPosition !== null) {
- handleColumnDrop(draggedColumn.index, columnDropPosition);
- }
- setColumnHoverIndex(null);
- }, [draggedColumn, columnDropPosition, handleColumnDrop]);
-
return (
<div className="board-view">
<CollectionProperties note={parentNote} />
@@ -434,12 +489,21 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
panning: isPanning
})}
onKeyDown={handleKeyDown}
- onDragOver={handleColumnDragOver}
- onDrop={handleContainerDrop}
onWheel={onWheelHorizontalScroll}
>
+ {/* The columns are keyed by value, so a reorder moves each column's
+ element with it rather than repurposing elements in place, which would
+ carry the `collapsed` class from one column to another and run its width
+ transition on a column that never collapsed.
+
+ They are wrapped because a moved element is placed before its next
+ sibling, and the last ones have none: in a parent that also holds the
+ button, the layer and the overlays, Preact appends them past all three.
+ The wrapper lays nothing out, so the columns are still the board's own
+ flex items. */}
+ <div className="board-columns">
{shownColumns.map((column, index) => (
- <>
+ <Fragment key={column}>
{columnDropPosition === index && (
<div
className="column-drop-placeholder show"
@@ -464,17 +528,18 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
onFocusColumn={focusColumn}
onFocusCard={focusCard}
columnItems={byColumn.get(column)}
- isDraggingColumn={draggedColumn?.column === column}
- onColumnHover={handleColumnHover}
- isAnyColumnDragging={!!draggedColumn}
/>
- </>
+ </Fragment>
))}
{columnDropPosition === shownColumns.length && draggedColumn && (
<div className="column-drop-placeholder show" style={placeholderSize} />
)}
+ </div>
<AddNewColumn api={api} isInRelationMode={isInRelationMode} />
+ {/* Where what is being carried is put. Preact draws the layer and never
+ its contents, so the copy is not among the children it places. */}
+ <div className="board-drag-layer" />
{/* Out of the board and onto the page: the dialog is positioned against
the window, and Bootstrap puts its backdrop on the body, so a stacking
context above the board would trap it underneath. */}
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
index 872c2b9ac2..e74fb5fa72 100644
--- a/apps/client/src/widgets/collections/board/keyboard.ts
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -82,8 +82,8 @@ export interface BoardKeyboardOptions {
* handlers keep what is theirs (F2 to rename, Enter to add a card, typing to start one).
*
* Focus follows what is under it rather than where it sits: a card moved to another column is
- * drawn as a new element, and columns are drawn unkeyed, so a header would otherwise be left
- * focused on whichever column took its place.
+ * drawn as a new element, and a column moved in the page is blurred by the browser, so a header
+ * would otherwise be left focused on nothing.
*/
export function useBoardKeyboard({
containerRef, columns, byColumn, api, moveColumn, insertColumn, setActiveColumn
@@ -98,8 +98,8 @@ export function useBoardKeyboard({
if (!pending || !container) return;
if (!("noteId" in pending.intent)) {
- // The columns are drawn unkeyed, so what was focused is now over whichever column took
- // the old one's place. Focus is pointed at the right one and the hold is done with.
+ // Moving a focused element blurs it, so the header is focused again by name once the
+ // board has drawn it in its new place, and the hold is done with.
const element = findInColumn(container, pending.intent.column, pending.intent.part);
if (element) {
element.focus();
@@ -122,8 +122,8 @@ export function useBoardKeyboard({
/**
* Puts focus on a column's heading once the board has drawn it again, for a move made from
- * somewhere other than the keyboard. The columns are drawn unkeyed, so an element held onto
- * across the move would be left standing over whichever column took the old one's place.
+ * somewhere other than the keyboard. The browser blurs an element it moves, so an element
+ * held onto across the move would be left focused on nothing.
*/
const focusColumn = useCallback((column: string) => {
pendingFocus.current = { intent: { column, part: "header" } };
@@ -472,8 +472,8 @@ function move(
/**
* Moves the column focus is in, answering with what to put focus back on. Whatever was focused
- * stays focused: the columns are drawn unkeyed, so the element would otherwise be left standing
- * over whichever column took the old one's place.
+ * stays focused: the browser blurs an element it moves, so it would otherwise be left focused on
+ * nothing.
*/
function shiftColumn(
spot: Spot,