Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(ui): preserve editable selection after clipboard fallback (#10016)

沙雕的小鱼儿 boyfeiyu6959199196b6
diff --git a/packages/ui/lib/clipboard.ssr.test.ts b/packages/ui/lib/clipboard.ssr.test.ts
new file mode 100644
index 0000000000..9121baa256
--- /dev/null
+++ b/packages/ui/lib/clipboard.ssr.test.ts
@@ -0,0 +1,7 @@
+// @vitest-environment node
+import { expect, it } from "vitest";
+import { copyText } from "./clipboard";
+
+it("returns false without a browser document or Clipboard API", async () => {
+ expect(await copyText("synthetic payload")).toBe(false);
+});
diff --git a/packages/ui/lib/clipboard.test.ts b/packages/ui/lib/clipboard.test.ts
new file mode 100644
index 0000000000..dffa5bc4c7
--- /dev/null
+++ b/packages/ui/lib/clipboard.test.ts
@@ -0,0 +1,142 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { copyText } from "./clipboard";
+
+const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, "clipboard");
+
+function selectEditable(direction: "forward" | "backward" | "collapsed") {
+ const editor = document.createElement("div");
+ editor.contentEditable = "true";
+ editor.tabIndex = 0;
+ editor.textContent = "synthetic editable text";
+ document.body.append(editor);
+ editor.focus();
+ const text = editor.firstChild!;
+ const selection = document.getSelection()!;
+ const anchor = direction === "backward" ? 12 : direction === "collapsed" ? 8 : 2;
+ const focus = direction === "collapsed" ? 8 : direction === "backward" ? 2 : 12;
+ selection.setBaseAndExtent(text, anchor, text, focus);
+ return { editor, text, selection, anchor, focus };
+}
+
+beforeEach(() => {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: undefined,
+ });
+ // jsdom does not move DOM Selection when a textarea receives focus. Model
+ // that browser behavior so these tests exercise restoration, not a no-op.
+ const focus = HTMLTextAreaElement.prototype.focus;
+ vi.spyOn(HTMLTextAreaElement.prototype, "focus").mockImplementation(
+ function (this: HTMLTextAreaElement) {
+ focus.call(this);
+ document.getSelection()?.removeAllRanges();
+ },
+ );
+ Object.defineProperty(document, "execCommand", {
+ configurable: true,
+ value: vi.fn(() => true),
+ });
+});
+
+afterEach(() => {
+ document.body.replaceChildren();
+ document.getSelection()?.removeAllRanges();
+ vi.restoreAllMocks();
+ if (clipboardDescriptor) {
+ Object.defineProperty(navigator, "clipboard", clipboardDescriptor);
+ } else {
+ Reflect.deleteProperty(navigator, "clipboard");
+ }
+});
+
+describe("copyText selection preservation", () => {
+ it.each(["forward", "backward", "collapsed"] as const)("restores a %s contenteditable selection after fallback", async (direction) => {
+ const { editor, text, selection, anchor, focus } = selectEditable(direction);
+ expect(await copyText("synthetic code payload")).toBe(true);
+ expect(document.activeElement).toBe(editor);
+ expect(selection.anchorNode).toBe(text);
+ expect(selection.anchorOffset).toBe(anchor);
+ expect(selection.focusNode).toBe(text);
+ expect(selection.focusOffset).toBe(focus);
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+
+ it.each(["false", "throw"])("restores selection when execCommand returns %s", async (outcome) => {
+ const { text, selection } = selectEditable("backward");
+ vi.mocked(document.execCommand).mockImplementation(() => {
+ if (outcome === "throw") throw new Error("synthetic copy failure");
+ return false;
+ });
+ expect(await copyText("payload")).toBe(false);
+ expect(selection.anchorNode).toBe(text);
+ expect(selection.anchorOffset).toBe(12);
+ expect(selection.focusOffset).toBe(2);
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+
+ it("restores selection when async writeText rejects into fallback", async () => {
+ const { text, selection } = selectEditable("forward");
+ const writeText = vi.fn().mockRejectedValue(new Error("synthetic denial"));
+ Object.defineProperty(navigator, "clipboard", {
+ value: { writeText },
+ configurable: true,
+ });
+ expect(await copyText("payload")).toBe(true);
+ expect(writeText).toHaveBeenCalledWith("payload");
+ expect(selection.anchorNode).toBe(text);
+ expect(selection.anchorOffset).toBe(2);
+ expect(selection.focusOffset).toBe(12);
+ });
+
+ it("leaves selection and focus untouched on async success", async () => {
+ const { editor, text, selection } = selectEditable("backward");
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, "clipboard", {
+ value: { writeText },
+ configurable: true,
+ });
+ expect(await copyText("payload")).toBe(true);
+ expect(document.execCommand).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(editor);
+ expect(selection.anchorNode).toBe(text);
+ expect(selection.anchorOffset).toBe(12);
+ expect(selection.focusOffset).toBe(2);
+ });
+
+ it.each(["input", "textarea"] as const)("preserves the focused %s selection", async (tag) => {
+ const input = document.createElement(tag);
+ input.value = "synthetic form field";
+ document.body.append(input);
+ input.focus();
+ input.setSelectionRange(2, 9, "backward");
+ expect(await copyText("payload")).toBe(true);
+ expect(document.activeElement).toBe(input);
+ expect([input.selectionStart, input.selectionEnd, input.selectionDirection]).toEqual([2, 9, "backward"]);
+ expect(document.querySelectorAll("textarea")).toHaveLength(tag === "textarea" ? 1 : 0);
+ });
+
+ it("keeps an empty DOM selection empty and restores the button focus", async () => {
+ const button = document.createElement("button");
+ document.body.append(button);
+ button.focus();
+ document.getSelection()!.removeAllRanges();
+ expect(await copyText("payload")).toBe(true);
+ expect(document.getSelection()!.rangeCount).toBe(0);
+ expect(document.activeElement).toBe(button);
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+
+ it("does not restore a selection or focus into disconnected nodes", async () => {
+ const { editor, text, selection } = selectEditable("forward");
+ const focus = vi.spyOn(editor, "focus");
+ vi.mocked(document.execCommand).mockImplementation(() => {
+ editor.remove();
+ return true;
+ });
+ expect(await copyText("payload")).toBe(true);
+ expect(selection.anchorNode).not.toBe(text);
+ expect(document.activeElement).toBe(document.body);
+ expect(focus).not.toHaveBeenCalled();
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+});
diff --git a/packages/ui/lib/clipboard.ts b/packages/ui/lib/clipboard.ts
index 4b8ba079aa..347811e0a5 100644
--- a/packages/ui/lib/clipboard.ts
+++ b/packages/ui/lib/clipboard.ts
@@ -46,6 +46,21 @@ export async function copyText(text: string): Promise<boolean> {
const previouslyFocused =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ // Form controls keep their own selection when focus is restored. Applying a
+ // DOM Selection there would instead reset their selectionStart/selectionEnd.
+ const selection =
+ previouslyFocused instanceof HTMLInputElement ||
+ previouslyFocused instanceof HTMLTextAreaElement
+ ? null
+ : document.getSelection();
+ const anchorNode = selection?.anchorNode;
+ const focusNode = selection?.focusNode;
+ const range = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : null;
+ const backward =
+ range &&
+ anchorNode === range.endContainer &&
+ selection?.anchorOffset === range.endOffset;
+
document.body.appendChild(textarea);
try {
textarea.focus();
@@ -55,7 +70,27 @@ export async function copyText(text: string): Promise<boolean> {
return false;
} finally {
document.body.removeChild(textarea);
- previouslyFocused?.focus();
+ if (previouslyFocused?.isConnected) previouslyFocused.focus();
+ if (selection && range && anchorNode?.isConnected && focusNode?.isConnected) {
+ // A Range alone loses backward selections. Restore the anchor and focus
+ // in their original order so the next edit keeps the same caret/selection.
+ selection.setBaseAndExtent(
+ backward ? range.endContainer : range.startContainer,
+ backward ? range.endOffset : range.startOffset,
+ backward ? range.startContainer : range.endContainer,
+ backward ? range.startOffset : range.endOffset,
+ );
+ // Setting a DOM selection can focus its editing host (e.g. after a copy
+ // button click). Keep the original focus target, as on the async path.
+ if (
+ previouslyFocused?.isConnected &&
+ document.activeElement !== previouslyFocused
+ ) {
+ previouslyFocused.focus();
+ }
+ } else if (selection && !range) {
+ selection.removeAllRanges();
+ }
}
}
diff --git a/packages/views/editor/extensions/code-block-view.clipboard.test.tsx b/packages/views/editor/extensions/code-block-view.clipboard.test.tsx
new file mode 100644
index 0000000000..a616df8fd6
--- /dev/null
+++ b/packages/views/editor/extensions/code-block-view.clipboard.test.tsx
@@ -0,0 +1,105 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { EditorContent, ReactNodeViewRenderer, useEditor } from "@tiptap/react";
+import StarterKit from "@tiptap/starter-kit";
+import { createLowlight } from "lowlight";
+import { CodeBlockExtension } from "./code-block";
+import { CodeBlockView } from "./code-block-view";
+
+const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, "clipboard");
+
+vi.mock("../mermaid-diagram", () => ({ MermaidDiagram: () => null }));
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (select: (value: unknown) => string) =>
+ select({ code_block: { copy_code: "Copy code" } }),
+ }),
+}));
+
+function CopyableEditor() {
+ const editor = useEditor({
+ extensions: [
+ StarterKit.configure({ codeBlock: false }),
+ CodeBlockExtension.extend({
+ addNodeView: () => ReactNodeViewRenderer(CodeBlockView),
+ }).configure({ lowlight: createLowlight() }),
+ ],
+ content: {
+ type: "doc",
+ content: [{
+ type: "codeBlock",
+ attrs: { language: "text" },
+ content: [{ type: "text", text: "synthetic editable text" }],
+ }],
+ },
+ });
+ return <EditorContent editor={editor} />;
+}
+
+afterEach(() => {
+ cleanup();
+ document.getSelection()?.removeAllRanges();
+ vi.restoreAllMocks();
+ if (clipboardDescriptor) {
+ Object.defineProperty(navigator, "clipboard", clipboardDescriptor);
+ } else {
+ Reflect.deleteProperty(navigator, "clipboard");
+ }
+});
+
+describe("CodeBlockView clipboard wiring with a real Tiptap editor", () => {
+ it.each([true, false])("keeps the editing selection and gates the copied indicator on %s", async (copied) => {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: undefined,
+ });
+ const focus = HTMLTextAreaElement.prototype.focus;
+ // jsdom does not replace DOM Selection when a textarea takes focus.
+ vi.spyOn(HTMLTextAreaElement.prototype, "focus").mockImplementation(
+ function (this: HTMLTextAreaElement) {
+ focus.call(this);
+ document.getSelection()?.removeAllRanges();
+ },
+ );
+ const payloads: string[] = [];
+ Object.defineProperty(document, "execCommand", {
+ configurable: true,
+ value: vi.fn(() => {
+ payloads.push((document.activeElement as HTMLTextAreaElement).value);
+ return copied;
+ }),
+ });
+ const { container } = render(<CopyableEditor />);
+ const button = await screen.findByRole("button", { name: "Copy code" });
+ const editor = container.querySelector<HTMLElement>(".tiptap")!;
+ const text = document.createTreeWalker(
+ container.querySelector("code")!,
+ NodeFilter.SHOW_TEXT,
+ ).nextNode()!;
+ act(() => {
+ editor.focus();
+ button.focus();
+ // jsdom moves Selection into focused buttons; real browsers retain the
+ // editor selection on a copy click (also covered by the browser fixture).
+ document.getSelection()!.setBaseAndExtent(text, 12, text, 2);
+ });
+ fireEvent.click(button);
+ await waitFor(() => expect(payloads).toEqual(["synthetic editable text"]));
+ await waitFor(() =>
+ expect(container.querySelector(".icon-check") !== null).toBe(copied),
+ );
+ const selection = document.getSelection()!;
+ expect(selection.anchorNode).toBe(text);
+ expect(selection.anchorOffset).toBe(12);
+ expect(selection.focusOffset).toBe(2);
+ expect(document.activeElement).toBe(button);
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+});