Skip to content

Build your personal knowledge base with Trilium Notes

feat(relation_map): paste notes onto the map (closes #1650)

Elian Doran1e1f10683500
diff --git a/apps/client/src/services/clipboard.ts b/apps/client/src/services/clipboard.ts
index d9773ded1e..5a0867f3bf 100644
--- a/apps/client/src/services/clipboard.ts
+++ b/apps/client/src/services/clipboard.ts
@@ -121,7 +121,18 @@ function isClipboardEmpty() {
return clipboardBranchIds.length === 0;
}
+/** The notes on the clipboard and whether they were cut or copied, or `null` when it is empty. */
+function getContents() {
+ if (isClipboardEmpty() || (clipboardMode !== "cut" && clipboardMode !== "copy")) {
+ return null;
+ }
+
+ const noteIds = froca.getBranches(clipboardBranchIds).map((branch) => branch.noteId);
+ return { noteIds, mode: clipboardMode };
+}
+
export default {
+ getContents,
pasteAfter,
pasteInto,
cut,
diff --git a/apps/client/src/services/note_paste.spec.ts b/apps/client/src/services/note_paste.spec.ts
new file mode 100644
index 0000000000..54fbdc8fdc
--- /dev/null
+++ b/apps/client/src/services/note_paste.spec.ts
@@ -0,0 +1,85 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../entities/fnote.js";
+import { buildNote } from "../test/easy-froca";
+import branchService from "./branches.js";
+import clipboard from "./clipboard.js";
+import froca from "./froca.js";
+import { pasteNotes } from "./note_paste.js";
+import toastService from "./toast.js";
+
+vi.mock("./clipboard_ext.js", () => ({ copyHtml: vi.fn(async () => true) }));
+
+branchService.moveToParentNote = vi.fn(async () => {}) as typeof branchService.moveToParentNote;
+toastService.showMessage = vi.fn() as typeof toastService.showMessage;
+
+describe("pasteNotes", () => {
+ let tree: FNote;
+ let map: FNote;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ clipboard.cut([]);
+ tree = buildNote({ title: "Tree", children: [ { id: "first", title: "First" }, { id: "second", title: "Second" } ] });
+ const parent = buildNote({ title: "Parent", children: [ { id: "map", title: "Map" } ] });
+ const mapNote = froca.getNoteFromCache("map");
+ if (!mapNote || !parent.childToBranch.map) throw new Error("the map note was not built");
+ map = mapNote;
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("pastes the notes the system clipboard links to, once each, and leaves them in place", async () => {
+ clipboard.cut([ tree.childToBranch.first ]);
+ const html = `<a class="reference-link" href="#root/${tree.noteId}/second">Second</a>, `
+ + `<a href="#root/first">First</a> <a href="#root/second">Again</a> `
+ + `<a href="https://example.com/#root/first">External</a>`;
+
+ expect(await pasteNotes(map, clipboardData({ "text/html": html }))).toEqual([ "second", "first" ]);
+ expect(branchService.moveToParentNote).not.toHaveBeenCalled();
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+
+ expect(await pasteNotes(map, clipboardData({ "text/plain": "#root/first, #root/second" })))
+ .toEqual([ "first", "second" ]);
+ });
+
+ it("falls back to Trilium's clipboard, moving cut notes under the parent and leaving copied ones", async () => {
+ const noLinks = clipboardData({ "text/html": "<p>Some text</p>", "text/plain": "Some text" });
+ expect(await pasteNotes(map, noLinks)).toEqual([]);
+
+ await clipboard.copy([ tree.childToBranch.first ]);
+ expect(await pasteNotes(map, noLinks)).toEqual([ "first" ]);
+ expect(branchService.moveToParentNote).not.toHaveBeenCalled();
+
+ clipboard.cut([ tree.childToBranch.first, tree.childToBranch.second ]);
+ expect(await pasteNotes(map, noLinks)).toEqual([ "first", "second" ]);
+ expect(branchService.moveToParentNote)
+ .toHaveBeenCalledWith([ tree.childToBranch.first, tree.childToBranch.second ], map.getParentBranchIds()[0]);
+ expect(clipboard.isClipboardEmpty()).toBe(true);
+ });
+
+ it("reads the system clipboard itself without a paste event, and falls back when it cannot", async () => {
+ vi.stubGlobal("navigator", { clipboard: { read: async () => [ clipboardItem({ "text/html": `<a href="#root/second">S</a>` }) ] } });
+ expect(await pasteNotes(map)).toEqual([ "second" ]);
+
+ await clipboard.copy([ tree.childToBranch.first ]);
+ vi.stubGlobal("navigator", { clipboard: { read: async () => { throw new Error("denied"); } } });
+ expect(await pasteNotes(map)).toEqual([ "first" ]);
+
+ vi.stubGlobal("navigator", {});
+ expect(await pasteNotes(map)).toEqual([ "first" ]);
+ });
+});
+
+function clipboardData(flavors: Record<string, string>) {
+ return { getData: (type: string) => flavors[type] ?? "" } as DataTransfer;
+}
+
+function clipboardItem(flavors: Record<string, string>) {
+ return {
+ types: Object.keys(flavors),
+ getType: async (type: string) => new Blob([ flavors[type] ?? "" ], { type })
+ } as unknown as ClipboardItem;
+}
diff --git a/apps/client/src/services/note_paste.ts b/apps/client/src/services/note_paste.ts
new file mode 100644
index 0000000000..619845cac8
--- /dev/null
+++ b/apps/client/src/services/note_paste.ts
@@ -0,0 +1,84 @@
+import type FNote from "../entities/fnote.js";
+import type { MenuCommandItem } from "../menus/context_menu.js";
+import clipboard from "./clipboard.js";
+import froca from "./froca.js";
+import { t } from "./i18n.js";
+import { parseNavigationStateFromUrl } from "./link.js";
+import { isMac } from "./utils.js";
+
+/**
+ * Pastes notes into a view that shows notes, such as a relation map, and returns the IDs of the
+ * pasted notes, which the view then shows. Empty when the clipboard holds no notes.
+ *
+ * The notes come from the links on the system clipboard (the tree's Copy puts reference links
+ * there, and so does copying a link to a note), read from `data`, a paste event's
+ * `clipboardData`, or from `navigator.clipboard` without one. When the system clipboard links to
+ * no note, they come from Trilium's own clipboard: cut notes move under `parentNote`, as the
+ * tree's Paste into does, while copied notes stay where they are.
+ */
+export async function pasteNotes(parentNote: FNote, data?: DataTransfer | null): Promise<string[]> {
+ const { html, text } = data
+ ? { html: data.getData("text/html"), text: data.getData("text/plain") }
+ : await readSystemClipboard();
+ const linkedNotes = await froca.getNotes(linkedNoteIds(html, text), true);
+ if (linkedNotes.length) {
+ return linkedNotes.map((note) => note.noteId);
+ }
+
+ const contents = clipboard.getContents();
+ if (!contents) return [];
+
+ const parentBranchId = parentNote.getParentBranchIds()[0];
+ if (contents.mode === "cut" && parentBranchId) {
+ await clipboard.pasteInto(parentBranchId);
+ }
+ return contents.noteIds;
+}
+
+/** The context menu row of a view that calls {@link pasteNotes} from its context menu. */
+export function pasteNotesMenuItem<T>(handler: () => void): MenuCommandItem<T> {
+ return {
+ title: t("clipboard.paste_notes"),
+ uiIcon: "bx bx-paste",
+ shortcut: `${isMac() ? "Meta" : "Ctrl"}+V`,
+ handler
+ };
+}
+
+/** The IDs of the notes linked from `html`, or else from the URLs in `text`, once each. */
+function linkedNoteIds(html: string, text: string) {
+ const hrefs = html
+ ? [ ...new DOMParser().parseFromString(html, "text/html").querySelectorAll("a[href]") ]
+ .map((link) => link.getAttribute("href") ?? "")
+ : text.split(/[\s,]+/);
+
+ const noteIds = new Set<string>();
+ for (const href of hrefs) {
+ const { noteId } = parseNavigationStateFromUrl(href);
+ if (noteId) noteIds.add(noteId);
+ }
+ return [ ...noteIds ];
+}
+
+/**
+ * The `text/html` and `text/plain` flavors on the system clipboard, empty when they are absent or
+ * the clipboard cannot be read: `navigator.clipboard.read()` requires a secure context, and the
+ * browser can refuse the permission.
+ */
+async function readSystemClipboard() {
+ let html = "";
+ let text = "";
+ try {
+ for (const item of await navigator.clipboard?.read?.() ?? []) {
+ if (!html && item.types.includes("text/html")) {
+ html = await (await item.getType("text/html")).text();
+ }
+ if (!text && item.types.includes("text/plain")) {
+ text = await (await item.getType("text/plain")).text();
+ }
+ }
+ } catch (error) {
+ console.warn("Failed to read the clipboard:", error);
+ }
+ return { html, text };
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 9374b19394..ac0c679ac7 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1677,6 +1677,7 @@
"fit_to_view": "Fit to view",
"hints": {
"title": "Relation map",
+ "paste_notes": "Paste the copied or cut notes",
"cancel_adding_note": "Cancel adding a note",
"close_note_pane": "Close the note panel"
}
@@ -2842,7 +2843,8 @@
"copied": "Note(s) have been copied into clipboard.",
"copied_without_links": "Note(s) have been copied into clipboard, but the note links could not be placed on the system clipboard.",
"copy_failed": "Cannot copy to clipboard due to permission issues.",
- "copy_success": "Copied to clipboard."
+ "copy_success": "Copied to clipboard.",
+ "paste_notes": "Paste note(s)"
},
"entrypoints": {
"note-revision-created": "Note revision has been created.",
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx
index cf29948b8a..a17fbde09b 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx
@@ -7,7 +7,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// A stand-in for the zoom library, which needs real layout: it applies a transform at once and
// reports it, as the library does once an animation ends.
-const { wrapperProps } = vi.hoisted(() => ({ wrapperProps: { current: null as Record<string, unknown> | null } }));
+const { wrapperProps, pasteNotes } = vi.hoisted(() => ({
+ wrapperProps: { current: null as Record<string, unknown> | null },
+ pasteNotes: vi.fn<(note: unknown, data?: DataTransfer | null) => Promise<string[]>>()
+}));
+vi.mock("../../../services/note_paste", () => ({ pasteNotes }));
vi.mock("react-zoom-pan-pinch", () => ({
TransformWrapper: forwardRef((props: { children?: ComponentChildren; onTransform?(ref: unknown, state: object): void }, ref) => {
wrapperProps.current = props;
@@ -29,10 +33,12 @@ vi.mock("react-zoom-pan-pinch", () => ({
}));
import Component from "../../../components/component";
+import type FNote from "../../../entities/fnote";
+import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
import type RelationMapApi from "./api";
import type { MapTransform } from "./api";
-import { MapViewport, useCanvasClicks, useMapZoom, useRevealSelectedBox } from "./RelationMap";
+import { MapViewport, useCanvasClicks, useMapPaste, useMapZoom, useRevealSelectedBox } from "./RelationMap";
import { noteIdToId } from "./utils";
describe("relation map canvas clicks", () => {
@@ -333,3 +339,117 @@ describe("relation map zoom", () => {
expect(state()?.scale).toBeCloseTo(1);
});
});
+
+describe("relation map paste", () => {
+ let container: HTMLElement | undefined;
+ let mapNote: FNote;
+ const addMultipleNotes = vi.fn();
+ let pasteAt: ReturnType<typeof useMapPaste>["pasteAt"] | undefined;
+
+ beforeEach(() => {
+ addMultipleNotes.mockClear();
+ pasteNotes.mockReset().mockResolvedValue([ "first", "second" ]);
+ mapNote = buildNote({ id: "map", title: "Map" });
+ buildNote({ id: "first", title: "First" });
+ buildNote({ id: "second", title: "Second" });
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ /** The map at 2x, with an editor over it as the note pane has. */
+ function Harness({ isReadOnly }: { isReadOnly: boolean }) {
+ const [ viewport, setViewport ] = useState<HTMLDivElement | null>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const mapApiRef = useRef({ addMultipleNotes } as unknown as RelationMapApi);
+ const paste = useMapPaste({ note: mapNote, isReadOnly, viewport, containerRef, mapApiRef, getScale: () => 2 });
+ pasteAt = paste.pasteAt;
+ return (
+ <div className="wrapper" onMouseMove={paste.followPointer} onMouseLeave={paste.forgetPointer}>
+ <div ref={setViewport} className="relation-map-viewport" tabIndex={0}>
+ <div ref={containerRef} className="relation-map-container" />
+ </div>
+ <div className="editor" contentEditable />
+ </div>
+ );
+ }
+
+ function mount(isReadOnly = false) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ act(() => render(<Harness isReadOnly={isReadOnly} />, container as HTMLElement));
+ const find = (selector: string) => {
+ const element = container?.querySelector<HTMLElement>(selector);
+ if (!element) throw new Error(`${selector} was not rendered`);
+ return element;
+ };
+ const viewport = find(".relation-map-viewport");
+ viewport.getBoundingClientRect = () => DOMRect.fromRect({ x: 0, y: 0, width: 400, height: 200 });
+ return { wrapper: find(".wrapper"), viewport, editor: find(".editor") };
+ }
+
+ /**
+ * Focuses `focused` and pastes. As in Chromium, the event goes to the editable holding the
+ * selection, and otherwise to the body, whatever has the focus.
+ */
+ async function paste(focused: HTMLElement, clipboardData: object | null = null) {
+ focused.focus();
+ const target = focused.isContentEditable ? focused : document.body;
+ const event = new Event("paste", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "clipboardData", { value: clipboardData });
+ await act(async () => {
+ target.dispatchEvent(event);
+ await new Promise((resolve) => setTimeout(resolve));
+ });
+ return event;
+ }
+
+ const placed = (x: number, y: number) => [ [
+ { noteId: "first", title: "First", x, y },
+ { noteId: "second", title: "Second", x: x + 200, y }
+ ] ];
+
+ it("pastes onto the map under the pointer, or in the middle once the pointer leaves", async () => {
+ const { wrapper, viewport } = mount();
+ const data = { getData: () => "" };
+
+ act(() => { viewport.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 300, clientY: 100 })); });
+ const event = await paste(viewport, data);
+ expect(event.defaultPrevented).toBe(true);
+ expect(pasteNotes).toHaveBeenCalledWith(mapNote, data);
+ expect(addMultipleNotes.mock.calls.at(-1)).toEqual(placed(70, 35));
+
+ act(() => { wrapper.dispatchEvent(new MouseEvent("mouseleave")); });
+ await paste(viewport);
+ expect(addMultipleNotes.mock.calls.at(-1)).toEqual(placed(20, 35));
+
+ await act(async () => {
+ pasteAt?.({ clientX: 200, clientY: 200 });
+ await new Promise((resolve) => setTimeout(resolve));
+ });
+ expect(addMultipleNotes.mock.calls.at(-1)).toEqual(placed(20, 85));
+ });
+
+ it("leaves a paste into the note pane to it, and pastes nothing onto a read-only map or from an empty clipboard", async () => {
+ const { editor } = mount();
+ const event = await paste(editor);
+ expect(event.defaultPrevented).toBe(false);
+ expect(pasteNotes).not.toHaveBeenCalled();
+
+ pasteNotes.mockResolvedValue([]);
+ await paste(container?.querySelector<HTMLElement>(".relation-map-viewport") ?? editor);
+ expect(pasteNotes).toHaveBeenCalledTimes(1);
+ expect(addMultipleNotes).not.toHaveBeenCalled();
+
+ act(() => render(null, container as HTMLElement));
+ container?.remove();
+ const { viewport } = mount(true);
+ await paste(viewport);
+ expect(pasteNotes).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
index 0549a242d9..bd9911f0f5 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx
@@ -12,6 +12,7 @@ import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
import { goToLinkExt } from "../../../services/link";
import note_create from "../../../services/note_create";
+import { pasteNotes } from "../../../services/note_paste";
import server from "../../../services/server";
import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";
import toast from "../../../services/toast";
@@ -23,7 +24,7 @@ import ShortcutHintButton from "../../shortcut_hints/shortcut_hint_button";
import { TypeWidgetProps } from "../type_widget";
import RelationMapApi, { ClientRelation, MapData, MapDataNoteEntry, MapTransform } from "./api";
import Connections from "./Connections";
-import { showRelationContextMenu } from "./context_menu";
+import { showCanvasContextMenu, showRelationContextMenu } from "./context_menu";
import { useBoxDragging, useRelationDrawing } from "./drags";
import type { Box } from "./geometry";
import MapToolbar, { EditToolbar } from "./MapToolbar";
@@ -119,6 +120,7 @@ export default function RelationMap({ note, noteContext, ntxId }: TypeWidgetProp
onOpenNote: openNoteFromBox
});
const dragProps = useNoteDragging({ containerRef, mapApiRef, getScale });
+ const paste = useMapPaste({ note, isReadOnly, viewport, containerRef, mapApiRef, getScale });
const relationNamePrompt = useRelationNamePrompt();
const { dragged, startDrag } = useBoxDragging({ containerRef, mapApiRef, getScale });
@@ -139,12 +141,28 @@ export default function RelationMap({ note, noteContext, ntxId }: TypeWidgetProp
showRelationContextMenu(e, relation, mapApiRef, (defaultValue) => relationNamePrompt.ask(anchor, defaultValue));
}, [ relationNamePrompt.ask ]);
+ const onCanvasContextMenu = useCallback((e: MouseEvent) => {
+ const isOnItem = e.target instanceof Element && e.target.closest(PAN_EXCLUDED.map((name) => `.${name}`).join(","));
+ if (isReadOnly || e.defaultPrevented || isOnItem || !isOnCanvas(e)) return;
+ showCanvasContextMenu(e, {
+ onPaste: () => paste.pasteAt(e),
+ onAddNote: () => placement.placeAt(e)
+ });
+ }, [ isReadOnly, paste.pasteAt, placement.placeAt ]);
+
return (
<div
ref={wrapperRef}
className={clsx("relation-map-wrapper", placement.placing && "placing-note")}
- onMouseMove={placement.followPointer}
- onMouseLeave={placement.hideGhost}
+ onMouseMove={(e) => {
+ placement.followPointer(e);
+ paste.followPointer(e);
+ }}
+ onMouseLeave={() => {
+ placement.hideGhost();
+ paste.forgetPointer();
+ }}
+ onContextMenu={onCanvasContextMenu}
{...clickProps}
{...dragProps}
>
@@ -312,6 +330,7 @@ const RELATION_MAP_HINTS: ShortcutHintDefinition = [
{
titleKey: "relation_map.hints.title",
hints: [
+ { keys: [ "Ctrl+V" ], labelKey: "relation_map.hints.paste_notes" },
{ keys: [ "Escape" ], labelKey: "relation_map.hints.cancel_adding_note" },
{ keys: [ "Escape" ], labelKey: "relation_map.hints.close_note_pane" }
]
@@ -498,6 +517,61 @@ function useNotePlacement({ ntxId, note, containerRef, getScale, mapApiRef, onAr
return { placing, toggle, ghostRef, followPointer, hideGhost, placeAt };
}
+/**
+ * Pastes notes onto the map (see `pasteNotes`): with Ctrl+V while the map has the focus, under the
+ * pointer or in the middle of the view when the pointer is off the canvas, and from the context
+ * menu of empty canvas through `pasteAt`. Cut notes also move under the map's note.
+ *
+ * The paste event goes to the element holding the selection, or to the body, not to the focused
+ * element, so the hook listens on the document and checks the focus.
+ */
+export function useMapPaste({ note, isReadOnly, viewport, containerRef, mapApiRef, getScale }: {
+ note: FNote;
+ isReadOnly: boolean;
+ viewport: HTMLDivElement | null;
+ containerRef: RefObject<HTMLDivElement | null>;
+ mapApiRef: RefObject<RelationMapApi | null>;
+ getScale(): number;
+}) {
+ const pointerRef = useRef<{ clientX: number; clientY: number }>(null);
+
+ const paste = useCallback(async (at: { clientX: number; clientY: number } | null, data?: DataTransfer | null) => {
+ const noteIds = await pasteNotes(note, data);
+ const container = containerRef.current;
+ if (!noteIds.length || !container) return;
+
+ const rect = viewport?.getBoundingClientRect();
+ const point = at ?? (rect ? { clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 } : null);
+ if (!point) return;
+
+ const notes = froca.getNotesFromCache(noteIds, true);
+ mapApiRef.current?.addMultipleNotes(layOutBoxes(notes, boxPositionAt(point, container, getScale())));
+ }, [ note, viewport, containerRef, mapApiRef, getScale ]);
+
+ useEffect(() => {
+ if (!viewport || isReadOnly) return;
+
+ const onPaste = (e: ClipboardEvent) => {
+ if (document.activeElement !== viewport) return;
+ e.preventDefault();
+ void paste(pointerRef.current, e.clipboardData);
+ };
+ document.addEventListener("paste", onPaste);
+ return () => document.removeEventListener("paste", onPaste);
+ }, [ viewport, isReadOnly, paste ]);
+
+ const pasteAt = useCallback((at: { clientX: number; clientY: number }) => void paste(at), [ paste ]);
+
+ const followPointer = useCallback((e: MouseEvent) => {
+ pointerRef.current = isOnCanvas(e) ? { clientX: e.clientX, clientY: e.clientY } : null;
+ }, []);
+ const forgetPointer = useCallback(() => {
+ pointerRef.current = null;
+ }, []);
+
+ return { pasteAt, followPointer, forgetPointer };
+}
+
/**
* Handles clicks on the map. In placement mode, a click places a new note. Otherwise a click on a
* box selects it, and a click on empty canvas closes the pane. A Ctrl, Shift or middle click on a box
@@ -646,8 +720,30 @@ function openNoteFromBox(noteId: string, e: MouseEvent) {
goToLinkExt(e, `#${notePath || noteId}`);
}
+/**
+ * Map entries for `notes`, laid out in rows from `start`: each box 200 pixels right of the last, and
+ * a new row 100 pixels down once a row passes 1000.
+ */
+function layOutBoxes(notes: { noteId: string; title: string }[], start: { x: number; y: number }) {
+ let { x, y } = start;
+ const entries: (MapDataNoteEntry & { title: string })[] = [];
+
+ for (const { noteId, title } of notes) {
+ entries.push({ noteId, title, x, y });
+
+ if (x > 1000) {
+ y += 100;
+ x = 0;
+ } else {
+ x += 200;
+ }
+ }
+
+ return entries;
+}
+
/** The map position, in unzoomed map pixels, of a box placed under the pointer. */
-function boxPositionAt(e: MouseEvent, container: HTMLDivElement, scale: number) {
+function boxPositionAt(e: Pick<MouseEvent, "clientX" | "clientY">, container: HTMLDivElement, scale: number) {
const { x, y } = getMousePosition(e, container, scale);
return { x: x - PLACEMENT_OFFSET.x, y: y - PLACEMENT_OFFSET.y };
}
@@ -657,7 +753,7 @@ function boxPositionAt(e: MouseEvent, container: HTMLDivElement, scale: number)
* it. The boxes stand in a container without a size of its own, so empty canvas is outside it. The
* viewport must be the wrapper's own, not that of a relation map shown in the note pane.
*/
-function isOnCanvas(e: MouseEvent) {
+function isOnCanvas(e: Event) {
if (e.target === e.currentTarget) return true;
const viewport = e.target instanceof Element ? e.target.closest(".relation-map-viewport") : null;
return !!viewport && viewport.parentElement === e.currentTarget;
@@ -675,26 +771,9 @@ function useNoteDragging({ containerRef, mapApiRef, getScale }: {
const dragData = ev.dataTransfer?.getData("text");
if (!dragData) return;
- const notes = JSON.parse(dragData);
-
- let { x, y } = getMousePosition(ev, container, getScale());
- const entries: (MapDataNoteEntry & { title: string })[] = [];
-
- for (const note of notes) {
- entries.push({
- ...note,
- x, y
- });
-
- if (x > 1000) {
- y += 100;
- x = 0;
- } else {
- x += 200;
- }
- }
+ const notes: { noteId: string; title: string }[] = JSON.parse(dragData);
- mapApiRef.current?.addMultipleNotes(entries);
+ mapApiRef.current?.addMultipleNotes(layOutBoxes(notes, getMousePosition(ev, container, getScale())));
},
onDragOver(ev) {
ev.preventDefault();
diff --git a/apps/client/src/widgets/type_widgets/relation_map/context_menu.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/context_menu.spec.tsx
index e6c0620a15..e8b9dba6c6 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/context_menu.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/context_menu.spec.tsx
@@ -7,7 +7,7 @@ import link_context_menu from "../../../menus/link_context_menu";
import froca from "../../../services/froca";
import { buildNote } from "../../../test/easy-froca";
import type RelationMapApi from "./api";
-import { buildNoteContextMenuHandler } from "./context_menu";
+import { buildNoteContextMenuHandler, showCanvasContextMenu } from "./context_menu";
describe("relation map note context menu", () => {
let container: HTMLElement | undefined;
@@ -57,3 +57,27 @@ describe("relation map note context menu", () => {
expect(custom).toHaveLength(0);
});
});
+
+describe("relation map canvas context menu", () => {
+ it("pastes notes or adds one where it opened", () => {
+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
+ const onPaste = vi.fn();
+ const onAddNote = vi.fn();
+ const event = new MouseEvent("contextmenu", { cancelable: true });
+
+ showCanvasContextMenu(event, { onPaste, onAddNote });
+ expect(event.defaultPrevented).toBe(true);
+
+ const items = (show.mock.calls.at(-1)?.[0].items ?? []) as MenuItem<string>[];
+ const choose = (index: number) => {
+ const item = items[index];
+ if (item && "handler" in item) item.handler?.(item, event);
+ };
+ expect(items.map((item) => ("kind" in item ? item.kind : item.uiIcon))).toEqual([ "bx bx-paste", "separator", "bx bx-note" ]);
+
+ choose(0);
+ expect([ onPaste.mock.calls.length, onAddNote.mock.calls.length ]).toEqual([ 1, 0 ]);
+ choose(2);
+ expect(onAddNote).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts b/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
index 2d71562f96..164727b7e5 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
@@ -6,9 +6,10 @@ import contextMenu from "../../../menus/context_menu";
import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";
import link_context_menu from "../../../menus/link_context_menu";
import dialog from "../../../services/dialog";
-import toast from "../../../services/toast";
import { t } from "../../../services/i18n";
+import { pasteNotesMenuItem } from "../../../services/note_paste";
import server from "../../../services/server";
+import toast from "../../../services/toast";
import RelationMapApi, { type ClientRelation } from "./api";
export function buildNoteContextMenuHandler(note: FNote | null | undefined, mapApiRef: RefObject<RelationMapApi | null>, isReadOnly: boolean) {
@@ -75,6 +76,25 @@ export async function confirmRemoveFromMap(note: FNote, mapApiRef: RefObject<Rel
await mapApiRef.current?.removeItem(note.noteId, result.isDeleteNoteChecked);
}
+/** Shows the context menu of empty canvas, which pastes notes or adds a new one where it opened. */
+export function showCanvasContextMenu(event: MouseEvent, { onPaste, onAddNote }: {
+ onPaste(): void;
+ onAddNote(): void;
+}) {
+ event.preventDefault();
+
+ contextMenu.show({
+ x: event.pageX,
+ y: event.pageY,
+ items: [
+ pasteNotesMenuItem(onPaste),
+ { kind: "separator" },
+ { title: t("relation_map_buttons.create_child_note_text"), uiIcon: "bx bx-note", handler: onAddNote }
+ ],
+ selectMenuItemHandler() {}
+ });
+}
+
/**
* Shows the context menu of a relation, which renames or removes it. `askRelationName` asks for the
* new name next to the relation.
diff --git a/apps/client/src/widgets/type_widgets/relation_map/utils.ts b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
index d255b04a05..29a949fc0e 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/utils.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
@@ -9,7 +9,7 @@ export function idToNoteId(id: string) {
/** How far, in pixels, the pointer can move between press and release for the click to count. */
export const CLICK_TOLERANCE = 4;
-export function getMousePosition(evt: MouseEvent, container: HTMLDivElement, zoom: number) {
+export function getMousePosition(evt: Pick<MouseEvent, "clientX" | "clientY">, container: HTMLDivElement, zoom: number) {
const rect = container.getBoundingClientRect();
return {
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html
index 1a9c23243f..85f269e88c 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html
@@ -24,6 +24,22 @@
position.</li>
</ul>
</li>
+ <li>Notes can also be pasted onto the map. Copy or cut them in the <a class="reference-link"
+ href="#root/_help_oPVyFC7WL2Lp">Note Tree</a>, then click the map and press <kbd>Ctrl</kbd>+<kbd>V</kbd>,
+ or right click an empty part of the map and select <em>Paste note(s)</em>.
+ <ul>
+ <li>With <kbd>Ctrl</kbd>+<kbd>V</kbd>, the notes are placed under the mouse,
+ or in the middle of the map if the mouse is not over it. From the right
+ click menu, they are placed where the menu was opened.</li>
+ <li>Copied notes stay where they are in the tree. Cut notes are moved under
+ the map, as if they had been pasted into it in the tree.</li>
+ <li>Links to notes, such as an <a class="reference-link" href="#root/_help_hrZ1D00cLbal">Internal (reference) links</a> copied
+ from a text note, can be pasted the same way. If the clipboard holds no
+ link to a note, the notes last copied or cut in the tree are pasted.</li>
+ <li>The right click menu of an empty part of the map also has <em>Add note</em>,
+ which creates a new note where the menu was opened.</li>
+ </ul>
+ </li>
<li>To create a relationship, hold the mouse on the dot on the right of a
note and then:
<ul>
diff --git a/docs/User Guide/User Guide/Note Types/Relation Map.md b/docs/User Guide/User Guide/Note Types/Relation Map.md
index 137f0eeab2..3b4075b438 100644
--- a/docs/User Guide/User Guide/Note Types/Relation Map.md
+++ b/docs/User Guide/User Guide/Note Types/Relation Map.md
@@ -9,6 +9,11 @@ Relation map is a type of note which visualizes notes and their [relations](..
* An existing note can also be dragged from the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree.md">Note Tree</a>. It will be placed at the position it's dragged on.
* Multiple notes can also be dragged via <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree/Multiple%20selection.md">Multiple selection</a>. The notes will be positioned near the dragged position without overlapping.
* The dragged note can be a sub-child of the map, or it can be at any arbitrary position.
+* Notes can also be pasted onto the map. Copy or cut them in the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree.md">Note Tree</a>, then click the map and press <kbd>Ctrl</kbd>+<kbd>V</kbd>, or right click an empty part of the map and select _Paste note(s)_.
+ * With <kbd>Ctrl</kbd>+<kbd>V</kbd>, the notes are placed under the mouse, or in the middle of the map if the mouse is not over it. From the right click menu, they are placed where the menu was opened.
+ * Copied notes stay where they are in the tree. Cut notes are moved under the map, as if they had been pasted into it in the tree.
+ * Links to notes, such as an <a class="reference-link" href="Text/Links/Internal%20(reference)%20links.md">Internal (reference) links</a> copied from a text note, can be pasted the same way. If the clipboard holds no link to a note, the notes last copied or cut in the tree are pasted.
+ * The right click menu of an empty part of the map also has _Add note_, which creates a new note where the menu was opened.
* To create a relationship, hold the mouse on the dot on the right of a note and then:
* Drag it over another note to create a relationship pointing from the first note to the second one.
* Drag over the same note to create a self-referencing relationship (represented as a loop).