Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/AI chat: add a way to copy a whole message to clipboard
Adorian Doran9824c0c136c4
diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.tsindex 97108ba357..52b0ba1a6f 100644--- a/apps/client/src/services/utils.spec.ts+++ b/apps/client/src/services/utils.spec.ts@@ -437,6 +437,21 @@ describe("DOM / clipboard helpers (default export)", () => {delete (document as any).execCommand;});+ it("copyHtmlToClipboard writes a distinct plain-text payload when given one", () => {+ const setData = vi.fn();+ const execSpy = vi.fn(() => {+ const evt: any = new Event("copy");+ evt.clipboardData = { setData };+ document.dispatchEvent(evt);+ return true;+ });+ (document as any).execCommand = execSpy;+ utils.copyHtmlToClipboard("<b>x</b>", "x");+ expect(setData).toHaveBeenCalledWith("text/html", "<b>x</b>");+ expect(setData).toHaveBeenCalledWith("text/plain", "x");+ delete (document as any).execCommand;+ });+it("copyHtmlToClipboard tolerates a copy event without clipboardData", () => {const execSpy = vi.fn(() => {document.dispatchEvent(new Event("copy"));diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex e805fc9268..0b3711c235 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -587,17 +587,18 @@ function areObjectsEqual(...args: unknown[]) {return true;}-function copyHtmlToClipboard(content: string) {+function copyHtmlToClipboard(html: string, plainText: string = html) {function listener(e: ClipboardEvent) {if (e.clipboardData) {- e.clipboardData.setData("text/html", content);- e.clipboardData.setData("text/plain", content);+ e.clipboardData.setData("text/html", html);+ e.clipboardData.setData("text/plain", plainText);}e.preventDefault();}document.addEventListener("copy", listener);- document.execCommand("copy");+ const ok = document.execCommand("copy");document.removeEventListener("copy", listener);+ return ok;}export function createImageSrcUrl(note: FNote) {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 618ec8615e..cffd99298f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2078,6 +2078,7 @@"highlight_remove": "Remove highlight","highlight_remove_confirm": "Remove this highlight?","quote_selection": "Quote selection",+ "copy_message": "Copy message","save_to_subnote": "Save to sub-note","save_to_subnote_failed": "Failed to create a note from the message.","attach_file": "Attach image, PDF, or text file",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_copy.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_copy.spec.tsnew file mode 100644index 0000000000..d8b9182505--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_copy.spec.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from "vitest";++import { canCopyMessage } from "./chat_copy.js";++describe("canCopyMessage", () => {+ it("offers the command with no selection and a non-empty message", () => {+ expect(canCopyMessage(false, "some reply text")).toBe(true);+ });++ it("hides the command when text is selected (the selection commands apply instead)", () => {+ expect(canCopyMessage(true, "some reply text")).toBe(false);+ });++ it("hides the command when the message has no text to copy", () => {+ expect(canCopyMessage(false, "")).toBe(false);+ expect(canCopyMessage(false, " \n\t ")).toBe(false);+ });+});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_copy.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_copy.tsnew file mode 100644index 0000000000..172930546d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_copy.ts@@ -0,0 +1,27 @@+import { t } from "../../../services/i18n.js";+import toast from "../../../services/toast.js";+import utils from "../../../services/utils.js";+import { renderMarkdown } from "./chat_markdown.js";++/**+ * Whether the "Copy message" command should be offered for a right-clicked message: only with no+ * active text selection (a selection means the selection commands apply) and only when the message+ * actually has text. Unlike saving to a sub-note, copying needs no parent note, so it works in both+ * the note chat and the right-pane sidebar chat.+ */+export function canCopyMessage(hasSelection: boolean, markdown: string): boolean {+ return !hasSelection && markdown.trim().length > 0;+}++/**+ * Copy a whole message to the clipboard: rich HTML (rendered from the markdown, so it pastes with+ * formatting into a note or other rich editor) plus the markdown source as the plain-text fallback.+ */+export function copyMessageToClipboard(markdown: string) {+ const ok = utils.copyHtmlToClipboard(renderMarkdown(markdown), markdown);+ if (ok) {+ toast.showMessage(t("clipboard.copy_success"));+ } else {+ toast.showError(t("clipboard.copy_failed"));+ }+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.tsindex ff7a8d317d..13a0c39ec4 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts@@ -7,6 +7,7 @@ import contextMenu, { type MenuItem } from "../../../menus/context_menu.js";import { t } from "../../../services/i18n.js";import toast from "../../../services/toast.js";import { randomString } from "../../../services/utils.js";+import { canCopyMessage, copyMessageToClipboard } from "./chat_copy.js";import { createAnchorFromSelection, resolveAnchorRange } from "./chat_highlights_anchor.js";import { buildQuoteMarkdown } from "./chat_quote.js";import { canSaveToSubNote, saveMessageToSubNote } from "./chat_save.js";@@ -132,10 +133,10 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte}, []);// Right-click menu over the timeline. With a text selection: Copy, Quote, and Add/Remove- // highlight. With no selection: Save the whole message to a sub-note (note chats only). Because- // preventing the default menu drops the browser's own Copy, we provide it here. Bails (leaving the- // native menu) when there's nothing to offer. Copy stays available while a reply streams; only the- // message-mutating add/remove are suppressed then.+ // highlight. With no selection: Copy the whole message, and Save it to a sub-note (note chats+ // only). Because preventing the default menu drops the browser's own Copy, we provide it here.+ // Bails (leaving the native menu) when there's nothing to offer. Copy stays available while a+ // reply streams; only the message-mutating add/remove are suppressed then.useEffect(() => {const container = scrollContainerRef.current;if (!container) return;@@ -182,13 +183,20 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte// commands above apply, and a whole-message save would then be confusing.const parentNotePath = noteContextRef.current?.notePath;const hasSelection = !!selectionRange?.toString().trim();- const savedMessage = messagesRef.current.find(m => m.id === messageId);- const savedMarkdown = savedMessage ? getMessageText(savedMessage.content) : "";- if (parentNotePath && canSaveToSubNote(parentNotePath, hasSelection, savedMarkdown)) {+ const message = messagesRef.current.find(m => m.id === messageId);+ const messageMarkdown = message ? getMessageText(message.content) : "";+ if (canCopyMessage(hasSelection, messageMarkdown)) {+ items.push({+ title: t("llm_chat.copy_message"),+ uiIcon: "bx bx-copy",+ handler: () => copyMessageToClipboard(messageMarkdown)+ });+ }+ if (parentNotePath && canSaveToSubNote(parentNotePath, hasSelection, messageMarkdown)) {items.push({title: t("llm_chat.save_to_subnote"),uiIcon: "bx bx-save",- handler: () => void saveMessageToSubNote(parentNotePath, savedMarkdown)+ handler: () => void saveMessageToSubNote(parentNotePath, messageMarkdown)});}