Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: improve the way clipboard commands from context menu operate

Adorian Dorane77563da3aa0
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.ts
index 7be66c61b7..8abb182b98 100644
--- a/apps/client/src/menus/note_context_menu.spec.ts
+++ b/apps/client/src/menus/note_context_menu.spec.ts
@@ -28,13 +28,14 @@ vi.mock("../services/utils.js", () => ({
}));
vi.mock("./context_menu.js", () => ({ default: { show: vi.fn() } }));
vi.mock("./table_context_menu.js", () => ({
- buildTableContextMenuItems: vi.fn(async () => null)
+ buildTableContextMenuItems: vi.fn(async () => null),
+ hasTableCellSelection: vi.fn(async () => false)
}));
import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";
import server from "../services/server.js";
import contextMenu, { type MenuCommandItem, type MenuItem } from "./context_menu.js";
-import { buildTableContextMenuItems } from "./table_context_menu.js";
+import { buildTableContextMenuItems, hasTableCellSelection } from "./table_context_menu.js";
import {
buildNoteContextMenuItems,
type ContextMenuHost,
@@ -46,10 +47,12 @@ import {
const { tabManager } = h;
/** Builds an editor whose editable DOM root is `domRoot` and selection HTML is `selectedHtml`. */
-function fakeEditor(domRoot: Node | null, selectedHtml: string) {
+function fakeEditor(domRoot: Node | null, selectedHtml: string, plainText = "") {
return {
editing: { view: { getDomRoot: () => domRoot } },
getSelectedHtml: vi.fn(() => selectedHtml),
+ getSelectedPlainText: vi.fn(() => plainText),
+ pasteContent: vi.fn(),
// Without the plugin the AI assistant row is skipped, keeping these tests off it.
plugins: { has: () => false },
isReadOnly: false,
@@ -247,10 +250,51 @@ describe("buildNoteContextMenuItems", () => {
await run(items, "electron_context_menu.copy-as-markdown");
expect(server.post).toHaveBeenCalledWith("other/to-markdown", {
- htmlContent: "<h1>Hi</h1>"
+ htmlContent: "<h1>Hi</h1>",
+ headerlessTables: "emptyHeader"
});
expect(copyTextWithToast).toHaveBeenCalledWith("# Hi");
});
+
+ it("enables the clipboard rows over a cell selection with no selection text", async () => {
+ const cell = document.createElement("td");
+ vi.mocked(buildTableContextMenuItems).mockResolvedValue([
+ { title: "T1" }
+ ] as MenuItem<any>[]);
+
+ // No cell selection and no text: the rows show but stay disabled.
+ const disabled = await build({ isEditable: true, element: cell, selectionText: "" });
+ expect(findItem(disabled, "electron_context_menu.cut")?.enabled).toBe(false);
+ expect(findItem(disabled, "electron_context_menu.copy")?.enabled).toBe(false);
+ expect(findItem(disabled, "electron_context_menu.copy-as-markdown")?.enabled).toBe(false);
+
+ vi.mocked(hasTableCellSelection).mockResolvedValue(true);
+ const enabled = await build({ isEditable: true, element: cell, selectionText: "" });
+ expect(findItem(enabled, "electron_context_menu.cut")?.enabled).toBe(true);
+ expect(findItem(enabled, "electron_context_menu.copy")?.enabled).toBe(true);
+ expect(findItem(enabled, "electron_context_menu.copy-as-markdown")?.enabled).toBe(true);
+
+ vi.mocked(buildTableContextMenuItems).mockResolvedValue(null);
+ vi.mocked(hasTableCellSelection).mockResolvedValue(false);
+ });
+
+ it("ignores the fake-selection label Electron reports over a cell selection", async () => {
+ const cell = document.createElement("td");
+ vi.mocked(buildTableContextMenuItems).mockResolvedValueOnce([
+ { title: "T1" }
+ ] as MenuItem<any>[]);
+ vi.mocked(hasTableCellSelection).mockResolvedValueOnce(true);
+
+ const shown = titles(await build({
+ isEditable: true,
+ element: cell,
+ selectionText: "Selected 4 cells"
+ }));
+
+ expect(shown).not.toContain("electron_context_menu.search_online");
+ expect(shown).not.toContain("electron_context_menu.search_in_trilium");
+ expect(shown).toContain("electron_context_menu.copy");
+ });
});
describe("setupContextMenu (browser)", () => {
@@ -441,6 +485,101 @@ describe("setupContextMenu (browser)", () => {
expect(execCommand).not.toHaveBeenCalled();
});
+ it("copies the editor's plain-text flavor, not the DOM selection's fake label", async () => {
+ const editorRoot = codeEditable();
+ const anchor = document.createElement("span");
+ editorRoot.appendChild(anchor);
+ const editor = fakeEditor(editorRoot, "<table><tr><td>a1</td></tr></table>", "a1");
+ tabManager.activeNote = { type: "text" };
+ tabManager.activeContext = { getTextEditor: async () => editor };
+ setSelection(anchor, "", "Selected 1 cell");
+
+ await run(await menuFor(editorRoot), "electron_context_menu.copy");
+
+ expect(copyHtml).toHaveBeenCalledWith("<table><tr><td>a1</td></tr></table>", "a1");
+ });
+
+ it("offers paste in a secure context and routes it through the editor's pipeline", async () => {
+ const flavor = (type: string) => ({
+ text: async () => type === "text/html" ? "<b>hi</b>" : "hi"
+ });
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: {
+ read: vi.fn(async () => [ {
+ types: [ "text/html", "text/plain" ],
+ getType: async (type: string) => flavor(type)
+ } ])
+ }
+ });
+
+ try {
+ const editorRoot = codeEditable();
+ 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, "<p>clean</p>", "clean");
+
+ const rows = await menuFor(editorRoot);
+ expect(findItem(rows, "electron_context_menu.paste")?.enabled).toBe(true);
+
+ await run(rows, "electron_context_menu.paste");
+ await vi.waitFor(() =>
+ expect(editor.pasteContent).toHaveBeenCalledWith("<b>hi</b>", "hi"));
+
+ // Paste as plain text withholds the HTML flavor.
+ await run(rows, "electron_context_menu.paste-as-plain-text");
+ await vi.waitFor(() => expect(editor.pasteContent).toHaveBeenCalledWith("", "hi"));
+ } finally {
+ delete (navigator as { clipboard?: unknown }).clipboard;
+ }
+ });
+
+ it("pastes into a code note as a typed text insertion", async () => {
+ const execCommand = stubExecCommand();
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: {
+ read: vi.fn(async () => [
+ { types: [ "text/plain" ], getType: async () => ({ text: async () => "hi" }) }
+ ])
+ }
+ });
+
+ try {
+ const content = codeEditable();
+ tabManager.activeNote = { type: "code" };
+ setSelection(content, "<span>code</span>", "code");
+
+ await run(await menuFor(content), "electron_context_menu.paste");
+
+ await vi.waitFor(() =>
+ expect(execCommand).toHaveBeenCalledWith("insertText", false, "hi"));
+ } finally {
+ delete (navigator as { clipboard?: unknown }).clipboard;
+ }
+ });
+
+ it("drops the paste rows where the clipboard cannot be read", async () => {
+ // Plain HTTP, where the async clipboard API is undefined (#10723).
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined });
+
+ try {
+ const content = codeEditable();
+ tabManager.activeNote = { type: "code" };
+ setSelection(content, "<span>code</span>", "code");
+
+ const shown = titles(await menuFor(content));
+
+ expect(shown).not.toContain("electron_context_menu.paste");
+ expect(shown).not.toContain("electron_context_menu.paste-as-plain-text");
+ } finally {
+ delete (navigator as { clipboard?: unknown }).clipboard;
+ }
+ });
+
it("drops the cut row in a read-only code note", async () => {
const content = codeEditable(true);
tabManager.activeNote = { type: "code" };
diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.ts
index 00c03f67fa..e66692f7db 100644
--- a/apps/client/src/menus/note_context_menu.ts
+++ b/apps/client/src/menus/note_context_menu.ts
@@ -7,7 +7,7 @@ import options from "../services/options.js";
import server from "../services/server.js";
import utils from "../services/utils.js";
import contextMenu, { type MenuItem } from "./context_menu.js";
-import { buildTableContextMenuItems } from "./table_context_menu.js";
+import { buildTableContextMenuItems, hasTableCellSelection } from "./table_context_menu.js";
import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";
/** What the pointer was over when the menu was summoned. */
@@ -28,8 +28,8 @@ export interface ContextMenuTarget {
/**
* What the surrounding application can run on the menu's behalf. An optional member the host leaves
- * out drops the rows that depend on it: a page reaches neither the spell checker's state nor a
- * paste cheaper than Ctrl+V, so a browser host supplies neither.
+ * out drops the rows that depend on it: a page never reaches the spell checker's state, and reads
+ * the clipboard only in a secure context, so the browser host leaves out what it cannot serve.
*/
export interface ContextMenuHost {
spelling?: {
@@ -117,7 +117,6 @@ export async function buildNoteContextMenuItems(
target: ContextMenuTarget,
host: ContextMenuHost
): Promise<MenuItem<CommandNames>[]> {
- const hasText = target.selectionText.trim().length > 0;
const platformModifier = utils.isMac() ? "Meta" : "Ctrl";
const items: MenuItem<CommandNames>[] = [];
@@ -127,6 +126,13 @@ export async function buildNoteContextMenuItems(
const aiActions = target.isEditable ? await buildAiActionsMenuItem() : null;
const tableItems = target.isEditable ? await buildTableContextMenuItems(target.element) : null;
+ // Read after the table section is built, which moves the selection into the clicked cell.
+ // A cell selection supersedes `selectionText`: over one, Electron reports the hidden
+ // fake-selection label as the selected text, which no row should act on.
+ const hasCellSelection = tableItems !== null && await hasTableCellSelection(target.element);
+ const hasText = !hasCellSelection && target.selectionText.trim().length > 0;
+ const hasClipboardContent = hasText || hasCellSelection;
+
if (host.spelling?.misspelledWord) {
const { misspelledWord, suggestions, addToDictionary } = host.spelling;
@@ -158,7 +164,7 @@ export async function buildNoteContextMenuItems(
if (target.isEditable) {
items.push({
- enabled: host.canCut && hasText,
+ enabled: host.canCut && hasClipboardContent,
title: t("electron_context_menu.cut"),
shortcut: `${platformModifier}+X`,
uiIcon: "bx bx-cut",
@@ -168,7 +174,7 @@ export async function buildNoteContextMenuItems(
if (target.isEditable || hasText) {
items.push({
- enabled: host.canCopy && hasText,
+ enabled: host.canCopy && hasClipboardContent,
title: t("electron_context_menu.copy"),
shortcut: `${platformModifier}+C`,
uiIcon: "bx bx-copy",
@@ -176,7 +182,7 @@ export async function buildNoteContextMenuItems(
});
items.push({
- enabled: hasText,
+ enabled: hasClipboardContent,
title: t("electron_context_menu.copy-as-markdown"),
uiIcon: "bx bx-copy-alt",
handler: copySelectionAsMarkdown
@@ -284,7 +290,7 @@ export async function getSelectedHtmlForMarkdown(): Promise<string> {
async function showBrowserContextMenu(x: number, y: number, target: ContextMenuTarget) {
const editor = await getTextEditorAtSelection();
- const items = await buildNoteContextMenuItems(target, browserHost(editor));
+ const items = await buildNoteContextMenuItems(target, browserHost(editor, target.element));
if (!items.length) return;
contextMenu.show({ x, y, items, selectMenuItemHandler: () => {} });
@@ -321,8 +327,14 @@ function acceptsTyping(element: HTMLElement | null) {
* `editor` is what the selection sits in, when it sits in a text note at all — `null` in a code
* note, which has a CodeMirror instead, and in a plain field.
*/
-function browserHost(editor: CKTextEditor | null): ContextMenuHost {
+function browserHost(
+ editor: CKTextEditor | null,
+ element: Element | null | undefined
+): ContextMenuHost {
+ const paste = browserPaste(editor, element);
+
return {
+ ...(paste && { paste }),
canCut: !editor?.isReadOnly,
cut() {
// A text note's editor is asked directly, so that the clipboard gets the clean
@@ -341,10 +353,79 @@ function browserHost(editor: CKTextEditor | null): ContextMenuHost {
};
}
+/**
+ * The paste rows for a page, present only where the async clipboard API can read: a secure
+ * context, with the user granting the read on first use. Over plain HTTP the browser exposes no
+ * way to read the clipboard, so the rows stay out and Ctrl+V remains the way to paste.
+ */
+function browserPaste(
+ editor: CKTextEditor | null,
+ element: Element | null | undefined
+): ContextMenuHost["paste"] {
+ if (!navigator.clipboard?.read) {
+ return undefined;
+ }
+
+ return {
+ // Whether the clipboard holds anything is unknowable without reading it, which prompts
+ // for permission, so the rows stay enabled and an empty clipboard pastes nothing.
+ enabled: true,
+ run: () => void pasteFromClipboard(editor, element, false),
+ runAsPlainText: () => void pasteFromClipboard(editor, element, true)
+ };
+}
+
+async function pasteFromClipboard(
+ editor: CKTextEditor | null,
+ element: Element | null | undefined,
+ asPlainText: boolean
+) {
+ try {
+ const { html, text } = await readClipboard();
+
+ // The editor's clipboard pipeline, so a paste lands the way a native one does — a table
+ // pasted into a multi-cell selection merges into it.
+ if (editor) {
+ editor.pasteContent(asPlainText ? "" : html, text);
+ return;
+ }
+
+ // A non-CKEditor editable (a code note's CodeMirror, a plain field) takes the text
+ // flavor as a typed insertion.
+ const editable = element?.closest<HTMLElement>("[contenteditable]");
+ if (editable && text) {
+ editable.focus();
+ document.execCommand("insertText", false, text);
+ }
+ } catch (error) {
+ console.warn("Failed to paste from the clipboard:", error);
+ }
+}
+
+/** The first `text/html` and `text/plain` flavors on the clipboard, empty when absent. */
+async function readClipboard(): Promise<{ html: string; text: string }> {
+ let html = "";
+ let text = "";
+
+ 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();
+ }
+ }
+
+ return { html, text };
+}
+
/** Copies the selection as rich text, so that it pastes back into a note with its formatting. */
async function copySelection() {
const html = await getSelectedHtmlForMarkdown();
- const plainText = window.getSelection()?.toString() ?? "";
+ // The editor's own plain-text flavor first: over a multi-cell table selection the DOM
+ // selection reads as the hidden fake-selection label, not as cell text.
+ const editor = await getTextEditorAtSelection();
+ const plainText = (editor?.getSelectedPlainText() || window.getSelection()?.toString()) ?? "";
if (!html && !plainText) return;
await copyHtml(html || utils.escapeHtml(plainText), plainText);
@@ -357,7 +438,9 @@ async function copySelectionAsMarkdown() {
try {
const { markdownContent } = await server.post<{ markdownContent: string }>(
"other/to-markdown",
- { htmlContent }
+ // The clipboard never reimports, so a headerless table (a copied subset of body
+ // cells) becomes a markdown table under a blank header instead of raw HTML.
+ { htmlContent, headerlessTables: "emptyHeader" }
);
copyTextWithToast(markdownContent);
} catch (error) {
diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.ts
index 47fa44501d..975bb2cc46 100644
--- a/apps/client/src/menus/table_context_menu.spec.ts
+++ b/apps/client/src/menus/table_context_menu.spec.ts
@@ -6,7 +6,11 @@ vi.mock("./text_editor_context_menu.js", () => ({ getTextEditorContaining: vi.fn
import type { CKTextEditor } from "@triliumnext/ckeditor5";
import type { MenuCommandItem, MenuItem } from "./context_menu.js";
-import { buildTableContextMenuItems, buildTableMenuItems } from "./table_context_menu.js";
+import {
+ buildTableContextMenuItems,
+ buildTableMenuItems,
+ hasTableCellSelection
+} from "./table_context_menu.js";
import { getTextEditorContaining } from "./text_editor_context_menu.js";
const SECTION_TITLES = [
@@ -119,6 +123,43 @@ describe("buildTableContextMenuItems", () => {
});
});
+describe("hasTableCellSelection", () => {
+ const resolveEditor = vi.mocked(getTextEditorContaining);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("reports the resolved editor's multi-cell selection", async () => {
+ let selected: unknown[] | null = [ {}, {} ];
+ resolveEditor.mockResolvedValue({
+ plugins: {
+ has: (name: string) => name === "TableSelection",
+ get: () => ({ getSelectedTableCells: () => selected })
+ }
+ } as unknown as CKTextEditor);
+
+ expect(await hasTableCellSelection(cellElement())).toBe(true);
+
+ // A caret or a plain text range inside one cell reports null.
+ selected = null;
+ expect(await hasTableCellSelection(cellElement())).toBe(false);
+ });
+
+ it("reports false without an element, an editor, or the plugin", async () => {
+ expect(await hasTableCellSelection(null)).toBe(false);
+ expect(resolveEditor).not.toHaveBeenCalled();
+
+ resolveEditor.mockResolvedValue(null);
+ expect(await hasTableCellSelection(cellElement())).toBe(false);
+
+ resolveEditor.mockResolvedValue(
+ { plugins: { has: () => false } } as unknown as CKTextEditor
+ );
+ expect(await hasTableCellSelection(cellElement())).toBe(false);
+ });
+});
+
/**
* A minimal editor double: `TableContextMenu` is present unless `hasPlugin` says otherwise, and
* every command is enabled except the ones in `disabledCommands`.
diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.ts
index 7a0f38ca2a..c26362c8bd 100644
--- a/apps/client/src/menus/table_context_menu.ts
+++ b/apps/client/src/menus/table_context_menu.ts
@@ -75,3 +75,20 @@ export function buildTableMenuItems(
}
];
}
+
+/**
+ * Whether the active text editor containing `element` holds a multi-cell table selection.
+ * A caret or a plain text range inside one cell is not one.
+ */
+export async function hasTableCellSelection(element: Element | null | undefined): Promise<boolean> {
+ if (!element) {
+ return false;
+ }
+
+ const editor = await getTextEditorContaining(element);
+ if (!editor?.plugins.has("TableSelection")) {
+ return false;
+ }
+
+ return editor.plugins.get("TableSelection").getSelectedTableCells() !== null;
+}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
index 5256d59c6e..501ceccece 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
@@ -24,6 +24,18 @@ src="3_Tables_image.png" width="384" height="100">
<li><em>Merge cells</em> merges the selected cells into one. The selected cells
must form a rectangle.</li>
<li><em>Split cells</em> splits each selected cell in two, either <em>Vertically</em> or <em>Horizontally</em>.</li>
+ <li><em>Cut</em>, <em>Copy</em> and <em>Copy as Markdown</em>, below the table
+ section, act on the selected cells:
+ <ul>
+ <li>Cutting or copying produces a smaller table holding just the selected
+ cells. Pasting it over a cell selection replaces those cells; pasting elsewhere
+ inserts it as a table of its own. Cutting clears the cells without removing
+ rows or columns.</li>
+ <li><em>Copy as Markdown</em> converts the selected cells to a Markdown table.
+ A selected header row becomes the Markdown header; without one, an empty
+ header row is emitted, since Markdown tables require one.</li>
+ </ul>
+ </li>
</ul>
<p>Right-clicking a cell that is not part of the current selection moves
the cursor there first, so the menu always applies to the cell under the
@@ -32,7 +44,10 @@ src="3_Tables_image.png" width="384" height="100">
<p>In the browser, Trilium's menu replaces the browser's own context menu
inside tables. To reach the browser's menu (for example for its spell checking
suggestions), hold <kbd>Shift</kbd> while right-clicking. The desktop application
- is unaffected, since its menu already includes the spelling suggestions.</p>
+ is unaffected, since its menu already includes the spelling suggestions.
+ In the browser, the menu also offers <em>Paste</em> only when the page can
+ read the clipboard, which requires a secure (HTTPS) context and your permission;
+ otherwise, paste with <kbd>Ctrl</kbd>+<kbd>V</kbd>.</p>
</aside>
<h2>Navigating a table</h2>
<ul>
diff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.md
index 252c8e7da6..d5159855db 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md
@@ -20,11 +20,14 @@ Since v0.106.0, right-clicking anywhere inside a table opens a context menu with
* _Delete rows_ and _Delete columns_ remove every row or column the selection touches, even when only some of their cells are selected.
* _Merge cells_ merges the selected cells into one. The selected cells must form a rectangle.
* _Split cells_ splits each selected cell in two, either _Vertically_ or _Horizontally_.
+* _Cut_, _Copy_ and _Copy as Markdown_, below the table section, act on the selected cells:
+ * Cutting or copying produces a smaller table holding just the selected cells. Pasting it over a cell selection replaces those cells; pasting elsewhere inserts it as a table of its own. Cutting clears the cells without removing rows or columns.
+ * _Copy as Markdown_ converts the selected cells to a Markdown table. A selected header row becomes the Markdown header; without one, an empty header row is emitted, since Markdown tables require one.
Right-clicking a cell that is not part of the current selection moves the cursor there first, so the menu always applies to the cell under the pointer.
> [!NOTE]
-> In the browser, Trilium's menu replaces the browser's own context menu inside tables. To reach the browser's menu (for example for its spell checking suggestions), hold <kbd>Shift</kbd> while right-clicking. The desktop application is unaffected, since its menu already includes the spelling suggestions.
+> In the browser, Trilium's menu replaces the browser's own context menu inside tables. To reach the browser's menu (for example for its spell checking suggestions), hold <kbd>Shift</kbd> while right-clicking. The desktop application is unaffected, since its menu already includes the spelling suggestions. In the browser, the menu also offers _Paste_ only when the page can read the clipboard, which requires a secure (HTTPS) context and your permission; otherwise, paste with <kbd>Ctrl</kbd>+<kbd>V</kbd>.
## Navigating a table
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 87f733fad6..568caeed92 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -35,6 +35,8 @@ window[Symbol.for("cke distribution")] = "trilium";
*/
export type CKTextEditor = (ClassicEditor | PopupEditor) & {
getSelectedHtml(): string;
+ getSelectedPlainText(): string;
+ pasteContent(html: string, text: string): void;
removeSelection(): Promise<void>;
};
@@ -72,6 +74,8 @@ export class PopupEditor extends BalloonEditor {
declare module "ckeditor5" {
interface Editor {
getSelectedHtml(): string;
+ getSelectedPlainText(): string;
+ pasteContent(html: string, text: string): void;
removeSelection(): Promise<void>;
}
diff --git a/packages/ckeditor5/src/plugins/cuttonote.spec.ts b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
index 782cd11519..4c38a04986 100644
--- a/packages/ckeditor5/src/plugins/cuttonote.spec.ts
+++ b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
@@ -1,4 +1,4 @@
-import { _setModelData as setModelData, ClassicEditor, Essentials, List, Paragraph } from "ckeditor5";
+import { _setModelData as setModelData, ClassicEditor, Essentials, List, Paragraph, Table, TableSelection } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
@@ -74,6 +74,90 @@ describe("CutToNotePlugin", () => {
expect(editor.getSelectedHtml()).toBe("");
});
+ it("augments the editor with getSelectedPlainText for the plain-text flavor", () => {
+ setModelData(editor.model, "<paragraph>foo[bar]baz</paragraph>");
+
+ expect(editor.getSelectedPlainText()).toBe("bar");
+ });
+
+ it("pasteContent runs the given flavors through the clipboard paste pipeline", () => {
+ setModelData(editor.model, "<paragraph>a[]b</paragraph>");
+ editor.pasteContent("<span>X</span>", "X");
+ expect(editor.getData()).toContain("aXb");
+
+ // Without HTML the text flavor pastes as plain text.
+ setModelData(editor.model, "<paragraph>c[]d</paragraph>");
+ editor.pasteContent("", "plain");
+ expect(editor.getData()).toContain("plain");
+
+ // With neither flavor nothing is inserted.
+ setModelData(editor.model, "<paragraph>e[]f</paragraph>");
+ editor.pasteContent("", "");
+ expect(editor.getData()).toContain("ef");
+ });
+
+ describe("table cell selections", () => {
+ let tableEditor: ClassicEditor;
+
+ beforeEach(async () => {
+ tableEditor = await createTestEditor([Essentials, Paragraph, Table, CutToNotePlugin]);
+ });
+
+ it("serializes a cell selection as a table of just the selected cells", () => {
+ setModelData(tableEditor.model, modelTable([
+ ["a1", "b1", "c1"],
+ ["a2", "b2", "c2"],
+ ["a3", "b3", "c3"]
+ ]));
+ selectCells(tableEditor, [1, 1], [2, 2]);
+
+ const html = tableEditor.getSelectedHtml();
+ expect(html).toContain("<table");
+ for (const kept of ["b2", "c2", "b3", "c3"]) {
+ expect(html).toContain(kept);
+ }
+ for (const dropped of ["a1", "b1", "c1", "a2", "a3"]) {
+ expect(html).not.toContain(dropped);
+ }
+ });
+
+ it("keeps header cells when the selection includes the heading row", () => {
+ setModelData(tableEditor.model,
+ modelTable([["h1", "h2"], ["a1", "a2"]], 'headingRows="1"'));
+ selectCells(tableEditor, [0, 0], [1, 1]);
+
+ const html = tableEditor.getSelectedHtml();
+ expect(html).toContain("<th>");
+ expect(html).toContain("h1");
+ expect(html).toContain("a2");
+ });
+
+ it("reads a cell selection as cell text via getSelectedPlainText", () => {
+ setModelData(tableEditor.model, modelTable([["a1", "b1"], ["a2", "b2"]]));
+ selectCells(tableEditor, [0, 0], [1, 0]);
+
+ const text = tableEditor.getSelectedPlainText();
+ expect(text).toContain("a1");
+ expect(text).toContain("a2");
+ expect(text).not.toContain("b1");
+ });
+
+ it("pasteContent merges a copied cell fragment into a cell selection", () => {
+ setModelData(tableEditor.model, modelTable([["a1", "b1"], ["a2", "b2"]]));
+ selectCells(tableEditor, [0, 0], [1, 1]);
+ const html = tableEditor.getSelectedHtml();
+
+ setModelData(tableEditor.model, modelTable([["x1", "y1"], ["x2", "y2"]]));
+ selectCells(tableEditor, [0, 0], [1, 1]);
+ tableEditor.pasteContent(html, "");
+
+ const data = tableEditor.getData();
+ expect(data).toContain("a1");
+ expect(data).toContain("b2");
+ expect(data).not.toContain("x1");
+ });
+ });
+
it("removeSelection deletes the selection, inserts a paragraph and saves the note", async () => {
setModelData(editor.model, "<paragraph>foo[bar]baz</paragraph>");
@@ -93,3 +177,30 @@ describe("CutToNotePlugin", () => {
expect(triggerCommand).toHaveBeenCalledWith("saveNoteDetailNow");
});
});
+
+function modelTable(rows: string[][], attributes = ""): string {
+ const rowsMarkup = rows
+ .map((cells) => {
+ const cellsMarkup = cells
+ .map((cell) => `<tableCell><paragraph>${cell}</paragraph></tableCell>`)
+ .join("");
+ return `<tableRow>${cellsMarkup}</tableRow>`;
+ })
+ .join("");
+ return `<table${attributes ? ` ${attributes}` : ""}>${rowsMarkup}</table>`;
+}
+
+function selectCells(editor: ClassicEditor, anchor: [number, number], target: [number, number]) {
+ const getCell = (row: number, column: number) => {
+ const cell = editor.model.document.getRoot()?.getNodeByPath([0, row, column]);
+ if (!cell || !cell.is("element", "tableCell")) {
+ throw new Error(`No table cell at row ${row}, column ${column}.`);
+ }
+ return cell;
+ };
+
+ editor.plugins.get(TableSelection).setCellSelection(
+ getCell(anchor[0], anchor[1]),
+ getCell(target[0], target[1])
+ );
+}
diff --git a/packages/ckeditor5/src/plugins/cuttonote.ts b/packages/ckeditor5/src/plugins/cuttonote.ts
index 41a2e8617a..cf7727a9fb 100644
--- a/packages/ckeditor5/src/plugins/cuttonote.ts
+++ b/packages/ckeditor5/src/plugins/cuttonote.ts
@@ -1,5 +1,6 @@
import scissorsIcon from '../icons/scissors.svg?raw';
-import { ButtonView, HtmlDataProcessor, Plugin } from 'ckeditor5';
+import { ButtonView, HtmlDataProcessor, Plugin, plainTextToHtml, ViewDataTransfer, viewToPlainText } from 'ckeditor5';
+import type { ViewDocumentFragment } from 'ckeditor5';
export default class CutToNotePlugin extends Plugin {
@@ -31,20 +32,62 @@ export default class CutToNotePlugin extends Plugin {
} );
this.editor.getSelectedHtml = () => this.getSelectedHtml();
+ this.editor.getSelectedPlainText = () => this.getSelectedPlainText();
+ this.editor.pasteContent = (html, text) => this.pasteContent(html, text);
this.editor.removeSelection = () => this.removeSelection();
}
getSelectedHtml() {
+ return this.htmlDataProcessor.toData(this.getSelectedViewFragment());
+ }
+
+ /**
+ * Returns the selected content as plain text, through the same `viewToPlainText` the native
+ * copy uses for the `text/plain` clipboard flavor.
+ */
+ getSelectedPlainText() {
+ return viewToPlainText(this.editor.editing.view.domConverter, this.getSelectedViewFragment());
+ }
+
+ /**
+ * Returns the selected content as a view fragment.
+ *
+ * A multi-cell table selection goes through `TableSelection#getSelectionAsFragment()`, the
+ * same crop the native table copy uses, so it serializes as a table of just the selected
+ * cells. The downcast runs through the clipboard pipeline so editor-only list bookkeeping
+ * (data-list-item-id) is skipped, matching what a native copy produces.
+ */
+ private getSelectedViewFragment(): ViewDocumentFragment {
const model = this.editor.model;
- const document = model.document;
+ const tableFragment = this.editor.plugins.has("TableSelection")
+ ? this.editor.plugins.get("TableSelection").getSelectionAsFragment()
+ : null;
+
+ return this.editor.data.toView(
+ tableFragment ?? model.getSelectedContent(model.document.selection),
+ { isClipboardPipeline: true }
+ );
+ }
- // Downcast through the clipboard pipeline so editor-only list bookkeeping
- // (data-list-item-id) is skipped, matching what a native copy produces.
- const content = this.editor.data.toView(model.getSelectedContent(document.selection), {
- isClipboardPipeline: true
+ /**
+ * Runs `html` (or `text` when `html` is empty) through the clipboard paste pipeline, as a
+ * paste at the current selection. Pasting a table into a multi-cell table selection merges
+ * it the way a native paste does.
+ */
+ pasteContent(html: string, text: string) {
+ const content = html || (text ? plainTextToHtml(text) : "");
+ if (!content) {
+ return;
+ }
+
+ const view = this.editor.editing.view;
+ view.focus();
+ view.document.fire("clipboardInput", {
+ dataTransfer: new ViewDataTransfer(new DataTransfer()),
+ content,
+ method: "paste",
+ targetRanges: null
});
-
- return this.htmlDataProcessor.toData(content);
}
async removeSelection() {
diff --git a/packages/trilium-core/src/routes/api/others.spec.ts b/packages/trilium-core/src/routes/api/others.spec.ts
index 5dab96983a..b5059c2676 100644
--- a/packages/trilium-core/src/routes/api/others.spec.ts
+++ b/packages/trilium-core/src/routes/api/others.spec.ts
@@ -102,5 +102,28 @@ describe("Others API (core)", () => {
});
expect(res.status).toBe(400);
});
+
+ it("renders a headerless table as markdown under emptyHeader mode", async () => {
+ const htmlContent = "<table><tbody><tr><td>a</td><td>b</td></tr></tbody></table>";
+
+ const res = await api.post<{ markdownContent: string }>("/api/other/to-markdown", {
+ body: { htmlContent, headerlessTables: "emptyHeader" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.markdownContent).toBe("| | |\n| --- | --- |\n| a | b |");
+
+ // Without the flag the same table stays raw HTML, for a faithful reimport.
+ const plain = await api.post<{ markdownContent: string }>("/api/other/to-markdown", {
+ body: { htmlContent }
+ });
+ expect(plain.body.markdownContent).toContain("<table>");
+ });
+
+ it("400s on an unknown headerlessTables value", async () => {
+ const res = await api.post("/api/other/to-markdown", {
+ body: { htmlContent: "<p>x</p>", headerlessTables: "bogus" }
+ });
+ expect(res.status).toBe(400);
+ });
});
});
diff --git a/packages/trilium-core/src/routes/api/others.ts b/packages/trilium-core/src/routes/api/others.ts
index 70cc685070..9f252010fb 100644
--- a/packages/trilium-core/src/routes/api/others.ts
+++ b/packages/trilium-core/src/routes/api/others.ts
@@ -18,12 +18,16 @@ function renderMarkdown(req: Request) {
}
function toMarkdown(req: Request) {
- const { htmlContent } = req.body;
+ const { htmlContent, headerlessTables } = req.body;
if (typeof htmlContent !== 'string') {
throw new ValidationError('htmlContent parameter is required and must be a string');
}
+ if (headerlessTables !== undefined && headerlessTables !== "keepHtml"
+ && headerlessTables !== "emptyHeader") {
+ throw new ValidationError('headerlessTables must be "keepHtml" or "emptyHeader"');
+ }
return {
- markdownContent: markdown.toMarkdown(htmlContent)
+ markdownContent: markdown.toMarkdown(htmlContent, { headerlessTables })
} satisfies ToMarkdownResponse;
}
diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.ts
index 9ed2bd135a..75c7523b84 100644
--- a/packages/trilium-core/src/services/export/markdown.spec.ts
+++ b/packages/trilium-core/src/services/export/markdown.spec.ts
@@ -663,6 +663,36 @@ describe("Markdown export", () => {
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
+ // The clipboard's "copy as markdown" never reimports, so it accepts the phantom header the
+ // note export refuses: a copied subset of body cells still comes out as a markdown table.
+ it("renders a headerless table under a blank header with headerlessTables: emptyHeader", () => {
+ const html = trimIndentation/*html*/`\
+ <figure class="table">
+ <table>
+ <tbody>
+ <tr><td>a1</td><td>b1</td></tr>
+ <tr><td>a2</td><td>b2</td></tr>
+ </tbody>
+ </table>
+ </figure>
+ `;
+ const expected = "| | |\n| --- | --- |\n| a1 | b1 |\n| a2 | b2 |";
+
+ expect(markdownExportService.toMarkdown(html, { headerlessTables: "emptyHeader" }))
+ .toBe(expected);
+ // The mode is per call, not sticky converter state.
+ expect(markdownExportService.toMarkdown(html)).toContain("<table>");
+ });
+
+ it("keeps a real heading row as the header under headerlessTables: emptyHeader", () => {
+ const html = "<table><thead><tr><th>h1</th><th>h2</th></tr></thead>"
+ + "<tbody><tr><td>a1</td><td>b1</td></tr></tbody></table>";
+ const expected = "| h1 | h2 |\n| --- | --- |\n| a1 | b1 |";
+
+ expect(markdownExportService.toMarkdown(html, { headerlessTables: "emptyHeader" }))
+ .toBe(expected);
+ });
+
// Admonitions are block content, and GFM table cells can only hold inline
// content. Flattening the admonition into a cell produces unrenderable
// `> [!NOTE]<br>...` noise, so a table containing one is kept as raw HTML to
diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.ts
index b74e29dedb..336628f46c 100644
--- a/packages/trilium-core/src/services/export/markdown.ts
+++ b/packages/trilium-core/src/services/export/markdown.ts
@@ -8,11 +8,23 @@ import Turnish, { type Rule } from "turnish";
import { getTaskStates } from "../task_states.js";
-let instance: Turnish | null = null;
+/** One converter per headerless-table mode, built lazily and reused across invocations. */
+const instances = new Map<HeaderlessTableMode, Turnish>();
/** Task states for the current `toMarkdown` invocation, consulted by the list-item filter. */
let currentTaskStates: TaskStateDef[] = [];
+/**
+ * How a table without a heading row renders: kept as raw HTML so notes round-trip ("keepHtml",
+ * the default), or under a synthesized blank header ("emptyHeader") for output that never
+ * reimports, such as the clipboard.
+ */
+export type HeaderlessTableMode = "keepHtml" | "emptyHeader";
+
+export interface ToMarkdownOptions {
+ headerlessTables?: HeaderlessTableMode;
+}
+
export { ADMONITION_TYPE_MAPPINGS };
export const DEFAULT_ADMONITION_TYPE = ADMONITION_TYPE_MAPPINGS.note;
@@ -36,15 +48,18 @@ const fencedCodeBlockFilter: Rule = {
}
};
-function toMarkdown(content: string) {
+function toMarkdown(content: string, options: ToMarkdownOptions = {}) {
currentTaskStates = getTaskStates();
- if (instance === null) {
+ const headerlessTables = options.headerlessTables ?? "keepHtml";
+ let instance = instances.get(headerlessTables);
+ if (instance === undefined) {
instance = new Turnish({
headingStyle: "atx",
bulletListMarker: "*",
emDelimiter: "_",
codeBlockStyle: "fenced",
+ headerlessTables,
blankReplacement(_content, node) {
if (node.nodeName === "SECTION" && node.classList.contains("include-note")) {
return node.outerHTML;
@@ -76,6 +91,7 @@ function toMarkdown(content: string) {
instance.addRule("li", buildListItemFilter());
instance.use(gfm);
instance.keep([ "kbd", "sup", "sub" ]);
+ instances.set(headerlessTables, instance);
}
return instance.render(injectIconFallbacks(injectLinkPreviewFallbacks(content)));
diff --git a/packages/turndown-plugin-gfm/src/lib/tables.ts b/packages/turndown-plugin-gfm/src/lib/tables.ts
index ad569dd044..8bdde5d3ea 100644
--- a/packages/turndown-plugin-gfm/src/lib/tables.ts
+++ b/packages/turndown-plugin-gfm/src/lib/tables.ts
@@ -9,7 +9,6 @@ var rules: Record<string, Rule> = {}
var alignMap: Record<string, string> = { left: ':---', right: '---:', center: ':---:' };
let isCodeBlock_: ((node: Node) => boolean) | null = null;
-let options_: TurnishOptions | null = null;
// We need to cache the result of tableShouldBeSkipped() as it is expensive.
// Caching it means we went from about 9000 ms for rendering down to 90 ms.
@@ -82,10 +81,12 @@ rules.table = {
return node.nodeName === 'TABLE';
},
- replacement: function (content: string, node) {
+ // The per-call `options` parameter, not a module-level copy: several Turnish instances with
+ // different options share this rules object.
+ replacement: function (content: string, node, options: TurnishOptions) {
// Only convert tables that can result in valid Markdown
// Other tables are kept as HTML using `keep` (see below).
- if (tableShouldBeHtml(node, options_)) {
+ if (tableShouldBeHtml(node, options)) {
return prettyPrintTable(node);
} else {
if (tableShouldBeSkipped(node)) return content;
@@ -93,13 +94,14 @@ rules.table = {
// Ensure there are no blank lines
content = content.replace(/\n+/g, '\n')
- // A table reaching this branch always has a real heading row (otherwise
- // `tableShouldBeHtml` would have kept it as HTML), so the rendered content
- // already starts with a header + divider and no synthetic header is needed.
+ // A headerless table reaches this branch only under `headerlessTables:
+ // "emptyHeader"` (otherwise `tableShouldBeHtml` keeps it as HTML), and GFM
+ // requires a header, so a blank one is synthesized above the content.
+ const header = tableHasHeadingRow(node) ? '' : `${emptyHeader(node)}\n`;
const captionContent = node.caption ? node.caption.textContent || '' : '';
const caption = captionContent ? `${captionContent}\n\n` : '';
const tableContent = content.trimStart();
- return `\n\n${caption}${tableContent}\n\n`;
+ return `\n\n${caption}${header}${tableContent}\n\n`;
}
}
}
@@ -222,7 +224,23 @@ const tableShouldBeHtml = (tableNode: any, options: TurnishOptions | null): bool
// a phantom empty header, which reimports as a spurious blank row. Keep such
// tables as raw HTML instead so they round-trip faithfully. Skippable tables
// (e.g. a single cell) are rendered as paragraphs and are left untouched.
- (!tableShouldBeSkipped(tableNode) && !tableHasHeadingRow(tableNode));
+ // `headerlessTables: "emptyHeader"` accepts the phantom header instead, for
+ // output that never reimports, such as the clipboard.
+ (!tableShouldBeSkipped(tableNode) && !tableHasHeadingRow(tableNode) &&
+ options?.headerlessTables !== 'emptyHeader');
+}
+
+// A blank header row plus its divider line, sized and aligned per column, for a
+// headerless table rendered under `headerlessTables: "emptyHeader"`.
+function emptyHeader(node: HTMLTableElement): string {
+ const colCount = tableColCount(node);
+ let headerCells = '';
+ let borderCells = '';
+ for (let i = 0; i < colCount; i++) {
+ headerCells += cell('', null, i);
+ borderCells += cell(getBorder(getColumnAlignment(node, i)), null, i);
+ }
+ return `${headerCells}\n${borderCells}`;
}
// A table has a heading row when its first row qualifies as a heading row (its
@@ -307,7 +325,6 @@ function prettyPrintTable(node: Element): string {
export default function tables (turndownService: Turnish) {
isCodeBlock_ = (turndownService as any).isCodeBlock ?? null;
- options_ = turndownService.options;
turndownService.keep(function (node) {
if (node.nodeName === 'TABLE' && tableShouldBeHtml(node, turndownService.options)) return true;