Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: add support to insert rows from clipboard

Adorian Doran5967f7eadce0
diff --git a/apps/client/src/menus/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.ts
index ce519ec6a8..5555300a60 100644
--- a/apps/client/src/menus/electron_context_menu.ts
+++ b/apps/client/src/menus/electron_context_menu.ts
@@ -60,7 +60,14 @@ function electronHost(eApi: ElectronApi, params: ElectronContextMenuParams): Con
paste: {
enabled: editFlags.canPaste,
run: () => api.webContentsAction("paste"),
- runAsPlainText: () => api.webContentsAction("pasteAndMatchStyle")
+ runAsPlainText: () => api.webContentsAction("pasteAndMatchStyle"),
+ read: async () => {
+ const [html, text] = await Promise.all([
+ eApi.clipboard.readHTML(),
+ eApi.clipboard.readText()
+ ]);
+ return { html, text };
+ }
},
canCut: editFlags.canCut,
cut: () => api.webContentsAction("cut"),
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.ts
index 7ee3da3586..dc516e5145 100644
--- a/apps/client/src/menus/note_context_menu.spec.ts
+++ b/apps/client/src/menus/note_context_menu.spec.ts
@@ -172,7 +172,7 @@ describe("buildNoteContextMenuItems", () => {
const addToDictionary = vi.fn();
const items = await build({ isEditable: true }, browserLikeHost({
spelling: { misspelledWord: "teh", suggestions: [ "the", "ten" ], addToDictionary },
- paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn() }
+ paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn(), read: vi.fn() }
}));
expect(titles(items).slice(0, 4)).toEqual([
@@ -224,15 +224,16 @@ describe("buildNoteContextMenuItems", () => {
main: [ { title: "T1" }, { kind: "separator" }, { title: "T2" } ],
sort: { title: "S" },
delete: [ { title: "D1" }, { title: "D2" } ],
- select: { title: "SEL" }
+ select: { title: "SEL" },
+ pasteRows: [ { title: "PR1" }, { title: "PR2" } ]
} as TableMenuSections);
const host = browserLikeHost({
- paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn() }
+ paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn(), read: vi.fn() }
});
const items = await build({ isEditable: true, element: cell }, host);
- expect(buildTableContextMenuSections).toHaveBeenCalledWith(cell);
+ expect(buildTableContextMenuSections).toHaveBeenCalledWith(cell, host.paste);
expect(titles(items)).toEqual([
"T1",
"---",
@@ -243,6 +244,8 @@ describe("buildNoteContextMenuItems", () => {
"electron_context_menu.copy-as-markdown",
"electron_context_menu.paste",
"electron_context_menu.paste-as-plain-text",
+ "PR1",
+ "PR2",
"---",
"S",
"---",
@@ -282,7 +285,8 @@ describe("buildNoteContextMenuItems", () => {
main: [ { title: "T1" } ],
sort: { title: "S" },
delete: [],
- select: { title: "SEL" }
+ select: { title: "SEL" },
+ pasteRows: []
} as TableMenuSections);
// No cell selection and no text: the rows show but stay disabled.
@@ -307,7 +311,8 @@ describe("buildNoteContextMenuItems", () => {
main: [ { title: "T1" } ],
sort: { title: "S" },
delete: [],
- select: { title: "SEL" }
+ select: { title: "SEL" },
+ pasteRows: []
} as TableMenuSections);
vi.mocked(hasTableCellSelection).mockResolvedValueOnce(true);
@@ -399,7 +404,8 @@ describe("setupContextMenu (browser)", () => {
main: [ { title: "table_context_menu.merge_cells" } ],
sort: { title: "S" },
delete: [],
- select: { title: "SEL" }
+ select: { title: "SEL" },
+ pasteRows: []
} as TableMenuSections);
const event = rightClick(cell);
@@ -408,7 +414,33 @@ describe("setupContextMenu (browser)", () => {
await vi.waitFor(() => expect(contextMenu.show).toHaveBeenCalled());
const shown = vi.mocked(contextMenu.show).mock.calls[0][0];
expect(titles(shown.items)).toContain("table_context_menu.merge_cells");
- expect(buildTableContextMenuSections).toHaveBeenCalledWith(cell);
+ expect(vi.mocked(buildTableContextMenuSections).mock.calls[0]?.[0]).toBe(cell);
+ });
+
+ it("hands the table section the page's clipboard reader", async () => {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: {
+ read: vi.fn(async () => [ {
+ types: [ "text/html", "text/plain" ],
+ getType: async (type: string) => ({
+ text: async () => type === "text/html" ? "<table></table>" : "t"
+ })
+ } ])
+ }
+ });
+
+ try {
+ setSelection(null, "", "");
+ rightClick(editableTableCell());
+ await vi.waitFor(() => expect(buildTableContextMenuSections).toHaveBeenCalled());
+
+ const [ , clipboard ] = vi.mocked(buildTableContextMenuSections).mock.calls[0];
+ expect(clipboard?.enabled).toBe(true);
+ expect(await clipboard?.read()).toEqual({ html: "<table></table>", text: "t" });
+ } finally {
+ delete (navigator as { clipboard?: unknown }).clipboard;
+ }
});
it("leaves a table cell to the browser when read-only, non-editable, or Shift is held", async () => {
diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.ts
index f02528ef94..e8cff7ff95 100644
--- a/apps/client/src/menus/note_context_menu.ts
+++ b/apps/client/src/menus/note_context_menu.ts
@@ -41,6 +41,8 @@ export interface ContextMenuHost {
enabled: boolean;
run(): void;
runAsPlainText(): void;
+ /** Reads the clipboard, for the rows that paste through an editor command. */
+ read(): Promise<{ html: string; text: string }>;
};
canCut: boolean;
cut(): void | Promise<void>;
@@ -125,7 +127,7 @@ export async function buildNoteContextMenuItems(
// lands somewhere a completion could not be committed anyway (a read-only note, the tree).
const aiActions = target.isEditable ? await buildAiActionsMenuItem() : null;
const tableSections = target.isEditable
- ? await buildTableContextMenuSections(target.element)
+ ? await buildTableContextMenuSections(target.element, host.paste)
: null;
// Read after the table sections are built, which moves the selection into the clicked cell.
@@ -222,6 +224,10 @@ export async function buildNoteContextMenuItems(
uiIcon: "bx bx-paste",
handler: runAsPlainText
});
+
+ if (tableSections) {
+ items.push(...tableSections.pasteRows);
+ }
}
if (tableSections) {
@@ -377,7 +383,8 @@ function browserPaste(
// 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)
+ runAsPlainText: () => void pasteFromClipboard(editor, element, true),
+ read: readClipboard
};
}
diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.ts
index 9bdf8bdd9c..34e6cc357d 100644
--- a/apps/client/src/menus/table_context_menu.spec.ts
+++ b/apps/client/src/menus/table_context_menu.spec.ts
@@ -55,6 +55,7 @@ describe("buildTableMenuSections", () => {
expect(syncSelectionToDomTarget).toHaveBeenCalledWith(element);
expect(titles(sections?.main ?? [])).toEqual(MAIN_TITLES);
+ expect(sections?.pasteRows).toEqual([]);
expect(titles(sections?.delete ?? [])).toEqual(DELETE_TITLES);
expect(titles(sections ? [sections.sort] : [])).toEqual(["table_context_menu.sort"]);
expect(titles(sortSubmenu(sections))).toEqual(SORT_TITLES);
@@ -230,6 +231,71 @@ describe("buildTableMenuSections", () => {
});
});
+describe("paste rows", () => {
+ const TITLES = ["table_context_menu.paste_rows_above", "table_context_menu.paste_rows_below"];
+
+ it("shows the items only for a single-row selection and a readable clipboard", () => {
+ const pasteRows = (disabled: string[], clipboard?: ReturnType<typeof clipboardAccess>) => {
+ const { editor } = stubEditor(disabled);
+ return buildTableMenuSections(editor, cellElement(), clipboard)?.pasteRows ?? [];
+ };
+
+ expect(pasteRows([])).toEqual([]);
+ expect(pasteRows(["triliumPasteTableRowsAbove"], clipboardAccess())).toEqual([]);
+
+ const shown = pasteRows([], clipboardAccess());
+ expect(titles(shown)).toEqual(TITLES);
+ expect(shown.map((item) => (item as MenuCommandItem<any>).uiIcon)).toEqual([
+ "bx bx-horizontal-left bx-rotate-90",
+ "bx bx-horizontal-left bx-rotate-270"
+ ]);
+ expect(shown.map((item) => (item as MenuCommandItem<any>).enabled)).toEqual([true, true]);
+
+ const unavailable = pasteRows([], clipboardAccess(false));
+ expect(unavailable.map((item) => (item as MenuCommandItem<any>).enabled))
+ .toEqual([false, false]);
+ });
+
+ it("reads the clipboard and pastes it as rows at the selection pinned beforehand", async () => {
+ const { editor, execute, capturePasteTarget, pasteTarget } = stubEditor();
+ const clipboard = clipboardAccess();
+ const items = buildTableMenuSections(editor, cellElement(), clipboard)?.pasteRows ?? [];
+
+ run(items, TITLES[1]);
+ await vi.waitFor(() => expect(pasteTarget.release).toHaveBeenCalled());
+
+ expect(capturePasteTarget.mock.invocationCallOrder[0])
+ .toBeLessThan(clipboard.read.mock.invocationCallOrder[0]);
+ expect(pasteTarget.restore).toHaveBeenCalled();
+ expect(execute).toHaveBeenCalledWith("triliumPasteTableRowsBelow",
+ { html: "<table></table>", text: "t" });
+ });
+
+ it("drops the paste when the pinned selection is gone or the read fails", async () => {
+ const gone = stubEditor([], { restoreResult: false });
+ run(buildTableMenuSections(gone.editor, cellElement(), clipboardAccess())?.pasteRows ?? [],
+ TITLES[0]);
+ await vi.waitFor(() => expect(gone.pasteTarget.release).toHaveBeenCalled());
+ expect(gone.execute).not.toHaveBeenCalled();
+
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const failing = stubEditor();
+ const clipboard = clipboardAccess();
+ clipboard.read.mockRejectedValueOnce(new Error("denied"));
+ run(buildTableMenuSections(failing.editor, cellElement(), clipboard)?.pasteRows ?? [],
+ TITLES[0]);
+ await vi.waitFor(() => expect(failing.pasteTarget.release).toHaveBeenCalled());
+
+ expect(failing.pasteTarget.restore).not.toHaveBeenCalled();
+ expect(failing.execute).not.toHaveBeenCalled();
+ expect(warn).toHaveBeenCalled();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
describe("buildTableContextMenuSections", () => {
const resolveEditor = vi.mocked(getTextEditorContaining);
@@ -248,11 +314,15 @@ describe("buildTableContextMenuSections", () => {
resolveEditor.mockResolvedValue(editor);
const element = cellElement();
- const sections = await buildTableContextMenuSections(element);
+ const sections = await buildTableContextMenuSections(element, clipboardAccess());
expect(resolveEditor).toHaveBeenCalledWith(element);
expect(titles(sections?.main ?? [])).toEqual(MAIN_TITLES);
expect(titles(sections?.delete ?? [])).toEqual(DELETE_TITLES);
+ expect(titles(sections?.pasteRows ?? [])).toEqual([
+ "table_context_menu.paste_rows_above",
+ "table_context_menu.paste_rows_below"
+ ]);
});
it("returns null when no text editor contains the target", async () => {
@@ -301,15 +371,26 @@ describe("hasTableCellSelection", () => {
/**
* A minimal editor double: `TableContextMenu` is present unless `hasPlugin` says otherwise, every
* command is enabled except the ones in `disabledCommands`, and only the ones in
- * `checkedCommands` have a `true` value.
+ * `checkedCommands` have a `true` value. Its paste target restores the selection unless
+ * `restoreResult` is `false`.
*/
function stubEditor(
disabledCommands: string[] = [],
- { hasPlugin = true, syncResult = true, checkedCommands = [] as string[] } = {}
+ {
+ hasPlugin = true,
+ syncResult = true,
+ checkedCommands = [] as string[],
+ restoreResult = true
+ } = {}
) {
const executed: string[] = [];
const focus = vi.fn();
const syncSelectionToDomTarget = vi.fn(() => syncResult);
+ const pasteTarget = { restore: vi.fn(() => restoreResult), release: vi.fn() };
+ const capturePasteTarget = vi.fn(() => pasteTarget);
+ const execute = vi.fn((name: string, ..._args: unknown[]) => {
+ executed.push(name);
+ });
const editor = {
plugins: {
has: (name: string) => hasPlugin && name === "TableContextMenu",
@@ -321,13 +402,28 @@ function stubEditor(
value: checkedCommands.includes(name)
})
},
- execute: (name: string) => {
- executed.push(name);
- },
+ execute,
+ capturePasteTarget,
editing: { view: { focus } }
};
- return { editor: editor as unknown as CKTextEditor, executed, focus, syncSelectionToDomTarget };
+ return {
+ editor: editor as unknown as CKTextEditor,
+ executed,
+ execute,
+ focus,
+ capturePasteTarget,
+ pasteTarget,
+ syncSelectionToDomTarget
+ };
+}
+
+/** A host's clipboard access, whose `read()` resolves with a one-cell table. */
+function clipboardAccess(enabled = true) {
+ return {
+ enabled,
+ read: vi.fn(() => Promise.resolve({ html: "<table></table>", text: "t" }))
+ };
}
/** A node nested inside a detached `<td>`, standing in for the right-click target. */
diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.ts
index 82a0625d17..98b0cf2ea8 100644
--- a/apps/client/src/menus/table_context_menu.ts
+++ b/apps/client/src/menus/table_context_menu.ts
@@ -6,19 +6,21 @@ import type { MenuItem } from "./context_menu.js";
import { getTextEditorContaining } from "./text_editor_context_menu.js";
/**
- * The table sections of the text editor's right-click menu.
+ * The table sections of the text editor's right-click menu. `clipboard` is the host's clipboard
+ * access, which the paste rows items need.
*
* Returns `null` when the click is not on a table cell of the active text editor.
*/
export async function buildTableContextMenuSections(
- element: Element | null | undefined
+ element: Element | null | undefined,
+ clipboard?: ClipboardAccess
): Promise<TableMenuSections | null> {
if (!element?.closest("td, th")) {
return null;
}
const editor = await getTextEditorContaining(element);
- return editor && buildTableMenuSections(editor, element);
+ return editor && buildTableMenuSections(editor, element, clipboard);
}
/**
@@ -28,7 +30,8 @@ export async function buildTableContextMenuSections(
*/
export function buildTableMenuSections(
editor: CKTextEditor,
- element: Element
+ element: Element,
+ clipboard?: ClipboardAccess
): TableMenuSections | null {
if (!editor.plugins.has("TableContextMenu")
|| !editor.plugins.get("TableContextMenu").syncSelectionToDomTarget(element)) {
@@ -119,11 +122,20 @@ export function buildTableMenuSections(
uiIcon: "bx bx-select-multiple",
enabled: selectItems.some((item) => item.enabled),
items: selectItems
- }
+ },
+ pasteRows: buildPasteRowsItems(editor, clipboard)
};
}
-/** The table rows of the text editor's right-click menu, in four sections. */
+/** The part of the menu host's paste support that the paste rows items use. */
+export interface ClipboardAccess {
+ /** Whether the clipboard holds anything to paste. */
+ enabled: boolean;
+ /** Reads the HTML and plain-text flavors of the clipboard, empty when absent. */
+ read(): Promise<{ html: string; text: string }>;
+}
+
+/** The table rows of the text editor's right-click menu, in five sections. */
export interface TableMenuSections {
/**
* Row and column insertion sized by the selection, the header rows, merging or splitting of
@@ -136,6 +148,12 @@ export interface TableMenuSections {
delete: MenuItem<CommandNames>[];
/** Selection of the spanned rows or columns, or of the whole table. Shown below deletion. */
select: MenuItem<CommandNames>;
+ /**
+ * Pasting the clipboard as new rows above or below the row of the selection. Shown below the
+ * paste rows of the clipboard section; empty unless the selection is in one row and the host
+ * can read the clipboard.
+ */
+ pasteRows: MenuItem<CommandNames>[];
}
/**
@@ -154,3 +172,50 @@ export async function hasTableCellSelection(element: Element | null | undefined)
return editor.plugins.get("TableSelection").getSelectedTableCells() !== null;
}
+
+/** The paste rows items, for a selection in a single row and a host that reads the clipboard. */
+function buildPasteRowsItems(
+ editor: CKTextEditor,
+ clipboard: ClipboardAccess | undefined
+): MenuItem<CommandNames>[] {
+ if (!clipboard || editor.commands.get("triliumPasteTableRowsAbove")?.isEnabled !== true) {
+ return [];
+ }
+
+ const item = (title: string, uiIcon: string, commandName: PasteRowsCommand) => ({
+ title,
+ uiIcon,
+ enabled: clipboard.enabled,
+ handler: () => void pasteRows(editor, clipboard, commandName)
+ });
+ return [
+ item(t("table_context_menu.paste_rows_above"), "bx bx-horizontal-left bx-rotate-90",
+ "triliumPasteTableRowsAbove"),
+ item(t("table_context_menu.paste_rows_below"), "bx bx-horizontal-left bx-rotate-270",
+ "triliumPasteTableRowsBelow")
+ ];
+}
+
+type PasteRowsCommand = "triliumPasteTableRowsAbove" | "triliumPasteTableRowsBelow";
+
+/**
+ * Reads the clipboard and pastes it as rows next to the selection the menu was opened on. The
+ * selection is pinned before the read, which can wait on a permission prompt.
+ */
+async function pasteRows(
+ editor: CKTextEditor,
+ clipboard: ClipboardAccess,
+ commandName: PasteRowsCommand
+) {
+ const target = editor.capturePasteTarget();
+ try {
+ const { html, text } = await clipboard.read();
+ if (target.restore()) {
+ editor.execute(commandName, { html, text });
+ }
+ } catch (error) {
+ console.warn("Failed to paste rows from the clipboard:", error);
+ } finally {
+ target.release();
+ }
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index cc20f79b60..dd41f51d6f 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3524,7 +3524,9 @@
"select_column": "Column",
"select_table": "Table",
"set_header_row": "Set as header",
- "set_header_up_to_row": "Set header up to this row"
+ "set_header_up_to_row": "Set header up to this row",
+ "paste_rows_above": "Paste rows above",
+ "paste_rows_below": "Paste rows below"
},
"board_view": {
"delete-note": "Delete note...",
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index 0ef7b77092..bc4ab19c69 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -279,6 +279,11 @@ describe("preload script", () => {
await clip().readText();
expect(ipcRendererInvoked).toContainEqual({ channel: "read-clipboard-text", args: [] });
});
+
+ it("readHTML invokes correct IPC channel", async () => {
+ await clip().readHTML();
+ expect(ipcRendererInvoked).toContainEqual({ channel: "read-clipboard-html", args: [] });
+ });
});
describe("shell", () => {
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 8dac0decaa..64d2bfcc7b 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -121,6 +121,9 @@ contextBridge.exposeInMainWorld("electronApi", {
},
readText() {
return ipcRenderer.invoke("read-clipboard-text");
+ },
+ readHTML() {
+ return ipcRenderer.invoke("read-clipboard-html");
}
},
diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.ts
index b93f2850a0..0e92442205 100644
--- a/apps/desktop/src/services/window.spec.ts
+++ b/apps/desktop/src/services/window.spec.ts
@@ -167,6 +167,14 @@ const fakeNativeImage = {
class FakeClipboardItem {
constructor(readonly items: Record<string, unknown>) {}
+
+ get types() {
+ return Object.keys(this.items);
+ }
+
+ getType(type: string) {
+ return Promise.resolve(this.items[type]);
+ }
}
const fakeApp = {
@@ -183,7 +191,11 @@ const electronSurface = {
shell: fakeShell,
globalShortcut: fakeGlobalShortcut,
nativeImage: fakeNativeImage,
- clipboard: { write: vi.fn((_items: FakeClipboardItem[]) => Promise.resolve()), readText: vi.fn(() => Promise.resolve("")) },
+ clipboard: {
+ write: vi.fn((_items: FakeClipboardItem[]) => Promise.resolve()),
+ readText: vi.fn(() => Promise.resolve("")),
+ read: vi.fn((): Promise<FakeClipboardItem[]> => Promise.resolve([]))
+ },
ClipboardItem: FakeClipboardItem,
nativeTheme: { themeSource: "system" },
BrowserWindow: fakeBrowserWindowClass,
@@ -887,6 +899,21 @@ describe("window service", () => {
expect(state.log.error).toHaveBeenCalledWith(expect.stringContaining("failed"));
});
+ it("read-clipboard-text and read-clipboard-html return the clipboard flavors", async () => {
+ const html = new Blob(["<b>html</b>"], { type: "text/html" });
+ const text = new Blob(["text"], { type: "text/plain" });
+ electronSurface.clipboard.readText.mockReturnValueOnce(Promise.resolve("text"));
+ electronSurface.clipboard.read
+ .mockResolvedValueOnce([
+ new FakeClipboardItem({ "text/plain": text, "text/html": html })
+ ])
+ .mockResolvedValueOnce([new FakeClipboardItem({ "text/plain": text })]);
+
+ expect(await fireHandle("read-clipboard-text", makeEvent())).toBe("text");
+ expect(await fireHandle("read-clipboard-html", makeEvent())).toBe("<b>html</b>");
+ expect(await fireHandle("read-clipboard-html", makeEvent())).toBe("");
+ });
+
it("show-window shows the resolved window (and tolerates null)", () => {
const win = state.windows[state.windows.length - 1];
fireOn("show-window", makeEvent());
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index 98016bd717..706e278cce 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -556,6 +556,15 @@ export function setupWindowing() {
});
electron.ipcMain.handle("read-clipboard-text", () => electron.clipboard.readText());
+ electron.ipcMain.handle("read-clipboard-html", async () => {
+ for (const item of await electron.clipboard.read()) {
+ if (item.types.includes("text/html")) {
+ const html = await item.getType("text/html");
+ return html instanceof Blob ? html.text() : "";
+ }
+ }
+ return "";
+ });
electron.ipcMain.on("show-window", (event) => {
const window = electron.BrowserWindow.fromWebContents(event.sender);
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 68f3c456b6..bb2c076c47 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
@@ -69,6 +69,21 @@ src="3_Tables_image.png" width="384" height="100">
header row is emitted, since Markdown tables require one.</li>
</ul>
</li>
+ <li>Since v0.107.0, <em>Paste rows above</em> and <em>Paste rows below</em>,
+ after <em>Paste as plain text</em>, paste the clipboard as new rows next
+ to the row of the current cell, instead of over the cells from the cursor
+ on. They show only when the selection is in a single row, and, like <em>Paste</em>,
+ only where the clipboard can be read:
+ <ul>
+ <li>A copied table becomes one new row for each of its rows, filled from the
+ first column. When it has more columns than the table, the table gains
+ columns, as with a regular paste. Other content goes in the first cell
+ of a single new row.</li>
+ <li>The new rows are selected afterwards.</li>
+ <li>When merged cells join the row to others, the new rows go above or below
+ that whole block of rows.</li>
+ </ul>
+ </li>
<li><em>Sort</em>, below the clipboard section, sorts the rows by the column
of the current cell, in <em>Ascending</em> or <em>Descending</em> order. See <a
href="#sorting-rows">Sorting rows</a>.</li>
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 f9407a9e6b..b5759ea937 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md
@@ -36,6 +36,10 @@ Since v0.106.0, right-clicking anywhere inside a table opens a context menu with
* _Cut_, _Copy_ and _Copy as Markdown_ 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.
+* Since v0.107.0, _Paste rows above_ and _Paste rows below_, after _Paste as plain text_, paste the clipboard as new rows next to the row of the current cell, instead of over the cells from the cursor on. They show only when the selection is in a single row, and, like _Paste_, only where the clipboard can be read:
+ * A copied table becomes one new row for each of its rows, filled from the first column. When it has more columns than the table, the table gains columns, as with a regular paste. Other content goes in the first cell of a single new row.
+ * The new rows are selected afterwards.
+ * When merged cells join the row to others, the new rows go above or below that whole block of rows.
* _Sort_, below the clipboard section, sorts the rows by the column of the current cell, in _Ascending_ or _Descending_ order. See [Sorting rows](#sorting-rows).
* _Delete row_ and _Delete column_, below _Sort_, remove every row or column the selection touches, even when only some of their cells are selected.
* _Delete table_ removes the whole table and leaves an empty paragraph in its place. In a table nested inside another, only the inner table is removed.
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index ecf2b46035..836ccb0b2f 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -28,6 +28,7 @@ export * from "./utils.js";
import "./plugins/math/math.js";
import "./plugins/mermaid/mermaid.js";
import "./plugins/table_context_menu.js";
+import "./plugins/table_paste_rows.js";
window[Symbol.for("cke distribution")] = "trilium";
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index f09ad8a614..b30c5420b1 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -59,6 +59,7 @@ import CollapsibleListItems from "./plugins/collapsible_list_items.js";
import TableIndent from "./plugins/table_indent.js";
import TableContextMenu from "./plugins/table_context_menu.js";
import TableMove from "./plugins/table_move/table_move.js";
+import TablePasteRows from "./plugins/table_paste_rows.js";
import TableSort from "./plugins/table_sort.js";
import TableInsertUI from "./plugins/table_insert/table_insert_ui.js";
import TableToolbarDropdowns from "./plugins/table_toolbar_dropdowns.js";
@@ -100,6 +101,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
TableIndent,
TableContextMenu,
TableMove,
+ TablePasteRows,
TableSort,
TableInsertUI,
TableToolbarDropdowns,
diff --git a/packages/ckeditor5/src/plugins/cuttonote.spec.ts b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
index addf5e2fd7..c56475ca36 100644
--- a/packages/ckeditor5/src/plugins/cuttonote.spec.ts
+++ b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
@@ -1,4 +1,13 @@
-import { _setModelData as setModelData, ClassicEditor, Essentials, List, Paragraph, Table, TableSelection } from "ckeditor5";
+import {
+ _getModelData as getModelData,
+ _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";
@@ -109,6 +118,21 @@ describe("CutToNotePlugin", () => {
expect(editor.getData()).toBe("<p>aXb</p><p>cd</p>");
});
+ it("restores the captured selection, or reports that its content is gone", () => {
+ setModelData(editor.model, "<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");
+ const target = editor.capturePasteTarget();
+ moveCaret(editor, 1, 1);
+
+ expect(target.restore()).toBe(true);
+ expect(getModelData(editor.model))
+ .toBe("<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");
+
+ const gone = editor.capturePasteTarget();
+ editor.setData("<p>other</p>");
+ expect(gone.restore()).toBe(false);
+ expect(getModelData(editor.model)).toBe("<paragraph>[]other</paragraph>");
+ });
+
it("discards the paste when the captured content was removed", () => {
setModelData(editor.model, "<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");
const target = editor.capturePasteTarget();
diff --git a/packages/ckeditor5/src/plugins/cuttonote.ts b/packages/ckeditor5/src/plugins/cuttonote.ts
index cc3370e47f..0109e0f894 100644
--- a/packages/ckeditor5/src/plugins/cuttonote.ts
+++ b/packages/ckeditor5/src/plugins/cuttonote.ts
@@ -17,6 +17,12 @@ export interface PasteTarget {
* gone.
*/
paste(html: string, text: string): void;
+ /**
+ * Moves the selection back onto the pinned ranges and releases them, for a paste that runs
+ * through a command instead of `paste()`. Returns `false`, leaving the selection alone, when
+ * the pinned content is gone.
+ */
+ restore(): boolean;
/** Detaches the pinned ranges without pasting. Safe to call more than once. */
release(): void;
}
@@ -126,16 +132,22 @@ export default class CutToNotePlugin extends Plugin {
range.detach();
}
};
+ const restore = () => {
+ const targets = editor.state === "destroyed" ? [] : this.getRemainingRanges(ranges);
+ release();
+ if (targets.length) {
+ this.restoreSelection(targets);
+ }
+ return targets.length > 0;
+ };
return {
paste: (html, text) => {
- const targets = editor.state === "destroyed" ? [] : this.getRemainingRanges(ranges);
- release();
- if (targets.length) {
- this.restoreSelection(targets);
+ if (restore()) {
this.pasteContent(html, text);
}
},
+ restore,
release
};
}
diff --git a/packages/ckeditor5/src/plugins/table_paste_rows.spec.ts b/packages/ckeditor5/src/plugins/table_paste_rows.spec.ts
new file mode 100644
index 0000000000..2a3bed80d6
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_paste_rows.spec.ts
@@ -0,0 +1,136 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ Essentials,
+ Paragraph,
+ Table,
+ TableSelection
+} from "ckeditor5";
+import type { ClassicEditor } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { modelTable, selectCells } from "../../test/table-kit.js";
+import TablePasteRows from "./table_paste_rows.js";
+
+const ABOVE = "triliumPasteTableRowsAbove";
+const BELOW = "triliumPasteTableRowsBelow";
+
+describe("TablePasteRows", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Table, TablePasteRows]);
+ });
+
+ it("is enabled while the selection is in a single row of a table", () => {
+ const isEnabled = () => [ABOVE, BELOW].map((name) => editor.commands.get(name)?.isEnabled);
+
+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");
+ expect(isEnabled()).toEqual([false, false]);
+
+ setModelData(editor.model, modelTable([["1[]1", "12"], ["21", "22"]]));
+ expect(isEnabled()).toEqual([true, true]);
+
+ selectCells(editor, [1, 0], [1, 1]);
+ expect(isEnabled()).toEqual([true, true]);
+
+ selectCells(editor, [0, 0], [1, 0]);
+ expect(isEnabled()).toEqual([false, false]);
+
+ setModelData(editor.model, modelTable([["1[]1"]]));
+ editor.enableReadOnlyMode("spec");
+ expect(isEnabled()).toEqual([false, false]);
+ });
+
+ it("inserts a pasted table as new rows above or below the row, and selects them", () => {
+ const html = htmlTable([["a", "b"], ["c", "d"]]);
+
+ setModelData(editor.model, modelTable([["11", "12"], ["2[]1", "22"], ["31", "32"]]));
+ editor.execute(ABOVE, { html, text: "" });
+ expect(tableData(editor)).toBe(
+ modelTable([["11", "12"], ["a", "b"], ["c", "d"], ["21", "22"], ["31", "32"]]));
+ expect(selectedCellTexts(editor)).toEqual(["a", "b", "c", "d"]);
+
+ setModelData(editor.model, modelTable([["11", "12"], ["2[]1", "22"], ["31", "32"]]));
+ selectCells(editor, [1, 0], [1, 1]);
+ editor.execute(BELOW, { html, text: "" });
+ expect(tableData(editor)).toBe(
+ modelTable([["11", "12"], ["21", "22"], ["a", "b"], ["c", "d"], ["31", "32"]]));
+ expect(selectedCellTexts(editor)).toEqual(["a", "b", "c", "d"]);
+ });
+
+ it("widens the table for a wider paste and leaves the rest of a narrower one empty", () => {
+ setModelData(editor.model, modelTable([["1[]1"], ["21"]]));
+ editor.execute(BELOW, { html: htmlTable([["a", "b", "c"]]), text: "" });
+ expect(tableData(editor))
+ .toBe(modelTable([["11", "", ""], ["a", "b", "c"], ["21", "", ""]]));
+ expect(selectedCellTexts(editor)).toEqual(["a", "b", "c"]);
+
+ setModelData(editor.model, modelTable([["1[]1", "12", "13"]]));
+ editor.execute(ABOVE, { html: htmlTable([["a"]]), text: "" });
+ expect(tableData(editor)).toBe(modelTable([["a", "", ""], ["11", "12", "13"]]));
+ expect(selectedCellTexts(editor)).toEqual(["a", "", ""]);
+ });
+
+ it("puts content other than a table in the first cell of one new row", () => {
+ setModelData(editor.model, modelTable([["1[]1", "12"]]));
+ editor.execute(BELOW, { html: "", text: "plain" });
+
+ expect(tableData(editor)).toBe(modelTable([["11", "12"], ["plain", ""]]));
+ expect(selectedCellTexts(editor)).toEqual(["plain", ""]);
+ });
+
+ it("keeps the new rows out of a block of rows joined by a merged cell", () => {
+ const block = (...rows: string[][]) => modelTable([
+ [{ contents: "a", rowspan: 2 }, "b"],
+ ["c"],
+ ...rows,
+ ["d", "e"]
+ ]);
+ const html = htmlTable([["x", "y"]]);
+
+ setModelData(editor.model, block().replace(">c<", ">c[]<"));
+ editor.execute(ABOVE, { html, text: "" });
+ expect(tableData(editor)).toBe(block().replace("<table>", `<table>${rowMarkup("x", "y")}`));
+
+ setModelData(editor.model, block().replace(">c<", ">c[]<"));
+ editor.execute(BELOW, { html, text: "" });
+ expect(tableData(editor)).toBe(block(["x", "y"]));
+ });
+
+ it("changes nothing for an empty clipboard, and undoes a paste in one step", () => {
+ const table = modelTable([["1[]1", "12"]]);
+
+ setModelData(editor.model, table);
+ editor.execute(ABOVE, { html: "", text: "" });
+ expect(getModelData(editor.model)).toBe(table);
+
+ editor.execute(ABOVE, { html: htmlTable([["a", "b"]]), text: "" });
+ editor.execute("undo");
+ expect(tableData(editor)).toBe(modelTable([["11", "12"]]));
+ });
+});
+
+function htmlTable(rows: string[][]): string {
+ const body = rows
+ .map((cells) => `<tr>${cells.map((cell) => `<td>${cell}</td>`).join("")}</tr>`)
+ .join("");
+ return `<table><tbody>${body}</tbody></table>`;
+}
+
+function rowMarkup(...cells: string[]): string {
+ return modelTable([cells]).replace(/^<table>|<\/table>$/g, "");
+}
+
+function tableData(editor: ClassicEditor): string {
+ return getModelData(editor.model, { withoutSelection: true });
+}
+
+/** The text of every cell in the cell selection, in document order. */
+function selectedCellTexts(editor: ClassicEditor): string[] {
+ const cells = editor.plugins.get(TableSelection).getSelectedTableCells() ?? [];
+ return cells.map((cell) => Array.from(editor.model.createRangeIn(cell).getItems())
+ .map((item) => (item.is("$textProxy") ? item.data : ""))
+ .join(""));
+}
diff --git a/packages/ckeditor5/src/plugins/table_paste_rows.ts b/packages/ckeditor5/src/plugins/table_paste_rows.ts
new file mode 100644
index 0000000000..411a5a8955
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_paste_rows.ts
@@ -0,0 +1,127 @@
+import { Command, Plugin, Table, TableClipboard, TableUtils, TableWalker } from "ckeditor5";
+import type { Editor, ModelInsertContentEvent } from "ckeditor5";
+
+import CutToNotePlugin from "./cuttonote.js";
+import { splitIntoGroups } from "./table_move/table_move_groups.js";
+
+/**
+ * Registers `triliumPasteTableRowsAbove` and `triliumPasteTableRowsBelow`, which paste clipboard
+ * content as new rows next to the row of the selection instead of over its cells.
+ */
+export default class TablePasteRows extends Plugin {
+
+ static get requires() {
+ return [CutToNotePlugin, Table, TableUtils] as const;
+ }
+
+ static get pluginName() {
+ return "TablePasteRows" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+ editor.commands.add("triliumPasteTableRowsAbove",
+ new TablePasteRowsCommand(editor, "above"));
+ editor.commands.add("triliumPasteTableRowsBelow",
+ new TablePasteRowsCommand(editor, "below"));
+ }
+
+}
+
+/** The two clipboard flavors {@link TablePasteRowsCommand} pastes. */
+export interface TablePasteRowsOptions {
+ html: string;
+ text: string;
+}
+
+/**
+ * Pastes clipboard content as new rows above or below the row of the selection, then selects
+ * them. A pasted table becomes one row per table row, starting at the first column, and widens
+ * the table when it has more columns; other content goes in the first cell of one new row. The
+ * rows go outside any block of rows that a merged cell joins. Enabled while the selection is in
+ * a single row.
+ */
+export class TablePasteRowsCommand extends Command {
+
+ private readonly direction: "above" | "below";
+
+ constructor(editor: Editor, direction: "above" | "below") {
+ super(editor);
+ this.direction = direction;
+ }
+
+ refresh() {
+ const tableUtils = this.editor.plugins.get(TableUtils);
+ const selection = this.editor.model.document.selection;
+ const cells = tableUtils.getSelectionAffectedTableCells(selection);
+ if (!cells.length) {
+ this.isEnabled = false;
+ return;
+ }
+
+ const { first, last } = tableUtils.getRowIndexes(cells);
+ this.isEnabled = first === last;
+ }
+
+ execute({ html, text }: TablePasteRowsOptions) {
+ const editor = this.editor;
+ const model = editor.model;
+ const tableUtils = editor.plugins.get(TableUtils);
+ const cells = tableUtils.getSelectionAffectedTableCells(model.document.selection);
+ const table = cells[0]?.findAncestor("table");
+ /* v8 ignore next 3 -- defensive: disabled whenever the selection is outside a table */
+ if (!table) {
+ return;
+ }
+
+ const [group] = splitIntoGroups(table, "row", tableUtils.getRowIndexes(cells));
+ const at = this.direction === "above" ? group.first : group.last + 1;
+ let insertedRows = 0;
+
+ // Runs ahead of `TableClipboard`, which then pastes a table into the new rows from the
+ // caret in their first cell, adding columns when the pasted table is wider.
+ const onInsertContent = (_evt: unknown, [content]: ModelInsertContentEvent["args"][0]) => {
+ if (insertedRows > 0) {
+ return;
+ }
+
+ const pastedTable = editor.plugins.get(TableClipboard)
+ .getTableIfOnlyTableInContent(content, model);
+ insertedRows = pastedTable ? tableUtils.getRows(pastedTable) : 1;
+ model.change((writer) => {
+ tableUtils.insertRows(table, { at, rows: insertedRows });
+ const [firstSlot] = new TableWalker(table, { row: at });
+ const caret = model.schema
+ .getNearestSelectionRange(writer.createPositionAt(firstSlot.cell, 0));
+ writer.setSelection(caret);
+ });
+ };
+
+ this.listenTo<ModelInsertContentEvent>(model, "insertContent", onInsertContent,
+ { priority: "highest" });
+ try {
+ editor.pasteContent(html, text);
+ } finally {
+ this.stopListening(model, "insertContent", onInsertContent);
+ }
+
+ if (insertedRows > 0) {
+ const rows = new TableWalker(table, { startRow: at, endRow: at + insertedRows - 1 });
+ model.change((writer) => {
+ writer.setSelection(Array.from(rows, ({ cell }) => writer.createRangeOn(cell)));
+ });
+ }
+ }
+
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [TablePasteRows.pluginName]: TablePasteRows;
+ }
+
+ interface CommandsMap {
+ triliumPasteTableRowsAbove: TablePasteRowsCommand;
+ triliumPasteTableRowsBelow: TablePasteRowsCommand;
+ }
+}
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 6c6b5f7192..090a10c734 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -230,6 +230,12 @@ export interface ElectronClipboardApi {
* grant the sensitive `clipboard-read` permission to the whole session.
*/
readText(): Promise<string>;
+
+ /**
+ * Reads the HTML flavor of the system clipboard, the same way as {@link readText}. Empty when
+ * the clipboard holds no HTML.
+ */
+ readHTML(): Promise<string>;
}
/**