Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: add fallback native drag and drop support for cards (when Ctrl key is pressed)

Adorian Doran703d233270eb
diff --git a/apps/client/src/widgets/collections/board/board_drag.spec.tsx b/apps/client/src/widgets/collections/board/board_drag.spec.tsx
index 0c5bc7ac16..9cfa974081 100644
--- a/apps/client/src/widgets/collections/board/board_drag.spec.tsx
+++ b/apps/client/src/widgets/collections/board/board_drag.spec.tsx
@@ -590,6 +590,52 @@ describe("useBoardDrag, carrying a card", () => {
expect(calls.start).toHaveLength(0);
});
+ describe("the drag Ctrl hands to the browser", () => {
+ /**
+ * Nothing else reaches the note tree or a board in another split, so a Ctrl press makes the
+ * card natively draggable and stands back. `draggable` is set on the press rather than kept
+ * on the card, or every ordinary drag would become a native one.
+ */
+ it("makes the card draggable and opens no gesture of its own", () => {
+ setup();
+ const element = card("n1");
+ // `toBeFalsy`, not `toBe(false)`: happy-dom does not reflect the `draggable` attribute
+ // onto the property, so an element nothing has set it on reads undefined.
+ expect(element.draggable).toBeFalsy();
+
+ press(element, 50, 60, "mouse", { ctrlKey: true });
+ expect(element.draggable).toBe(true);
+
+ move(90, 90);
+ expect(calls.start).toHaveLength(0);
+ });
+
+ it("puts `draggable` back, whether the press became a drag or stayed a click", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 50, 60, "mouse", { ctrlKey: true });
+ act(() => { element.dispatchEvent(new Event("dragend", { bubbles: true })); });
+ expect(element.draggable).toBe(false);
+
+ // A Ctrl click that never moved delivers no `dragend`, so the release clears it.
+ press(element, 50, 60, "mouse", { ctrlKey: true });
+ release(50, 60);
+ expect(element.draggable).toBe(false);
+ });
+
+ it("leaves an ordinary press to the board's own gesture", () => {
+ setup();
+ const element = card("n1");
+
+ press(element, 50, 60);
+ move(90, 90);
+
+ expect(element.draggable).toBeFalsy();
+ expect(calls.start).toHaveLength(1);
+ });
+ });
+
describe("carrying a column", () => {
it("takes hold of it by its heading, and says what it measures", () => {
setup();
@@ -770,18 +816,26 @@ describe("useBoardDrag, carrying a card", () => {
}) as DOMRect;
}
- function pointer(type: string, clientX: number, clientY: number, pointerType: string) {
+ function pointer(
+ type: string, clientX: number, clientY: number, pointerType: string,
+ modifiers: { ctrlKey?: boolean } = {}
+ ) {
const event = new Event(type, { bubbles: true, cancelable: true });
for (const [ name, value ] of Object.entries({
- clientX, clientY, pointerId: 1, button: 0, pointerType
+ clientX, clientY, pointerId: 1, button: 0, pointerType, ...modifiers
})) {
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 press(
+ target: HTMLElement, x: number, y: number, pointerType = "mouse",
+ modifiers: { ctrlKey?: boolean } = {}
+ ) {
+ act(() => {
+ target.dispatchEvent(pointer("pointerdown", x, y, pointerType, modifiers));
+ });
}
function move(x: number, y: number, pointerType = "mouse") {
diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.ts
index 328e4911e0..c573966d88 100644
--- a/apps/client/src/widgets/collections/board/board_drag.ts
+++ b/apps/client/src/widgets/collections/board/board_drag.ts
@@ -122,6 +122,8 @@ export function useBoardDrag(
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);
+ /** The card a Ctrl press made natively draggable, which `disarm` puts back. */
+ const armed = useRef<HTMLElement | 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
@@ -290,6 +292,17 @@ export function useBoardDrag(
// Anything the card or the heading offers in its own right keeps its press.
if (!target || target.closest("input, textarea, button, a")) return;
+ // Ctrl hands the press to the browser's own drag, which is the only one that reaches
+ // outside the board: the note tree, and a board in another split. `draggable` is set
+ // here rather than left on the card so that an ordinary press still opens the board's
+ // own gesture, and cleared again in `disarm`.
+ const held = target.closest<HTMLElement>(".board-note");
+ if (held && !held.classList.contains("editing") && (event.ctrlKey || event.metaKey)) {
+ held.draggable = true;
+ armed.current = held;
+ return;
+ }
+
const started = startCard(target, latest.current.carriedWith)
?? startColumn(target, container);
if (!started) return;
@@ -351,7 +364,23 @@ export function useBoardDrag(
}
};
+ /**
+ * Takes `draggable` off the card a Ctrl press armed.
+ *
+ * Left on, the next ordinary press on that card would start a native drag instead of the
+ * board's own. Called from `dragend` for a press that became a drag, and from `pointerup`
+ * for a Ctrl click that did not: a native drag delivers no `pointerup`.
+ */
+ const disarm = () => {
+ if (armed.current) {
+ armed.current.draggable = false;
+ armed.current = null;
+ }
+ };
+
const onPointerUp = (event: PointerEvent) => {
+ disarm();
+
const held = gesture.current;
if (!held || event.pointerId !== held.pointerId) return;
@@ -440,6 +469,7 @@ export function useBoardDrag(
};
container.addEventListener("contextmenu", onContextMenu, { capture: true });
+ container.addEventListener("dragend", disarm);
container.addEventListener("pointerdown", onPointerDown);
container.addEventListener("pointermove", onPointerMove);
container.addEventListener("pointerup", onPointerUp);
@@ -450,7 +480,9 @@ export function useBoardDrag(
return () => {
close(true);
+ disarm();
container.removeEventListener("contextmenu", onContextMenu, { capture: true });
+ container.removeEventListener("dragend", disarm);
container.removeEventListener("pointerdown", onPointerDown);
container.removeEventListener("pointermove", onPointerMove);
container.removeEventListener("pointerup", onPointerUp);
diff --git a/apps/client/src/widgets/collections/board/card.spec.tsx b/apps/client/src/widgets/collections/board/card.spec.tsx
index 2db6343182..6ac5ecac8a 100644
--- a/apps/client/src/widgets/collections/board/card.spec.tsx
+++ b/apps/client/src/widgets/collections/board/card.spec.tsx
@@ -371,6 +371,40 @@ describe("Board card", () => {
}
});
+ describe("the drag that carries a card off the board", () => {
+ it("fills the drag with the one card, in the two entries the tree reads", async () => {
+ const { first } = await renderBoard();
+ const data = new Map<string, string>();
+
+ fireDrag(card(first), "dragstart", { setData: (type: string, value: string) => data.set(type, value) });
+
+ expect(data.get("application/x-fancytree-node")).toBe("");
+ expect(JSON.parse(data.get("text") ?? "[]")).toEqual([
+ { noteId: first, branchId: expect.any(String), title: "First" }
+ ]);
+ });
+
+ /** A drag started on a card that is picked out takes everything picked out with it. */
+ it("fills it with every card picked out, where the one dragged is among them", async () => {
+ const { first, second } = await renderBoard();
+ const data = new Map<string, string>();
+
+ await act(async () => {
+ card(first).dispatchEvent(new MouseEvent(
+ "click", { bubbles: true, cancelable: true, detail: 1, ctrlKey: true }));
+ });
+ await act(async () => {
+ card(second).dispatchEvent(new MouseEvent(
+ "click", { bubbles: true, cancelable: true, detail: 1, ctrlKey: true }));
+ });
+
+ fireDrag(card(first), "dragstart", { setData: (type: string, value: string) => data.set(type, value) });
+
+ expect(JSON.parse(data.get("text") ?? "[]").map((entry: { title: string }) => entry.title))
+ .toEqual([ "First", "Second" ]);
+ });
+ });
+
/**
* The card is the same height either way, so opening the editor neither drops what the card
* shows nor moves the cards below it.
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index 537a580ba1..a46a6c8dbd 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -24,6 +24,7 @@ import {
import { TooltipIcon } from "../../react/Icon";
import { HighlightedText } from "../../react/RawHtml";
import { useIsSelected, useSelection } from "../../react/selection";
+import { type DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";
function Card({
api,
@@ -163,6 +164,27 @@ function Card({
api.openNote(note.noteId);
}, [ api, note, column, selection ]);
+ /**
+ * Fills the drag with what the note tree reads, for the native drag a Ctrl press arms in
+ * `board_drag.ts`. Carries the whole selection where this card is part of one.
+ *
+ * The same two entries the tree writes, so a card reaches everything a note dragged from the
+ * tree does: `TREE_CLIPBOARD_TYPE` says the drag holds notes, `text` says which.
+ */
+ const handleDragStart = useCallback((e: DragEvent) => {
+ const carried = isSelected
+ ? api.getCards(selection.keys)
+ : [ { note, branch } ];
+ const dragged: DragData[] = carried.map((item) => ({
+ noteId: item.note.noteId,
+ branchId: item.branch.branchId,
+ title: item.note.title
+ }));
+
+ e.dataTransfer?.setData(TREE_CLIPBOARD_TYPE, "");
+ e.dataTransfer?.setData("text", JSON.stringify(dragged));
+ }, [ api, note, branch, isSelected, selection ]);
+
const handleEdit = useCallback((e: MouseEvent) => {
e.stopPropagation(); // don't also open the note
setBranchIdToEdit(branch.branchId);
@@ -244,6 +266,7 @@ function Card({
}}
data-note-id={note.noteId}
onContextMenu={handleContextMenu}
+ onDragStart={handleDragStart}
onClick={!isEditing ? handleClick : undefined}
onKeyDown={handleKeyDown}
tabIndex={300}
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 094fadc513..e26965c6c0 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Modal as BootstrapModal } from "bootstrap";
+import appContext from "../../../components/app_context";
import Component from "../../../components/component";
import contextMenu from "../../../menus/context_menu";
import dialog from "../../../services/dialog";
@@ -788,10 +789,15 @@ describe("A board in a tab the reader is not looking at", () => {
});
// The context the board belongs to, reached the way `useNoteContext` reaches it: from the
- // nearest ancestor carrying one.
- let active = true;
+ // nearest ancestor carrying one. The board compares main contexts, so the tab is what the
+ // stub stands for and a split pane of it would answer with the same one.
+ const tab = {};
+ const otherTab = {};
+ let shown: object = tab;
const host = new Component();
- Object.assign(host, { noteContext: { isActive: () => active } });
+ Object.assign(host, { noteContext: { getMainContext: () => tab } });
+ const previousTabManager = appContext.tabManager;
+ appContext.tabManager = { getActiveMainContext: () => shown } as never;
const mountPoint = document.createElement("div");
container = mountPoint;
@@ -821,8 +827,8 @@ describe("A board in a tab the reader is not looking at", () => {
await draw();
expect(columnOf("First")).toBe("To Do");
- // The card moves column while the tab is in the background.
- active = false;
+ // The card moves column while another tab is the one being looked at.
+ shown = otherTab;
for (const attribute of froca.getNoteFromCache("one")?.getAttributes() ?? []) {
if (attribute.name === "status") attribute.value = "Done";
}
@@ -830,9 +836,71 @@ describe("A board in a tab the reader is not looking at", () => {
expect(columnOf("First")).toBe("To Do");
// Looked at again, it catches up with what it missed.
- active = true;
+ shown = tab;
await draw();
expect(columnOf("First")).toBe("Done");
+
+ appContext.tabManager = previousTabManager;
+ });
+
+ /**
+ * `getActiveMainContext` names one pane across the whole app, so a board sharing a tab with the
+ * focused pane is on screen and redraws: a card dropped onto it from another split appears at
+ * once rather than waiting for something to force a refresh.
+ */
+ it("redraws for a change while it is the split the reader is not focused on", async () => {
+ const note = buildNote({
+ title: "Board",
+ "#collection": "",
+ "#viewType": "board",
+ children: [
+ { id: "split1", title: "First", "#status": "To Do" },
+ { id: "split2", title: "Second", "#status": "Done" }
+ ]
+ });
+
+ // One tab, and the board is in a pane of it that does not hold the focus.
+ const tab = {};
+ const host = new Component();
+ Object.assign(host, { noteContext: { getMainContext: () => tab } });
+ const previousTabManager = appContext.tabManager;
+ appContext.tabManager = { getActiveMainContext: () => tab } as never;
+
+ const mountPoint = document.createElement("div");
+ container = mountPoint;
+ document.body.appendChild(mountPoint);
+
+ const draw = async () => {
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={host}>
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={{ columns: [ { value: "To Do" }, { value: "Done" } ] }}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await act(async () => { await flush(); });
+ };
+
+ const columnOf = (title: string) => [ ...mountPoint.querySelectorAll(".board-column") ]
+ .find(column => [ ...column.querySelectorAll(".board-note") ]
+ .some(card => card.textContent?.includes(title)))
+ ?.getAttribute("data-column");
+
+ await draw();
+ expect(columnOf("First")).toBe("To Do");
+
+ for (const attribute of froca.getNoteFromCache("split1")?.getAttributes() ?? []) {
+ if (attribute.name === "status") attribute.value = "Done";
+ }
+ await draw();
+ expect(columnOf("First")).toBe("Done");
+
+ appContext.tabManager = previousTabManager;
});
});
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index a86cb02054..67c88240bf 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -11,6 +11,7 @@ import {
import { type HighlightedTokenInfo, normalizeBoardGroupBy } from "@triliumnext/commons";
+import appContext from "../../../components/app_context";
import FNote from "../../../entities/fnote";
import attributes from "../../../services/attributes";
import froca from "../../../services/froca";
@@ -671,9 +672,15 @@ export default function BoardView({
// hears every change: a card renamed once redraws each of them, whichever is on screen. The
// change is remembered instead, and drawn once the tab is looked at again. Asked of the
// context rather than of the box, which is empty for a board that has not drawn yet.
+ // Compared by main context, not `noteContext.isActive()`: that names one pane across the
+ // whole app, so a board in a split the reader is not focused on is on screen but would
+ // never redraw, the `ResizeObserver` above having no size change to report.
// Only once it has drawn: a board opened straight into a background tab has to draw at
// least once, or there is no container to notice the tab being shown and it stays empty.
- if (byColumn && noteContext && !noteContext.isActive()) {
+ // Nothing is deferred where the active tab cannot be read, so an answer that has yet to
+ // arrive leaves the board drawn rather than blank.
+ const shownTab = appContext.tabManager?.getActiveMainContext();
+ if (byColumn && noteContext && shownTab && shownTab !== noteContext.getMainContext()) {
isStale.current = true;
return;
}