Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBrowserKeyboard.ts

339 lines15.0 KB

1// @effect-diagnostics globalTimers:off -- The Electron CDP callback adapter bounds native renderer receipts outside an Effect runtime.
2/** Routes Playwright's keyboard packets to the guest, without changing desktop focus. */
3export function createDesktopBrowserKeyboard(
4 contents: Electron.WebContents,
5 debuggee: Electron.Debugger,
6 readClipboard: () => Promise<ReadonlyArray<Electron.ClipboardItem>>,
7) {
8 let pending = 0;
9 let sequence = 0;
10 let generation = 0;
11 let tail: Promise<unknown> = Promise.resolve();
12​
13 const focusedFrame = async () => {
14 // Electron's focusedFrame follows native focus and can be null while the
15 // desktop owns it. Follow DOM focus instead, including cross-site frames.
16 let frame = contents.mainFrame;
17 while (true) {
18 const index: unknown = await frame.executeJavaScript(`(() => {
19 let element = document.activeElement;
20 while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;
21 if (element?.tagName !== "IFRAME" && element?.tagName !== "FRAME") return -1;
22 return Array.from({ length: window.length }, (_, i) => window[i]).indexOf(element.contentWindow);
23 })()`);
24 if (index === -1) return frame;
25 if (typeof index !== "number" || !frame.frames[index]) {
26 throw new Error("The focused preview frame is unavailable.");
27 }
28 frame = frame.frames[index]!;
29 }
30 };
31​
32 const dispatch = async (event: Electron.KeyboardInputEvent, checkCurrent: () => void) => {
33 checkCurrent();
34 const packet = { ...event, skipIfUnhandled: true };
35 contents.setIgnoreMenuShortcuts(true);
36 // Chromium suppresses the char packet when keydown is canceled. The
37 // following keyup receipt confirms the whole native sequence was handled.
38 if (event.type === "char") {
39 contents.sendInputEvent(packet);
40 return false;
41 }
42 const frame = await focusedFrame();
43 const receipt = `__t3KeyboardReceipt${++sequence}`;
44 const type = event.type === "keyUp" ? "keyup" : "keydown";
45 await frame.executeJavaScript(`(() => {
46 const name = ${JSON.stringify(receipt)};
47 const type = ${JSON.stringify(type)};
48 let finish;
49 const promise = new Promise(resolve => { finish = resolve; });
50 let observed = false;
51 let received;
52 const count = performance.eventCounts.get(type) ?? 0;
53 const channel = new MessageChannel();
54 channel.port1.onmessage = () => done({ prevented: received.defaultPrevented });
55 const listener = event => {
56 if (!event.isTrusted) return;
57 observed = true;
58 received = event;
59 // A task runs after every page listener and the default edit. A
60 // microtask can run between listeners, before preventDefault.
61 channel.port2.postMessage(null);
62 };
63 const pagehide = () => done(observed ? { prevented: false } : null);
64 const timer = setTimeout(() => done(null), 5000);
65 const check = setInterval(() => {
66 // Trusted event counts also confirm delivery when page code hides a
67 // key with stopImmediatePropagation before our listener sees it.
68 if (!observed && (performance.eventCounts.get(type) ?? 0) > count) done({ prevented: false });
69 }, 16);
70 const done = result => {
71 clearTimeout(timer);
72 clearInterval(check);
73 channel.port1.close();
74 channel.port2.close();
75 removeEventListener(type, listener, true);
76 removeEventListener("pagehide", pagehide, true);
77 finish(result);
78 };
79 addEventListener(type, listener, true);
80 addEventListener("pagehide", pagehide, true);
81 globalThis[name] = { promise, dispose: () => done(null) };
82 })()`);
83 let timeout: ReturnType<typeof setTimeout> | undefined;
84 try {
85 // CDP's root Input commands can target the embedder's focused renderer.
86 // Native packets address this guest widget; skipIfUnhandled also keeps
87 // keys such as Enter from falling back to the desktop composer.
88 checkCurrent();
89 contents.sendInputEvent(packet);
90 const result: unknown = await Promise.race([
91 frame.executeJavaScript(`globalThis[${JSON.stringify(receipt)}]?.promise`),
92 new Promise<never>((_, reject) => {
93 timeout = setTimeout(
94 () => reject(new Error("The preview page did not receive the keyboard event.")),
95 5000,
96 );
97 }),
98 ]);
99 if (typeof result !== "object" || result === null || !("prevented" in result)) {
100 throw new Error("The preview page did not receive the keyboard event.");
101 }
102 return result.prevented === true;
103 } finally {
104 clearTimeout(timeout);
105 if (!frame.detached) {
106 void frame
107 .executeJavaScript(
108 `globalThis[${JSON.stringify(receipt)}]?.dispose(); delete globalThis[${JSON.stringify(receipt)}]`,
109 )
110 .catch(() => {});
111 }
112 }
113 };
114​
115 const press = async (params: Record<string, unknown>, checkCurrent: () => void) => {
116 const type = params["type"];
117 const key = params["key"];
118 if (
119 (type !== "keyDown" && type !== "rawKeyDown" && type !== "keyUp" && type !== "char") ||
120 typeof key !== "string"
121 ) {
122 throw new Error("Invalid preview keyboard event.");
123 }
124 const mask = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
125 const target = await focusedFrame();
126 if (target.processId !== contents.mainFrame.processId) {
127 // A cross-site frame has its own renderer session. Its Input commands
128 // bypass the root target's embedder-focus lookup.
129 const sessions: Array<string> = [];
130 let sessionId: string | undefined;
131 let contextId: number | undefined;
132 try {
133 while (true) {
134 const evaluated = (await debuggee.sendCommand(
135 "Runtime.evaluate",
136 {
137 expression: `(() => {
138 let element = document.activeElement;
139 while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;
140 return element?.tagName === "IFRAME" || element?.tagName === "FRAME" ? element : null;
141 })()`,
142 ...(contextId === undefined ? {} : { contextId }),
143 },
144 sessionId,
145 )) as { result: { objectId?: string; subtype?: string } };
146 if (evaluated.result.subtype === "null") break;
147 const objectId = evaluated.result.objectId;
148 if (!objectId) throw new Error("The focused preview frame is unavailable.");
149 let frameId: string | undefined;
150 try {
151 const described = (await debuggee.sendCommand(
152 "DOM.describeNode",
153 { objectId },
154 sessionId,
155 )) as { node: { frameId?: string } };
156 frameId = described.node.frameId;
157 } finally {
158 await debuggee
159 .sendCommand("Runtime.releaseObject", { objectId }, sessionId)
160 .catch(() => {});
161 }
162 if (!frameId) throw new Error("The focused preview frame is unavailable.");
163 const targets = (await debuggee.sendCommand("Target.getTargets")) as {
164 targetInfos: ReadonlyArray<{ targetId: string; type: string }>;
165 };
166 if (
167 targets.targetInfos.some(
168 (target) => target.type === "iframe" && target.targetId === frameId,
169 )
170 ) {
171 const attached = (await debuggee.sendCommand("Target.attachToTarget", {
172 targetId: frameId,
173 flatten: true,
174 })) as { sessionId: string };
175 sessionId = attached.sessionId;
176 sessions.push(sessionId);
177 contextId = undefined;
178 } else {
179 const world = (await debuggee.sendCommand(
180 "Page.createIsolatedWorld",
181 { frameId, worldName: "t3-preview-keyboard" },
182 sessionId,
183 )) as { executionContextId: number };
184 contextId = world.executionContextId;
185 }
186 }
187 if (!sessionId) throw new Error("The focused preview frame is unavailable.");
188 await debuggee.sendCommand(
189 "Emulation.setFocusEmulationEnabled",
190 { enabled: true },
191 sessionId,
192 );
193 checkCurrent();
194 await debuggee.sendCommand("Input.dispatchKeyEvent", params, sessionId);
195 } finally {
196 if (sessionId)
197 await debuggee
198 .sendCommand("Emulation.setFocusEmulationEnabled", { enabled: false }, sessionId)
199 .catch(() => {});
200 for (const id of sessions)
201 await debuggee.sendCommand("Target.detachFromTarget", { sessionId: id }).catch(() => {});
202 }
203 return;
204 }
205 const modifiers: NonNullable<Electron.KeyboardInputEvent["modifiers"]> = [];
206 for (const [bit, modifier] of [
207 [1, "alt"],
208 [2, "control"],
209 [4, "meta"],
210 [8, "shift"],
211 ] as const) {
212 if (mask & bit) modifiers.push(modifier);
213 }
214 if (params["isKeypad"] === true) modifiers.push("iskeypad");
215 if (params["autoRepeat"] === true) modifiers.push("isautorepeat");
216 if (params["location"] === 1) modifiers.push("left");
217 if (params["location"] === 2) modifiers.push("right");
218 const keyCode = key.startsWith("Arrow") ? key.slice(5) : key === " " ? "Space" : key;
219 const prevented = await dispatch(
220 {
221 type: type === "rawKeyDown" ? "keyDown" : type,
222 keyCode,
223 modifiers,
224 },
225 checkCurrent,
226 );
227 if (type === "keyUp" || type === "char" || prevented) return;
228 const commands = params["commands"];
229 if (Array.isArray(commands) && commands.length > 0) {
230 const frame = await focusedFrame();
231 const clipboardData: Array<{ type: string; data: string }> = [];
232 if (commands.includes("paste")) {
233 for (const item of await readClipboard()) {
234 for (const type of item.types) {
235 if (type.startsWith("electron ")) continue;
236 const blob = await item.getType(type);
237 if (!("arrayBuffer" in blob)) continue;
238 clipboardData.push({
239 type,
240 data: type.startsWith("text/")
241 ? await blob.text()
242 : Buffer.from(await blob.arrayBuffer()).toString("base64"),
243 });
244 }
245 }
246 }
247 checkCurrent();
248 await frame.executeJavaScript(
249 `(() => {
250 for (const command of ${JSON.stringify(commands)}) {
251 let element = document.activeElement;
252 while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;
253 if (command === "paste") {
254 const transfer = new DataTransfer();
255 for (const { type, data } of ${JSON.stringify(clipboardData)}) {
256 if (type === "text/html") {
257 const container = document.createElement("div");
258 container.setHTML(data);
259 transfer.setData(type, container.innerHTML);
260 } else if (type.startsWith("text/")) transfer.setData(type, data);
261 else transfer.items.add(new File([Uint8Array.from(atob(data), c => c.charCodeAt(0))], "clipboard", { type }));
262 }
263 if (!element?.dispatchEvent(new ClipboardEvent("paste", { clipboardData: transfer, bubbles: true, cancelable: true, composed: true }))) continue;
264 const text = transfer.getData("text/plain");
265 if (!element.dispatchEvent(new InputEvent("beforeinput", { inputType: "insertFromPaste", data: text, dataTransfer: transfer, bubbles: true, cancelable: true, composed: true }))) continue;
266 const html = element.isContentEditable ? transfer.getData("text/html") : "";
267 document.execCommand(html ? "insertHTML" : "insertText", false, html || text);
268 } else if (command.startsWith("moveTo")) {
269 document.getSelection()?.modify(
270 command.endsWith("AndModifySelection") ? "extend" : "move",
271 command.includes("Beginning") ? "backward" : command.includes("Left") ? "left" : command.includes("Right") ? "right" : "forward",
272 command.includes("Document") ? "documentboundary" : "lineboundary",
273 );
274 } else if (command === "deleteToBeginningOfLine") {
275 const selection = document.getSelection();
276 if (!element?.dispatchEvent(new InputEvent("beforeinput", { inputType: "deleteSoftLineBackward", bubbles: true, cancelable: true, composed: true }))) continue;
277 const collapsed = typeof element?.selectionStart === "number" ? element.selectionStart === element.selectionEnd : selection?.isCollapsed;
278 if (collapsed) selection?.modify("extend", "backward", "lineboundary");
279 document.execCommand("delete");
280 } else {
281 const inputType = command === "undo" ? "historyUndo" : command === "redo" ? "historyRedo" : null;
282 if (inputType && !element?.dispatchEvent(new InputEvent("beforeinput", { inputType, bubbles: true, cancelable: true, composed: true }))) continue;
283 document.execCommand(command);
284 }
285 }
286 })()`,
287 true,
288 );
289 }
290 const text = params["text"];
291 if (type === "keyDown" && typeof text === "string" && text.length > 0) {
292 await dispatch({ type: "char", keyCode: text, modifiers }, checkCurrent);
293 }
294 };
295​
296 return {
297 isDispatching: () => pending > 0,
298 cancel: () => {
299 generation++;
300 },
301 send: (method: string, params: Record<string, unknown>) => {
302 pending++;
303 const current = generation;
304 const checkCurrent = () => {
305 if (current !== generation)
306 throw new Error("The preview keyboard connection was released.");
307 };
308 const result = tail.then(async () => {
309 checkCurrent();
310 if (method === "Input.insertText") {
311 const text = params["text"];
312 if (typeof text !== "string") throw new Error("Invalid preview text.");
313 if (text.length > 0) {
314 const frame = await focusedFrame();
315 checkCurrent();
316 const inserted: unknown = await frame.executeJavaScript(`(() => {
317 let element = document.activeElement;
318 while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;
319 const text = ${JSON.stringify(text)};
320 const nonText = ["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"];
321 const textControl = element?.tagName === "TEXTAREA" || (element?.tagName === "INPUT" && !nonText.includes(element.type));
322 if (!(textControl || element?.isContentEditable) || element.disabled || element.readOnly) return false;
323 if (!element?.dispatchEvent(new InputEvent("beforeinput", { inputType: "insertText", data: text, bubbles: true, cancelable: true, composed: true }))) return true;
324 return document.execCommand("insertText", false, text);
325 })()`);
326 if (inserted !== true) throw new Error("The preview page did not accept the text.");
327 }
328 } else {
329 await press(params, checkCurrent);
330 }
331 return {};
332 });
333 tail = result.catch(() => {});
334 return result.finally(() => {
335 pending--;
336 });
337 },
338 };