Skip to content

Commit 3661e61

Browse files
committed
fix(server): preview copy keys forward only the text they copied
The copy recorder armed on every key, so text a page copied during another key, or text a frame kept without being read, could go out with a later copy key from a different frame. It now arms only on Ctrl or Cmd + C or X, and the server clears every frame's text right before it sends a copy or cut key, as well as after. The selection is now read while the event is captured at window, so a page copy handler that stops propagation still copies the selection. Text a page sets with preventDefault and setData still replaces it. The focused field is found through open shadow roots.
1 parent 847a93d commit 3661e61

2 files changed

Lines changed: 44 additions & 19 deletions

File tree

‎apps/server/src/preview/ServerBrowser.test.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,15 @@ function makeSession() {
7070
if (method === "Page.captureScreenshot") return { data: "ZnJhbWU=" };
7171
if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
7272
if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
73-
// The clipboard world answers with what the page last copied.
74-
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7)
75-
return { result: { value: pageCopy } };
73+
// A copy or cut key copies keyCopy; one that copies nothing leaves the frames as they were.
74+
if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands)
75+
pageCopy = keyCopy || pageCopy;
76+
// The clipboard world hands over what the page's frames copied, once.
77+
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) {
78+
const value = pageCopy;
79+
pageCopy = "";
80+
return { result: { value } };
81+
}
7682
return { result: { value: "evaluated" } };
7783
}),
7884
};
@@ -156,6 +162,8 @@ const contextRequests: Array<{ profileId: string; isolated: boolean }> = [];
156162
let contextGate: PromiseWithResolvers<void> | null = null;
157163
/** The text the page's frames hold from their latest copy. */
158164
let pageCopy = "";
165+
/** The text the next copy or cut key copies. */
166+
let keyCopy = "";
159167
let contextFailure: Error | null = null;
160168
/** Server tabs the fake desktop renders, and the endpoints the server connected to. */
161169
let desktopRendersNext = false;
@@ -274,6 +282,7 @@ beforeEach(() => {
274282
contextGate = null;
275283
contextFailure = null;
276284
pageCopy = "";
285+
keyCopy = "";
277286
desktopTabs.clear();
278287
desktopRendersNext = false;
279288
releasedDesktopTabs.length = 0;
@@ -1027,19 +1036,20 @@ it.live("only the controlling viewer's copy and cut keys reach its clipboard", (
10271036
yield* viewer.input({ type: "key", action: "down", key: "v", code: "KeyV", modifiers: 4 });
10281037
yield* viewer.input({ type: "unknown" });
10291038
expect(yield* clipboard(viewer.output)).toEqual([]);
1030-
pageCopy = "copied";
1039+
keyCopy = "copied";
10311040
yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
10321041
const cdp = contexts[0]!.sessions.at(-1)!;
10331042
expect(cdp.send).toHaveBeenCalledWith(
10341043
"Input.dispatchKeyEvent",
10351044
expect.objectContaining({ key: "c", commands: ["copy"] }),
10361045
);
10371046
expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "copied" }]);
1038-
pageCopy = "cut";
1047+
keyCopy = "cut";
10391048
yield* viewer.input({ type: "key", action: "down", key: "x", code: "KeyX", modifiers: 2 });
10401049
expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "cut" }]);
1041-
// A copy key with nothing copied sends nothing.
1042-
pageCopy = "";
1050+
// A copy key with nothing copied sends nothing, not what a frame kept from before.
1051+
pageCopy = "left over";
1052+
keyCopy = "";
10431053
yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
10441054
expect(yield* clipboard(viewer.output)).toEqual([]);
10451055
expect(yield* clipboard(watcher.output)).toEqual([]);

‎apps/server/src/preview/ServerBrowser.ts‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -440,26 +440,38 @@ const CLIPBOARD_WORLD = "t3-preview-clipboard";
440440
const CLIPBOARD_SCRIPT = `(() => {
441441
let keying = false;
442442
let copied = "";
443+
// The same Ctrl or Cmd + C or X that editingCommand sends as copy or cut.
443444
addEventListener("keydown", (event) => {
444-
if (!event.isTrusted) return;
445+
if (!event.isTrusted || event.altKey || event.ctrlKey === event.metaKey) return;
446+
const key = event.key.toLowerCase();
447+
if (key !== "c" && key !== "x") return;
445448
keying = true;
446449
copied = "";
447450
setTimeout(() => { keying = false; });
448451
}, true);
449452
const selection = () => {
450-
const field = document.activeElement;
453+
let field = document.activeElement;
454+
while (field?.shadowRoot?.activeElement) field = field.shadowRoot.activeElement;
451455
if ((field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) && field.selectionStart !== null)
452456
return field.value.slice(field.selectionStart, field.selectionEnd ?? field.selectionStart);
453457
return String(document.getSelection() ?? "");
454458
};
455-
// Bubbling to window runs after page handlers, before cut removes the selection.
456-
const record = (event) => {
457-
if (!keying || !event.isTrusted) return;
458-
const text = event.defaultPrevented ? event.clipboardData?.getData("text/plain") : selection();
459+
const record = (text) => {
459460
copied = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT});
460461
};
461-
addEventListener("copy", record);
462-
addEventListener("cut", record);
462+
// Capturing at window runs before page handlers can stop the event, and
463+
// before cut removes the selection.
464+
const snapshot = (event) => {
465+
if (keying && event.isTrusted) record(selection());
466+
};
467+
// Bubbling back to window picks up text a page handler set instead.
468+
const replace = (event) => {
469+
if (keying && event.isTrusted && event.defaultPrevented) record(event.clipboardData?.getData("text/plain"));
470+
};
471+
for (const type of ["copy", "cut"]) {
472+
addEventListener(type, snapshot, true);
473+
addEventListener(type, replace);
474+
}
463475
globalThis.takeCopy = () => {
464476
const text = copied;
465477
copied = "";
@@ -1136,7 +1148,7 @@ const make = Effect.gen(function* () {
11361148
});
11371149
};
11381150

1139-
/** What the key just handled copied or cut in any of the tab's frames, once. */
1151+
/** Clears every frame's copy and returns what the key just handled copied or cut. */
11401152
const takeCopiedText = async (tab: ServerTab) => {
11411153
const { frameTree } = await tab.cdp.send("Page.getFrameTree");
11421154
const frameIds = (node: typeof frameTree): Array<string> => [
@@ -2127,6 +2139,11 @@ const make = Effect.gen(function* () {
21272139
return;
21282140
}
21292141
const command = editingCommand(key, modifiers);
2142+
// Only the controlling viewer's own copy and cut reach its clipboard.
2143+
const copying =
2144+
!tab.desktop && (command?.commands[0] === "copy" || command?.commands[0] === "cut");
2145+
// Clear what any frame kept from an earlier key, so only this key's copy is read.
2146+
if (copying) await takeCopiedText(tab);
21302147
await session.send("Input.dispatchKeyEvent", {
21312148
type: text ? "keyDown" : "rawKeyDown",
21322149
key,
@@ -2140,9 +2157,7 @@ const make = Effect.gen(function* () {
21402157
),
21412158
});
21422159
viewer.pressedKeys.set(code || key, { key, code });
2143-
// Only the controlling viewer's own copy and cut reach its clipboard.
2144-
const copying = command?.commands[0] === "copy" || command?.commands[0] === "cut";
2145-
if (copying && !tab.desktop) {
2160+
if (copying) {
21462161
const copied = await takeCopiedText(tab);
21472162
if (copied) viewer.push({ _tag: "clipboard", text: copied });
21482163
}

0 commit comments

Comments
 (0)