Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): source Copy as Markdown from CKEditor's data pipeline

Elian Doran0604a1443fe1
diff --git a/apps/client/src/menus/electron_context_menu.spec.ts b/apps/client/src/menus/electron_context_menu.spec.ts
new file mode 100644
index 0000000000..f2d522af41
--- /dev/null
+++ b/apps/client/src/menus/electron_context_menu.spec.ts
@@ -0,0 +1,132 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// All mutable mock state lives in a hoisted holder so the (hoisted) vi.mock
+// factory below can reference it.
+const h = vi.hoisted(() => {
+ const tabManager = {
+ activeNote: null as { type: string } | null,
+ activeContext: null as { getTextEditor: () => Promise<unknown> } | null,
+ getActiveContextNote: () => tabManager.activeNote,
+ getActiveContext: () => tabManager.activeContext
+ };
+ return { tabManager };
+});
+
+vi.mock("../components/app_context.js", () => ({
+ default: { tabManager: h.tabManager }
+}));
+
+// The module under test pulls in several DOM/jQuery-heavy collaborators at import
+// time; stub them so importing stays cheap and side-effect free.
+vi.mock("../components/zoom.js", () => ({ default: {} }));
+vi.mock("../services/clipboard_ext.js", () => ({ copyTextWithToast: vi.fn() }));
+vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));
+vi.mock("../services/options.js", () => ({ default: { get: () => "" } }));
+vi.mock("../services/server.js", () => ({ default: { post: vi.fn() } }));
+vi.mock("../services/utils.js", () => ({ default: { escapeHtml: (s: string) => s } }));
+vi.mock("./context_menu.js", () => ({ default: { show: vi.fn() } }));
+
+import { getSelectedHtmlForMarkdown } from "./electron_context_menu.js";
+
+const { tabManager } = h;
+
+/** Builds an editor whose editable DOM root is `domRoot` and selection HTML is `selectedHtml`. */
+function fakeEditor(domRoot: Node | null, selectedHtml: string) {
+ return {
+ editing: { view: { getDomRoot: () => domRoot } },
+ getSelectedHtml: vi.fn(() => selectedHtml)
+ };
+}
+
+/** Points window.getSelection() at `anchorNode`, cloning `fallbackHtml` for the DOM-range path. */
+function setSelection(anchorNode: Node | null, fallbackHtml = "") {
+ const fragment = document.createDocumentFragment();
+ if (fallbackHtml) {
+ const holder = document.createElement("div");
+ holder.innerHTML = fallbackHtml;
+ while (holder.firstChild) fragment.appendChild(holder.firstChild);
+ }
+ vi.spyOn(window, "getSelection").mockReturnValue({
+ anchorNode,
+ rangeCount: anchorNode || fallbackHtml ? 1 : 0,
+ getRangeAt: () => ({ cloneContents: () => fragment.cloneNode(true) })
+ } as unknown as Selection);
+}
+
+describe("getSelectedHtmlForMarkdown", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ tabManager.activeNote = null;
+ tabManager.activeContext = null;
+ });
+
+ it("uses the editor's data-pipeline HTML when the selection is inside the editor", async () => {
+ const editorRoot = document.createElement("div");
+ const anchor = document.createElement("span");
+ editorRoot.appendChild(anchor);
+ const editor = fakeEditor(editorRoot, "<p>clean</p>");
+
+ tabManager.activeNote = { type: "text" };
+ tabManager.activeContext = { getTextEditor: async () => editor };
+ setSelection(anchor, "<b>dom clone</b>");
+
+ expect(await getSelectedHtmlForMarkdown()).toBe("<p>clean</p>");
+ expect(editor.getSelectedHtml).toHaveBeenCalled();
+ });
+
+ it("falls back to the DOM clone when the selection is outside the editor", async () => {
+ const editorRoot = document.createElement("div");
+ const outsideAnchor = document.createElement("span"); // not appended to editorRoot
+ const editor = fakeEditor(editorRoot, "<p>clean</p>");
+
+ tabManager.activeNote = { type: "text" };
+ tabManager.activeContext = { getTextEditor: async () => editor };
+ setSelection(outsideAnchor, "<b>dom clone</b>");
+
+ expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
+ expect(editor.getSelectedHtml).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the DOM clone when the editor selection is empty", async () => {
+ const editorRoot = document.createElement("div");
+ const anchor = document.createElement("span");
+ editorRoot.appendChild(anchor);
+ const editor = fakeEditor(editorRoot, ""); // empty model selection
+
+ tabManager.activeNote = { type: "text" };
+ tabManager.activeContext = { getTextEditor: async () => editor };
+ setSelection(anchor, "<b>dom clone</b>");
+
+ expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
+ });
+
+ it("skips the editor path entirely for a non-text note", async () => {
+ const editor = fakeEditor(document.createElement("div"), "<p>clean</p>");
+ tabManager.activeNote = { type: "code" };
+ tabManager.activeContext = { getTextEditor: async () => editor };
+ setSelection(document.createElement("span"), "<b>dom clone</b>");
+
+ expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
+ expect(editor.getSelectedHtml).not.toHaveBeenCalled();
+ });
+
+ it("falls back when resolving the text editor throws or times out", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {}); // the catch logs the timeout
+ tabManager.activeNote = { type: "text" };
+ tabManager.activeContext = {
+ getTextEditor: async () => {
+ throw new Error("timed out");
+ }
+ };
+ setSelection(document.createElement("span"), "<b>dom clone</b>");
+
+ expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
+ });
+
+ it("returns an empty string when there is no selection at all", async () => {
+ tabManager.activeNote = { type: "text" };
+ setSelection(null);
+
+ expect(await getSelectedHtmlForMarkdown()).toBe("");
+ });
+});
diff --git a/apps/client/src/menus/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.ts
index e6e46f671e..531400bce2 100644
--- a/apps/client/src/menus/electron_context_menu.ts
+++ b/apps/client/src/menus/electron_context_menu.ts
@@ -64,24 +64,17 @@ function setupContextMenu() {
title: t("electron_context_menu.copy-as-markdown"),
uiIcon: "bx bx-copy-alt",
handler: async () => {
- const selection = window.getSelection();
- if (!selection || !selection.rangeCount) return '';
-
- const range = selection.getRangeAt(0);
- const div = document.createElement('div');
- div.appendChild(range.cloneContents());
-
- const htmlContent = div.innerHTML;
- if (htmlContent) {
- try {
- const { markdownContent } = await server.post<{ markdownContent: string }>(
- "other/to-markdown",
- { htmlContent }
- );
- await clipboardExt.copyTextWithToast(markdownContent);
- } catch (error) {
- console.error("Failed to copy as markdown:", error);
- }
+ const htmlContent = await getSelectedHtmlForMarkdown();
+ if (!htmlContent) return;
+
+ try {
+ const { markdownContent } = await server.post<{ markdownContent: string }>(
+ "other/to-markdown",
+ { htmlContent }
+ );
+ await clipboardExt.copyTextWithToast(markdownContent);
+ } catch (error) {
+ console.error("Failed to copy as markdown:", error);
}
}
});
@@ -179,6 +172,46 @@ function setupContextMenu() {
});
}
+/**
+ * Returns the HTML to feed to the Markdown converter for the "Copy as Markdown" action.
+ *
+ * When the selection lives inside the active text note's CKEditor, we take the editor's
+ * data-pipeline HTML (`getSelectedHtml()`) — clean stored markup without the editing-view
+ * artifacts (`data-list-item-id`, collapsible handle/arrow spans, bogus-paragraph wrappers)
+ * that cloning the live DOM range drags along. For any other selection (read-only notes,
+ * dialogs, plain inputs) we fall back to cloning the DOM range.
+ */
+export async function getSelectedHtmlForMarkdown(): Promise<string> {
+ const note = appContext.tabManager.getActiveContextNote();
+
+ if (note?.type === "text") {
+ try {
+ const editor = await appContext.tabManager.getActiveContext()?.getTextEditor();
+ const domRoot = editor?.editing.view.getDomRoot();
+ const anchorNode = window.getSelection()?.anchorNode;
+
+ // Only trust the editor's model selection when the live DOM selection is
+ // actually inside the editor; otherwise a stale editor selection would win
+ // over what the user right-clicked (e.g. selected text in a dialog).
+ if (editor && domRoot && anchorNode && domRoot.contains(anchorNode)) {
+ const selectedHtml = editor.getSelectedHtml();
+ if (selectedHtml) return selectedHtml;
+ }
+ } catch (error) {
+ // Editor not ready or the request timed out — fall through to the DOM clone.
+ console.error("Failed to read selection from the text editor:", error);
+ }
+ }
+
+ const selection = window.getSelection();
+ if (!selection || !selection.rangeCount) return "";
+
+ const range = selection.getRangeAt(0);
+ const div = document.createElement("div");
+ div.appendChild(range.cloneContents());
+ return div.innerHTML;
+}
+
export default {
setupContextMenu
};