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/text editor/tables: fix some issues
Adorian Dorancbd290ee68cc
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex 8abb182b98..245a58b634 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -6,8 +6,9 @@ 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+ && { note: tabManager.activeNote, ...tabManager.activeContext },+ getNoteContexts: () => []};return { tabManager, triggerCommand: vi.fn() };});@@ -48,11 +49,13 @@ const { tabManager } = h;/** Builds an editor whose editable DOM root is `domRoot` and selection HTML is `selectedHtml`. */function fakeEditor(domRoot: Node | null, selectedHtml: string, plainText = "") {+ const pasteTarget = { paste: vi.fn(), release: vi.fn() };return {editing: { view: { getDomRoot: () => domRoot } },getSelectedHtml: vi.fn(() => selectedHtml),getSelectedPlainText: vi.fn(() => plainText),- pasteContent: vi.fn(),+ pasteTarget,+ capturePasteTarget: vi.fn(() => pasteTarget),// Without the plugin the AI assistant row is skipped, keeping these tests off it.plugins: { has: () => false },isReadOnly: false,@@ -527,11 +530,47 @@ describe("setupContextMenu (browser)", () => {await run(rows, "electron_context_menu.paste");await vi.waitFor(() =>- expect(editor.pasteContent).toHaveBeenCalledWith("<b>hi</b>", "hi"));+ expect(editor.pasteTarget.paste).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"));+ await vi.waitFor(() =>+ expect(editor.pasteTarget.paste).toHaveBeenCalledWith("", "hi"));+ expect(editor.pasteTarget.release).toHaveBeenCalledTimes(2);+ } finally {+ delete (navigator as { clipboard?: unknown }).clipboard;+ }+ });++ it("pins the paste target before reading the clipboard, and releases it on failure", async () => {+ let rejectRead: (error: Error) => void = () => {};+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: {+ read: vi.fn(() => new Promise((_resolve, reject) => {+ rejectRead = reject;+ }))+ }+ });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});++ 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");++ await run(await menuFor(editorRoot), "electron_context_menu.paste");+ expect(editor.capturePasteTarget).toHaveBeenCalledTimes(1);+ expect(editor.pasteTarget.release).not.toHaveBeenCalled();++ rejectRead(new Error("denied"));+ await vi.waitFor(() => expect(editor.pasteTarget.release).toHaveBeenCalledTimes(1));+ expect(editor.pasteTarget.paste).not.toHaveBeenCalled();+ expect(warn).toHaveBeenCalled();} finally {delete (navigator as { clipboard?: unknown }).clipboard;}diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex e66692f7db..e87856f42e 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -354,9 +354,8 @@ function browserHost(}/**- * 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.+ * The paste rows for a page, supplied when `navigator.clipboard.read()` exists, which requires a+ * secure context.*/function browserPaste(editor: CKTextEditor | null,@@ -380,13 +379,16 @@ async function pasteFromClipboard(element: Element | null | undefined,asPlainText: boolean) {+ // Pinned before the read, which can wait on a permission prompt, so the paste lands where the+ // menu was opened.+ const pasteTarget = editor?.capturePasteTarget();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);+ if (pasteTarget) {+ pasteTarget.paste(asPlainText ? "" : html, text);return;}@@ -399,6 +401,8 @@ async function pasteFromClipboard(}} catch (error) {console.warn("Failed to paste from the clipboard:", error);+ } finally {+ pasteTarget?.release();}}diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.tsindex 54169d26da..0b0f2a3eef 100644--- a/apps/client/src/menus/table_context_menu.spec.ts+++ b/apps/client/src/menus/table_context_menu.spec.ts@@ -83,12 +83,24 @@ describe("buildTableMenuItems", () => {expect(findItem(items, "table_context_menu.distribute_columns")?.enabled).toBe(false);expect(findItem(items, "table_context_menu.merge_cells")?.enabled).toBe(false);- expect(findItem(items, "table_context_menu.split_cells")?.enabled).toBe(false);+ expect(findItem(items, "table_context_menu.split_cells")?.enabled).toBe(true);expect(findItem(items, "table_context_menu.delete_rows")?.enabled).toBe(false);expect(findItem(items, "table_context_menu.delete_columns")?.enabled).toBe(true);expect(findItem(items, "table_context_menu.insert_rows_above")?.enabled).toBe(true);});+ it("enables the split submenu while either split direction is enabled", () => {+ const splitRow = (disabled: string[]) => {+ const { editor } = stubEditor(disabled);+ const items = buildTableMenuItems(editor, cellElement()) ?? [];+ return findItem(items, "table_context_menu.split_cells")?.enabled;+ };++ expect(splitRow(["splitTableCellVertically"])).toBe(true);+ expect(splitRow(["splitTableCellHorizontally"])).toBe(true);+ expect(splitRow(["splitTableCellVertically", "splitTableCellHorizontally"])).toBe(false);+ });+it("returns null without the plugin or a table cell at the target", () => {const { editor: withoutPlugin } = stubEditor([], { hasPlugin: false });expect(buildTableMenuItems(withoutPlugin, cellElement())).toBeNull();diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.tsindex 12c61709f8..4946595888 100644--- a/apps/client/src/menus/table_context_menu.ts+++ b/apps/client/src/menus/table_context_menu.ts@@ -68,7 +68,8 @@ export function buildTableMenuItems({title: t("table_context_menu.split_cells"),uiIcon: "bx bx-border-inner",- enabled: editor.commands.get("splitTableCellVertically")?.isEnabled === true,+ enabled: editor.commands.get("splitTableCellVertically")?.isEnabled === true+ || editor.commands.get("splitTableCellHorizontally")?.isEnabled === true,items: [commandItem(t("table_context_menu.split_vertically"), "bx bx-empty","splitTableCellVertically"),diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.tsindex ba56cdf192..9f3b97281b 100644--- a/apps/client/src/menus/text_editor_context_menu.spec.ts+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts@@ -2,11 +2,18 @@ import type { AiQuickAction, AiQuickActionFooter, AiQuickActionGroup } from "@trimport { beforeEach, describe, expect, it, vi } from "vitest";const h = vi.hoisted(() => {+ interface FakeContext {+ ntxId?: string;+ note?: { type: string } | null;+ getTextEditor: () => Promise<unknown>;+ }const tabManager = {activeNote: null as { type: string } | null,- activeContext: null as { getTextEditor: () => Promise<unknown> } | null,- getActiveContextNote: () => tabManager.activeNote,+ activeContext: null as FakeContext | null,+ contexts: [] as FakeContext[],getActiveContext: () => tabManager.activeContext+ && { note: tabManager.activeNote, ...tabManager.activeContext },+ getNoteContexts: () => tabManager.contexts};return { tabManager };});@@ -95,6 +102,7 @@ describe("getTextEditorAtSelection", () => {vi.restoreAllMocks();tabManager.activeNote = null;tabManager.activeContext = null;+ tabManager.contexts = [];});it("returns the editor only when the selection is inside its DOM root", async () => {@@ -122,6 +130,34 @@ describe("getTextEditorAtSelection", () => {vi.spyOn(console, "error").mockImplementation(() => {});expect(await getTextEditorAtSelection()).toBeNull();});++ it("looks the editor up in the split pane holding the node, active or not", async () => {+ const pane = document.createElement("div");+ pane.dataset.ntxId = "ntx-right";+ const root = document.createElement("div");+ const inside = document.createTextNode("cell");+ root.appendChild(inside);+ pane.appendChild(root);++ const editor = { editing: { view: { getDomRoot: () => root } } };+ tabManager.activeNote = { type: "code" };+ tabManager.activeContext = { ntxId: "ntx-left", getTextEditor: () => Promise.reject() };+ tabManager.contexts = [+ { ntxId: "ntx-left", note: { type: "code" }, getTextEditor: () => Promise.reject() },+ { ntxId: "ntx-right", note: { type: "text" }, getTextEditor: async () => editor }+ ];++ setSelection(inside);+ expect(await getTextEditorAtSelection()).toBe(editor);++ // A pane whose note context is gone, or holds another note type.+ tabManager.contexts = [];+ expect(await getTextEditorAtSelection()).toBeNull();+ tabManager.contexts = [+ { ntxId: "ntx-right", note: { type: "code" }, getTextEditor: async () => editor }+ ];+ expect(await getTextEditorAtSelection()).toBeNull();+ });});describe("buildAiActionsMenuItem", () => {diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsindex 9e9f5df9b4..6350e90ecd 100644--- a/apps/client/src/menus/text_editor_context_menu.ts+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -2,6 +2,7 @@ import type { AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, CKTextEditimport type { CommandNames } from "../components/app_context.js";import appContext from "../components/app_context.js";+import type NoteContext from "../components/note_context.js";import { t } from "../services/i18n.js";import type { MenuItem } from "./context_menu.js";@@ -146,16 +147,19 @@ export async function getTextEditorAtSelection(): Promise<CKTextEditor | null> {* The text editor whose editable contains `node`, or `null` when the node sits anywhere else.* Answers a pointer target rather than the DOM selection, which a right-click does not move in* every browser.+ *+ * The editor is looked up in the split pane holding `node`, which a right-click does not activate.*/export async function getTextEditorContaining(node: Node | null | undefined): Promise<CKTextEditor | null> {- if (!node || appContext.tabManager.getActiveContextNote()?.type !== "text") {+ const noteContext = node ? getNoteContextContaining(node) : null;+ if (!node || noteContext?.note?.type !== "text") {return null;}try {- const editor = await appContext.tabManager.getActiveContext()?.getTextEditor();+ const editor = await noteContext.getTextEditor();const domRoot = editor?.editing.view.getDomRoot();if (editor && domRoot && domRoot.contains(node)) {@@ -168,3 +172,18 @@ export async function getTextEditorContaining(return null;}++/**+ * The note context of the split pane that holds `node`. Outside every pane, e.g. in a dialog, the+ * active note context.+ */+function getNoteContextContaining(node: Node): NoteContext | null {+ const { tabManager } = appContext;+ const element = node instanceof Element ? node : node.parentElement;+ const ntxId = element?.closest<HTMLElement>("[data-ntx-id]")?.dataset.ntxId;+ if (!ntxId) {+ return tabManager.getActiveContext();+ }++ return tabManager.getNoteContexts().find((noteContext) => noteContext.ntxId === ntxId) ?? null;+}diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 568caeed92..82f85071cb 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -6,12 +6,14 @@ import "./theme/blockquote.css";import "./theme/code_block_toolbar.css";import "./theme/link_embed_form.css";import type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";+import type { PasteTarget } from "./plugins/cuttonote.js";import { COMMON_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js";import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";export { default as EditorWatchdog } from "./custom_watchdog";export { CHAT_INPUT_PLUGINS, MEMO_PLUGINS } from "./plugins.js";export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, TextTransformationConfig, TextTypingTransformationDescription, WatchdogConfig, WatchdogState } from "ckeditor5";export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";+export type { PasteTarget } from "./plugins/cuttonote.js";export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";export type { TriliumMentionFeed } from "./plugins/mention/types.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";@@ -37,6 +39,7 @@ export type CKTextEditor = (ClassicEditor | PopupEditor) & {getSelectedHtml(): string;getSelectedPlainText(): string;pasteContent(html: string, text: string): void;+ capturePasteTarget(): PasteTarget;removeSelection(): Promise<void>;};@@ -76,6 +79,7 @@ declare module "ckeditor5" {getSelectedHtml(): string;getSelectedPlainText(): string;pasteContent(html: string, text: string): void;+ capturePasteTarget(): PasteTarget;removeSelection(): Promise<void>;}diff --git a/packages/ckeditor5/src/plugins/cuttonote.spec.ts b/packages/ckeditor5/src/plugins/cuttonote.spec.tsindex 4c38a04986..317e01bdac 100644--- a/packages/ckeditor5/src/plugins/cuttonote.spec.ts+++ b/packages/ckeditor5/src/plugins/cuttonote.spec.ts@@ -96,6 +96,54 @@ describe("CutToNotePlugin", () => {expect(editor.getData()).toContain("ef");});+ describe("capturePasteTarget", () => {+ it("pastes at the selection captured before the content arrived", () => {+ setModelData(editor.model, "<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");+ editor.capturePasteTarget().paste("", "X");+ expect(editor.getData()).toBe("<p>aXb</p><p>cd</p>");++ setModelData(editor.model, "<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");+ const target = editor.capturePasteTarget();+ moveCaret(editor, 1, 1);+ target.paste("", "X");+ expect(editor.getData()).toBe("<p>aXb</p><p>cd</p>");+ });++ it("pastes at the current selection when the captured content was removed", () => {+ setModelData(editor.model, "<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");+ const target = editor.capturePasteTarget();+ editor.model.change((writer) => {+ const first = editor.model.document.getRoot()?.getChild(0);+ if (first) {+ writer.remove(first);+ }+ });+ moveCaret(editor, 0, 1);++ target.paste("", "X");++ expect(editor.getData()).toBe("<p>cXd</p>");+ });++ it("does nothing once the editor is destroyed", async () => {+ const element = document.createElement("div");+ document.body.appendChild(element);+ try {+ const shortLived = await ClassicEditor.create(element, {+ licenseKey: "GPL",+ plugins: [Essentials, Paragraph, CutToNotePlugin]+ });+ const target = shortLived.capturePasteTarget();+ await shortLived.destroy();++ expect(() => target.paste("", "X")).not.toThrow();+ target.release();+ } finally {+ element.remove();+ }+ });+ });+describe("table cell selections", () => {let tableEditor: ClassicEditor;@@ -156,6 +204,25 @@ describe("CutToNotePlugin", () => {expect(data).toContain("b2");expect(data).not.toContain("x1");});++ it("capturePasteTarget restores a cell selection before pasting into it", () => {+ setModelData(tableEditor.model, modelTable([["a1", "b1"], ["a2", "b2"]]));+ selectCells(tableEditor, [0, 0], [1, 1]);+ const html = tableEditor.getSelectedHtml();++ setModelData(tableEditor.model,+ modelTable([["x1", "y1", "z1"], ["x2", "y2", "z2"]]));+ selectCells(tableEditor, [0, 0], [1, 1]);+ const target = tableEditor.capturePasteTarget();+ selectCells(tableEditor, [0, 2], [0, 2]);+ target.paste(html, "");++ const data = tableEditor.getData();+ expect(data).toContain("a1");+ expect(data).toContain("b2");+ expect(data).not.toContain("x1");+ expect(data).toContain("z1");+ });});it("removeSelection deletes the selection, inserts a paragraph and saves the note", async () => {@@ -190,6 +257,17 @@ function modelTable(rows: string[][], attributes = ""): string {return `<table${attributes ? ` ${attributes}` : ""}>${rowsMarkup}</table>`;}+/** Moves the caret to `offset` in the root child at `childIndex`. */+function moveCaret(editor: ClassicEditor, childIndex: number, offset: number) {+ editor.model.change((writer) => {+ const block = editor.model.document.getRoot()?.getChild(childIndex);+ if (!block?.is("element")) {+ throw new Error(`No element at root child ${childIndex}.`);+ }+ writer.setSelection(block, offset);+ });+}+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]);diff --git a/packages/ckeditor5/src/plugins/cuttonote.ts b/packages/ckeditor5/src/plugins/cuttonote.tsindex cf7727a9fb..a6bfed3130 100644--- a/packages/ckeditor5/src/plugins/cuttonote.ts+++ b/packages/ckeditor5/src/plugins/cuttonote.ts@@ -1,7 +1,23 @@import scissorsIcon from '../icons/scissors.svg?raw';-import { ButtonView, HtmlDataProcessor, Plugin, plainTextToHtml, ViewDataTransfer, viewToPlainText } from 'ckeditor5';+import {+ ButtonView,+ HtmlDataProcessor,+ ModelLiveRange,+ Plugin,+ plainTextToHtml,+ ViewDataTransfer,+ viewToPlainText+} from 'ckeditor5';import type { ViewDocumentFragment } from 'ckeditor5';+/** A selection pinned by `capturePasteTarget()` for a paste whose content arrives later. */+export interface PasteTarget {+ /** Pastes at the pinned selection, then releases it. */+ paste(html: string, text: string): void;+ /** Detaches the pinned ranges without pasting. Safe to call more than once. */+ release(): void;+}+export default class CutToNotePlugin extends Plugin {private htmlDataProcessor!: HtmlDataProcessor;@@ -34,6 +50,7 @@ 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.capturePasteTarget = () => this.capturePasteTarget();this.editor.removeSelection = () => this.removeSelection();}@@ -90,6 +107,52 @@ export default class CutToNotePlugin extends Plugin {});}+ /**+ * Pins the current selection as live ranges, for a paste whose content arrives asynchronously,+ * e.g. from `navigator.clipboard.read()`. `paste()` moves the selection back onto the pinned+ * ranges first, so a selection changed while the content was read does not move the paste.+ * Ranges whose content was removed in the meantime are dropped; with none left, the paste goes+ * to the current selection.+ */+ capturePasteTarget(): PasteTarget {+ const editor = this.editor;+ const ranges = [...editor.model.document.selection.getRanges()]+ .map((range) => ModelLiveRange.fromRange(range));+ const release = () => {+ for (const range of ranges) {+ range.detach();+ }+ };++ return {+ paste: (html, text) => {+ if (editor.state === "destroyed") {+ release();+ return;+ }+ this.restoreSelection(ranges);+ release();+ this.pasteContent(html, text);+ },+ release+ };+ }++ private restoreSelection(ranges: ModelLiveRange[]) {+ const model = this.editor.model;+ const targets = ranges+ .filter((range) => range.root !== model.document.graveyard)+ .map((range) => range.toRange());+ const current = [...model.document.selection.getRanges()];+ const isUnchanged = targets.length === current.length+ && targets.every((range, index) => range.isEqual(current[index]));+ if (!targets.length || isUnchanged) {+ return;+ }++ model.change((writer) => writer.setSelection(targets));+ }+async removeSelection() {const model = this.editor.model;