Skip to content

Build your personal knowledge base with Trilium Notes

feat(clipboard): copy note reference links outside Electron too

Elian Doranaa649a823dda
diff --git a/apps/client/src/services/clipboard.spec.ts b/apps/client/src/services/clipboard.spec.ts
index 1363385cc6..ae758f7a8e 100644
--- a/apps/client/src/services/clipboard.spec.ts
+++ b/apps/client/src/services/clipboard.spec.ts
@@ -67,40 +67,39 @@ describe("isClipboardEmpty", () => {
});
describe("copy", () => {
- afterEach(() => {
- delete (window as any).electronApi;
- delete (globalThis as any).ClipboardItem;
- });
+ const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
+ let $link: JQuery<HTMLElement>;
- it("sets copy mode and toasts on a non-Electron platform", async () => {
- const { childBranchId } = buildParentWithChild();
- expect(utils.isElectron()).toBe(false);
+ /** Replace `navigator.clipboard`, which happy-dom exposes as a getter-only property. */
+ function setClipboard(value: unknown) {
+ Object.defineProperty(navigator, "clipboard", { configurable: true, get: () => value });
+ }
- await clipboard.copy([childBranchId]);
+ beforeEach(() => {
+ $link = $("<a>").attr("href", "ref").text("Child link");
+ linkService.createLink = vi.fn(async () => $link) as typeof linkService.createLink;
+ });
- expect(clipboard.isClipboardEmpty()).toBe(false);
- expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete (globalThis as any).ClipboardItem;
+ if (originalClipboard) {
+ Object.defineProperty(navigator, "clipboard", originalClipboard);
+ }
});
- it("writes reference links to the system clipboard on Electron", async () => {
+ it("sets copy mode and writes reference links to the system clipboard", async () => {
const { parent, childBranchId, childNoteId } = buildParentWithChild();
-
- (window as any).electronApi = {};
const writeSpy = vi.fn(async (..._args: any[]) => {});
- // happy-dom exposes `navigator.clipboard` as a getter-only property, so define our own.
- Object.defineProperty(navigator, "clipboard", {
- configurable: true,
- get: () => ({ write: writeSpy })
- });
+ setClipboard({ write: writeSpy });
(globalThis as any).ClipboardItem = class {
constructor(public readonly data: Record<string, unknown>) {}
};
- const link = $("<a>").attr("href", "ref").text("Child link");
- linkService.createLink = vi.fn(async () => link) as typeof linkService.createLink;
-
await clipboard.copy([childBranchId]);
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+
// The link key is `${branch.parentNoteId}/${branch.noteId}` with the reference-link option.
expect(linkService.createLink).toHaveBeenCalledTimes(1);
expect(linkService.createLink).toHaveBeenCalledWith(`${parent.noteId}/${childNoteId}`, { referenceLink: true });
@@ -112,15 +111,48 @@ describe("copy", () => {
// The html slot carries the link's outerHTML; the plain slot carries its text.
const htmlBlob = items[0].data["text/html"] as Blob;
const plainBlob = items[0].data["text/plain"] as Blob;
- expect(htmlBlob).toBeInstanceOf(Blob);
- expect(plainBlob).toBeInstanceOf(Blob);
expect(htmlBlob.type).toBe("text/html");
expect(plainBlob.type).toBe("text/plain");
- expect(await htmlBlob.text()).toBe(link[0].outerHTML);
+ expect(await htmlBlob.text()).toBe($link[0].outerHTML);
expect(await plainBlob.text()).toBe("Child link");
expect(toastService.showMessage).toHaveBeenCalledTimes(1);
});
+
+ it("falls back to the copy event when the asynchronous Clipboard API is unavailable", async () => {
+ const { childBranchId } = buildParentWithChild();
+ // No `navigator.clipboard` at all, as when Trilium is served over plain HTTP on a LAN (#10723).
+ setClipboard(undefined);
+ const copyHtmlToClipboard = vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(true);
+
+ await clipboard.copy([childBranchId]);
+
+ expect(copyHtmlToClipboard).toHaveBeenCalledWith($link[0].outerHTML, "Child link");
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+ expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it("still copies onto Trilium's own clipboard when the system clipboard refuses the links", async () => {
+ const { childBranchId } = buildParentWithChild();
+ setClipboard(undefined);
+ vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(false);
+
+ await clipboard.copy([childBranchId]);
+
+ // The notes stay pasteable within the tree, so the toast reports the partial success.
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+ expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(toastService.showMessage).mock.calls[0].slice(1)).toEqual([5000, "bx bx-error"]);
+ });
+
+ it("skips the system clipboard when there is nothing to copy", async () => {
+ const copyHtmlToClipboard = vi.spyOn(utils, "copyHtmlToClipboard");
+
+ await clipboard.copy([]);
+
+ expect(copyHtmlToClipboard).not.toHaveBeenCalled();
+ expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+ });
});
describe("pasteAfter", () => {
@@ -152,7 +184,7 @@ describe("pasteAfter", () => {
} as any;
// "missing-branch" is dropped by isClipboardEmpty()'s filter before the clone loop runs.
- clipboard.copy([childBranchId, "missing-branch", orphanBranchId]);
+ await clipboard.copy([childBranchId, "missing-branch", orphanBranchId]);
vi.clearAllMocks();
await clipboard.pasteAfter("target-branch");
@@ -193,7 +225,7 @@ describe("pasteInto", () => {
getNote: async () => null
} as any;
- clipboard.copy([childBranchId, "missing-branch", orphanBranchId]);
+ await clipboard.copy([childBranchId, "missing-branch", orphanBranchId]);
vi.clearAllMocks();
await clipboard.pasteInto("parent-branch");
diff --git a/apps/client/src/services/clipboard.ts b/apps/client/src/services/clipboard.ts
index 0f3569b3d4..d9773ded1e 100644
--- a/apps/client/src/services/clipboard.ts
+++ b/apps/client/src/services/clipboard.ts
@@ -1,8 +1,8 @@
import branchService from "./branches.js";
import toastService from "./toast.js";
import froca from "./froca.js";
+import { copyHtml } from "./clipboard_ext.js";
import linkService from "./link.js";
-import utils from "./utils.js";
import { t } from "./i18n.js";
import { throwError } from "./ws.js";
@@ -83,26 +83,26 @@ async function copy(branchIds: string[]) {
clipboardBranchIds = branchIds;
clipboardMode = "copy";
- if (utils.isElectron()) {
- // https://github.com/zadam/trilium/issues/2401
- const htmlParts: string[] = [];
- const textParts: string[] = [];
+ // Reference links go onto the system clipboard as well, so the notes can be pasted into the
+ // content of another note. https://github.com/zadam/trilium/issues/2401
+ const htmlParts: string[] = [];
+ const textParts: string[] = [];
- for (const branch of froca.getBranches(clipboardBranchIds)) {
- const $link = await linkService.createLink(`${branch.parentNoteId}/${branch.noteId}`, { referenceLink: true });
- htmlParts.push($link[0].outerHTML);
- textParts.push($link.text());
- }
-
- await navigator.clipboard.write([
- new ClipboardItem({
- "text/html": new Blob([htmlParts.join(", ")], { type: "text/html" }),
- "text/plain": new Blob([textParts.join(", ")], { type: "text/plain" })
- })
- ]);
+ for (const branch of froca.getBranches(clipboardBranchIds)) {
+ const $link = await linkService.createLink(`${branch.parentNoteId}/${branch.noteId}`, { referenceLink: true });
+ htmlParts.push($link[0].outerHTML);
+ textParts.push($link.text());
}
- toastService.showMessage(t("clipboard.copied"));
+ // The notes sit on Trilium's own clipboard either way, so a refused system clipboard only costs
+ // the ability to paste them into a note's content.
+ const linksCopied = htmlParts.length === 0 || (await copyHtml(htmlParts.join(", "), textParts.join(", ")));
+
+ if (linksCopied) {
+ toastService.showMessage(t("clipboard.copied"));
+ } else {
+ toastService.showMessage(t("clipboard.copied_without_links"), 5000, "bx bx-error");
+ }
}
function cut(branchIds: string[]) {
diff --git a/apps/client/src/services/clipboard_ext.spec.ts b/apps/client/src/services/clipboard_ext.spec.ts
index e5a55b38e4..e625a1b08b 100644
--- a/apps/client/src/services/clipboard_ext.spec.ts
+++ b/apps/client/src/services/clipboard_ext.spec.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import toast from "./toast.js";
import utils from "./utils.js";
-import { copyHtmlWithToast, copyText, copyTextWithToast } from "./clipboard_ext.js";
+import { copyHtml, copyHtmlWithToast, copyText, copyTextWithToast } from "./clipboard_ext.js";
const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
@@ -105,8 +105,68 @@ describe("copyTextWithToast", () => {
});
});
+describe("copyHtml", () => {
+ afterEach(() => {
+ delete (globalThis as any).ClipboardItem;
+ });
+
+ /** Install the `ClipboardItem` constructor the asynchronous Clipboard API needs. */
+ function stubClipboardItem() {
+ (globalThis as any).ClipboardItem = class {
+ constructor(public readonly data: Record<string, unknown>) {}
+ };
+ }
+
+ it("writes both flavours through navigator.clipboard when available", async () => {
+ const write = vi.fn(async (..._args: any[]) => {});
+ setClipboard({ write });
+ stubClipboardItem();
+ const copyHtmlToClipboard = vi.spyOn(utils, "copyHtmlToClipboard");
+
+ expect(await copyHtml("<b>x</b>", "x")).toBe(true);
+
+ const items = write.mock.calls[0][0] as any[];
+ expect(await (items[0].data["text/html"] as Blob).text()).toBe("<b>x</b>");
+ expect(await (items[0].data["text/plain"] as Blob).text()).toBe("x");
+ expect(copyHtmlToClipboard).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the copy event outside a secure context, where the API is undefined (#10723)", async () => {
+ setClipboard(undefined);
+ const copyHtmlToClipboard = vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(true);
+
+ // The plain text defaults to the HTML.
+ expect(await copyHtml("<b>x</b>")).toBe(true);
+ expect(copyHtmlToClipboard).toHaveBeenCalledWith("<b>x</b>", "<b>x</b>");
+ });
+
+ it("returns false and warns when the copy event itself throws", async () => {
+ setClipboard(undefined);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const error = new Error("execCommand failed");
+ vi.spyOn(utils, "copyHtmlToClipboard").mockImplementation(() => {
+ throw error;
+ });
+
+ expect(await copyHtml("<b>x</b>")).toBe(false);
+ expect(warn).toHaveBeenCalledWith(error);
+ });
+
+ it("falls back to the copy event when the write is denied, and reports a failure of both", async () => {
+ const denied = new Error("NotAllowedError");
+ setClipboard({ write: vi.fn(async () => { throw denied; }) });
+ stubClipboardItem();
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const copyHtmlToClipboard = vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(false);
+
+ expect(await copyHtml("<b>x</b>", "x")).toBe(false);
+ expect(warn).toHaveBeenCalledWith(denied);
+ expect(copyHtmlToClipboard).toHaveBeenCalledWith("<b>x</b>", "x");
+ });
+});
+
describe("copyHtmlWithToast", () => {
- it("copies through the copy event, defaults the plain text to the HTML, and reports success", () => {
+ it("copies through the copy event, defaults the plain text to the HTML, and reports success", async () => {
// No `navigator.clipboard` at all: the API is undefined outside secure contexts, which is
// how Trilium is usually served over a LAN (#10723).
setClipboard(undefined);
@@ -114,22 +174,23 @@ describe("copyHtmlWithToast", () => {
const showMessage = vi.spyOn(toast, "showMessage").mockImplementation(() => {});
const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
- copyHtmlWithToast("<b>x</b>");
+ await copyHtmlWithToast("<b>x</b>");
expect(copyHtmlToClipboard).toHaveBeenCalledWith("<b>x</b>", "<b>x</b>");
- copyHtmlWithToast("<a href=\"#root/abc\">Note</a>", "#root/abc");
+ await copyHtmlWithToast("<a href=\"#root/abc\">Note</a>", "#root/abc");
expect(copyHtmlToClipboard).toHaveBeenLastCalledWith("<a href=\"#root/abc\">Note</a>", "#root/abc");
expect(showMessage).toHaveBeenCalledTimes(2);
expect(showError).not.toHaveBeenCalled();
});
- it("shows an error message when the copy fails", () => {
+ it("shows an error message when the copy fails", async () => {
+ setClipboard(undefined);
vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(false);
const showMessage = vi.spyOn(toast, "showMessage").mockImplementation(() => {});
const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
- copyHtmlWithToast("<b>x</b>");
+ await copyHtmlWithToast("<b>x</b>");
expect(showError).toHaveBeenCalledTimes(1);
expect(showMessage).not.toHaveBeenCalled();
diff --git a/apps/client/src/services/clipboard_ext.ts b/apps/client/src/services/clipboard_ext.ts
index a7c7da135e..36e38a866b 100644
--- a/apps/client/src/services/clipboard_ext.ts
+++ b/apps/client/src/services/clipboard_ext.ts
@@ -39,14 +39,42 @@ export function copyTextWithToast(text: string) {
/**
* Copies rich HTML — so it pastes with formatting into a note or another rich editor — with
- * `plainText` as the plain-text alternative, and reports the outcome as a toast.
+ * `plainText` as the plain-text alternative. Returns whether the clipboard was written.
*
- * Goes through the copy event rather than `navigator.clipboard.write()`, which browsers expose
- * only in secure contexts; Trilium is routinely served over plain HTTP on a LAN, where the API is
- * simply undefined.
+ * `navigator.clipboard.write()` is the richer path but browsers expose it only in secure contexts,
+ * and Trilium is routinely served over plain HTTP on a LAN, where the API is simply undefined
+ * (#10723). The copy event is the fallback there, and also when the write is denied.
*/
-export function copyHtmlWithToast(html: string, plainText: string = html) {
- if (utils.copyHtmlToClipboard(html, plainText)) {
+export async function copyHtml(html: string, plainText: string = html) {
+ if (navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
+ try {
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ "text/html": new Blob([html], { type: "text/html" }),
+ "text/plain": new Blob([plainText], { type: "text/plain" })
+ })
+ ]);
+
+ return true;
+ } catch (e) {
+ // A denied permission or an unfocused document still leaves the copy event to try.
+ console.warn(e);
+ }
+ }
+
+ try {
+ return utils.copyHtmlToClipboard(html, plainText);
+ } catch (e) {
+ console.warn(e);
+ return false;
+ }
+}
+
+/**
+ * Copies rich HTML as {@link copyHtml} does and reports the outcome as a toast.
+ */
+export async function copyHtmlWithToast(html: string, plainText: string = html) {
+ if (await copyHtml(html, plainText)) {
toast.showMessage(t("clipboard.copy_success"));
} else {
toast.showError(t("clipboard.copy_failed"));
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index efd041ca4b..5ce704b220 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2750,6 +2750,7 @@
"clipboard": {
"cut": "Note(s) have been cut into clipboard.",
"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."
},