Skip to content

Build your personal knowledge base with Trilium Notes

fix(text): copy anchor links without the Clipboard API (closes #10723)

Elian Doran9b900b396960
diff --git a/apps/client/src/menus/tree_context_menu.ts b/apps/client/src/menus/tree_context_menu.ts
index b64c13899e..96b1747b10 100644
--- a/apps/client/src/menus/tree_context_menu.ts
+++ b/apps/client/src/menus/tree_context_menu.ts
@@ -8,6 +8,7 @@ import type FNote from "../entities/fnote.js";
import attributes from "../services/attributes.js";
import { executeBulkActions } from "../services/bulk_action.js";
import clipboard from "../services/clipboard.js";
+import { copyTextWithToast } from "../services/clipboard_ext.js";
import dialogService from "../services/dialog.js";
import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
@@ -423,7 +424,9 @@ export async function handleTreeContextMenuSelect(
toastService.showMessage(t("tree-context-menu.converted-to-attachments", { count: converted }));
} else if (command === "copyNotePathToClipboard") {
- navigator.clipboard.writeText(`#${notePath}`);
+ // Not `navigator.clipboard`: it is undefined outside secure contexts, and Trilium is
+ // routinely served over plain HTTP on a LAN. Matches the breadcrumb's copy of this command.
+ copyTextWithToast(`#${notePath}`);
} else if (command) {
component.triggerCommand<TreeCommandNames>(command, {
node: resolved.node,
diff --git a/apps/client/src/services/clipboard_ext.spec.ts b/apps/client/src/services/clipboard_ext.spec.ts
index 7c00adfcf3..e5a55b38e4 100644
--- a/apps/client/src/services/clipboard_ext.spec.ts
+++ b/apps/client/src/services/clipboard_ext.spec.ts
@@ -1,7 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import toast from "./toast.js";
-import { copyText, copyTextWithToast } from "./clipboard_ext.js";
+import utils from "./utils.js";
+import { copyHtmlWithToast, copyText, copyTextWithToast } from "./clipboard_ext.js";
const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
@@ -103,3 +104,34 @@ describe("copyTextWithToast", () => {
expect(showMessage).not.toHaveBeenCalled();
});
});
+
+describe("copyHtmlWithToast", () => {
+ it("copies through the copy event, defaults the plain text to the HTML, and reports success", () => {
+ // 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);
+ const copyHtmlToClipboard = vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(true);
+ const showMessage = vi.spyOn(toast, "showMessage").mockImplementation(() => {});
+ const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
+
+ copyHtmlWithToast("<b>x</b>");
+ expect(copyHtmlToClipboard).toHaveBeenCalledWith("<b>x</b>", "<b>x</b>");
+
+ 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", () => {
+ vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(false);
+ const showMessage = vi.spyOn(toast, "showMessage").mockImplementation(() => {});
+ const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
+
+ 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 16eea4ca49..a7c7da135e 100644
--- a/apps/client/src/services/clipboard_ext.ts
+++ b/apps/client/src/services/clipboard_ext.ts
@@ -1,5 +1,6 @@
import { t } from "./i18n.js";
import toast from "./toast.js";
+import utils from "./utils.js";
export function copyText(text: string) {
if (!text) {
@@ -35,3 +36,19 @@ export function copyTextWithToast(text: string) {
toast.showError(t("clipboard.copy_failed"));
}
}
+
+/**
+ * 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.
+ *
+ * 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.
+ */
+export function copyHtmlWithToast(html: string, plainText: string = html) {
+ if (utils.copyHtmlToClipboard(html, plainText)) {
+ toast.showMessage(t("clipboard.copy_success"));
+ } else {
+ toast.showError(t("clipboard.copy_failed"));
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index b75d4bab03..84d255c072 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -3,7 +3,7 @@ import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en
import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
import i18next from "i18next";
-import { copyTextWithToast } from "../../../services/clipboard_ext.js";
+import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboard_ext.js";
import { t } from "../../../services/i18n.js";
import imageService from "../../../services/image.js";
import { getMermaidConfig } from "../../../services/mermaid.js";
@@ -175,7 +175,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
enabled: isSyntaxHighlightEnabled()
},
clipboard: {
- copy: copyTextWithToast
+ copy: copyTextWithToast,
+ copyHtml: copyHtmlWithToast
},
slashCommand: {
// Drop CKEditor's built-in slash commands whose title/icon the palette re-defines: the
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 4048ce4c19..4df90b9652 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -87,6 +87,13 @@ declare module "ckeditor5" {
},
clipboard?: {
copy(text: string): void;
+ /**
+ * Copies rich HTML, with `plainText` as the plain-text alternative. Provided by the host
+ * because `navigator.clipboard.write()` only exists in secure contexts, and Trilium is
+ * routinely served over plain HTTP on a LAN — the host falls back to a copy-event
+ * handler there.
+ */
+ copyHtml?(html: string, plainText: string): void;
},
clipboardImageEmbed?: ClipboardImageEmbedConfig
}
diff --git a/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts b/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
index 3e8be819ae..7bc8a1a20a 100644
--- a/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
+++ b/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
@@ -2,14 +2,14 @@ import { _setModelData as setModelData, Bold, Bookmark, ClassicEditor, Essential
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
-import { installGlobMock, mockClipboard } from "../../test/globals-test-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import CopyAnchorLinkButton from "./copy_anchor_link.js";
describe("CopyAnchorLinkButton", () => {
let editor: ClassicEditor;
let getActiveContextNote: ReturnType<typeof vi.fn>;
let getReferenceLinkTitleSync: ReturnType<typeof vi.fn>;
- let clipboardWrite: ReturnType<typeof vi.fn>;
+ let copyHtml: ReturnType<typeof vi.fn>;
beforeEach(async () => {
getActiveContextNote = vi.fn(() => ({ noteId: "noteAbc" }));
@@ -19,10 +19,11 @@ describe("CopyAnchorLinkButton", () => {
getReferenceLinkTitleSync
});
- clipboardWrite = vi.fn(() => Promise.resolve());
- mockClipboard({ write: clipboardWrite });
+ copyHtml = vi.fn();
- editor = await createTestEditor([Essentials, Paragraph, Bold, Bookmark, CopyAnchorLinkButton]);
+ editor = await createTestEditor([Essentials, Paragraph, Bold, Bookmark, CopyAnchorLinkButton], {
+ clipboard: { copy: vi.fn(), copyHtml }
+ });
});
function getButton() {
@@ -39,24 +40,18 @@ describe("CopyAnchorLinkButton", () => {
getButton().fire("execute");
- expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/noteAbc?bookmark=my%20anchor");
- expect(clipboardWrite).toHaveBeenCalledTimes(1);
-
- const items = clipboardWrite.mock.calls[0]?.[0] as ClipboardItem[];
- expect(items).toHaveLength(1);
- const item = items[0];
- expect(item?.types).toEqual(expect.arrayContaining(["text/html", "text/plain"]));
+ const href = "#root/noteAbc?bookmark=my%20anchor";
+ expect(getReferenceLinkTitleSync).toHaveBeenCalledWith(href);
+ expect(copyHtml).toHaveBeenCalledWith(`<a class="reference-link" href="${href}">Some title</a>`, href);
});
- it("escapes HTML special characters in the generated link", async () => {
+ it("escapes HTML special characters in the generated link", () => {
getReferenceLinkTitleSync.mockReturnValue("a<b>&\"c");
setModelData(editor.model, "<paragraph>[<bookmark bookmarkId=\"anchor\"></bookmark>]</paragraph>");
getButton().fire("execute");
- const items = clipboardWrite.mock.calls[0]?.[0] as ClipboardItem[];
- const htmlBlob = await items[0]?.getType("text/html");
- const html = await htmlBlob?.text();
+ const html = copyHtml.mock.calls[0]?.[0] as string;
expect(html).toContain("&lt;b&gt;");
expect(html).toContain("&amp;");
expect(html).toContain("&quot;");
@@ -69,7 +64,7 @@ describe("CopyAnchorLinkButton", () => {
getButton().fire("execute");
expect(getActiveContextNote).not.toHaveBeenCalled();
- expect(clipboardWrite).not.toHaveBeenCalled();
+ expect(copyHtml).not.toHaveBeenCalled();
});
it("does nothing when there is no selected element", () => {
@@ -78,7 +73,7 @@ describe("CopyAnchorLinkButton", () => {
getButton().fire("execute");
expect(getActiveContextNote).not.toHaveBeenCalled();
- expect(clipboardWrite).not.toHaveBeenCalled();
+ expect(copyHtml).not.toHaveBeenCalled();
});
it("does nothing when there is no active context note", () => {
@@ -88,6 +83,15 @@ describe("CopyAnchorLinkButton", () => {
getButton().fire("execute");
expect(getReferenceLinkTitleSync).not.toHaveBeenCalled();
- expect(clipboardWrite).not.toHaveBeenCalled();
+ expect(copyHtml).not.toHaveBeenCalled();
+ });
+
+ it("does not throw when the host configures no clipboard bridge", async () => {
+ // `navigator.clipboard` is undefined outside secure contexts (Trilium over plain HTTP), so
+ // the button must never reach for it — with no host callback it is simply a no-op (#10723).
+ editor = await createTestEditor([Essentials, Paragraph, Bold, Bookmark, CopyAnchorLinkButton]);
+ setModelData(editor.model, "<paragraph>[<bookmark bookmarkId=\"anchor\"></bookmark>]</paragraph>");
+
+ expect(() => getButton().fire("execute")).not.toThrow();
});
});
diff --git a/packages/ckeditor5/src/plugins/copy_anchor_link.ts b/packages/ckeditor5/src/plugins/copy_anchor_link.ts
index 670b97b8f5..e989529236 100644
--- a/packages/ckeditor5/src/plugins/copy_anchor_link.ts
+++ b/packages/ckeditor5/src/plugins/copy_anchor_link.ts
@@ -5,7 +5,9 @@ import { escapeHtml } from "../utils";
/**
* Adds a "Copy anchor link" button to the bookmark/anchor widget toolbar.
* When clicked, copies a reference link href (e.g. `#root/noteId?bookmark=anchorName`)
- * to the clipboard.
+ * to the clipboard via the host-provided `clipboard.copyHtml` callback (cross-browser
+ * fallback + toast) — `navigator.clipboard` is undefined outside secure contexts, so
+ * writing to it directly crashed the editor when Trilium is served over plain HTTP.
*/
export default class CopyAnchorLinkButton extends Plugin {
@@ -34,12 +36,7 @@ export default class CopyAnchorLinkButton extends Plugin {
const href = `#root/${noteId}?bookmark=${encodeURIComponent(bookmarkId)}`;
const title = glob.getReferenceLinkTitleSync(href);
const html = `<a class="reference-link" href="${escapeHtml(href)}">${escapeHtml(title)}</a>`;
- navigator.clipboard.write([
- new ClipboardItem({
- "text/html": new Blob([html], { type: "text/html" }),
- "text/plain": new Blob([href], { type: "text/plain" })
- })
- ]);
+ editor.config.get("clipboard")?.copyHtml?.(html, href);
}
}
});
diff --git a/packages/ckeditor5/test/globals-test-kit.ts b/packages/ckeditor5/test/globals-test-kit.ts
index 96634a5b10..b342c29437 100644
--- a/packages/ckeditor5/test/globals-test-kit.ts
+++ b/packages/ckeditor5/test/globals-test-kit.ts
@@ -1,8 +1,7 @@
/**
* Helpers for the Trilium global stubs that several specs install on `globalThis` (the `glob`
- * bridge and `navigator.clipboard`). Each installer registers its own teardown, run after every
- * test by the global `afterEach` in `setup.ts`, so specs no longer need to delete/restore these
- * themselves.
+ * bridge). Each installer registers its own teardown, run after every test by the global
+ * `afterEach` in `setup.ts`, so specs no longer need to delete/restore these themselves.
*
* Lives outside `src/`, so it is excluded from both the production build and the 100% coverage
* gate (see editor-kit.ts).
@@ -36,16 +35,3 @@ export function installGlobMock<T extends object>(glob: T): T {
});
return glob;
}
-
-/**
- * Replace `navigator.clipboard` with the given mock for the current test, restoring the original
- * afterwards. Returns the mock for assertion access.
- */
-export function mockClipboard<T extends object>(clipboard: T): T {
- const original = navigator.clipboard;
- Object.defineProperty(navigator, "clipboard", { configurable: true, value: clipboard });
- registerTestCleanup(() => {
- Object.defineProperty(navigator, "clipboard", { configurable: true, value: original });
- });
- return clipboard;
-}