Open History to see the last commit
1// CDP input follows shared window focus; send directly to unfocused guests to avoid typing into the app.
2
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5
6const FOCUS_ROUTED_INPUT = new Set([
7 "Input.insertText",
8 "Input.dispatchKeyEvent",
9 "Input.imeSetComposition",
10]);
11
12/** Direct input reaches only the main-frame process; insertText crashes when a cross-site frame has focus. */
13const FOCUSED_DOCUMENT = `(() => {
14 let doc = document;
15 for (;;) {
16 const active = doc.activeElement;
17 if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return doc;
18 if (!active.contentDocument) return null;
19 doc = active.contentDocument;
20 }
21})()`;
22
23/** The cross-site frame element holding the document's focus, past same-site frames; null if none does. */
24const FOCUSED_CROSS_SITE_FRAME = `(() => {
25 let doc = document;
26 for (;;) {
27 const active = doc.activeElement;
28 if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return null;
29 if (!active.contentDocument) return active;
30 doc = active.contentDocument;
31 }
32})()`;
33
34/** Electron runs editing commands only for CDP keys; exclude clipboard commands to preserve the user's clipboard. */
35const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]);
36
37/** The queued key's keydown watch, read once its key events have reached the page. */
38const KEY_DOWN = "globalThis.__t3PreviewKeyDown";
39
40const editingCommands = (params: Record<string, unknown>) =>
41 Array.isArray(params["commands"])
42 ? params["commands"].filter((command) => EDITING_COMMANDS.has(command))
43 : undefined;
44
45const CROSS_SITE_FOCUS_MESSAGE =
46 "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first.";
47
48const ARROW_KEYS: Record<string, string> = {
49 ArrowUp: "Up",
50 ArrowDown: "Down",
51 ArrowLeft: "Left",
52 ArrowRight: "Right",
53};
54const NAMED_KEYS = new Set([
55 "Backspace",
56 "Tab",
57 "Enter",
58 "Escape",
59 "Delete",
60 "Insert",
61 "Home",
62 "End",
63 "PageUp",
64 "PageDown",
65 "Shift",
66 "Control",
67 "Alt",
68 "Meta",
69 "CapsLock",
70 "NumLock",
71 "ScrollLock",
72 "PrintScreen",
73]);
74const MODIFIER_BITS = [
75 [1, "alt"],
76 [2, "control"],
77 [4, "meta"],
78 [8, "shift"],
79] as const;
80
81const keyCodeFor = (key: string) => {
82 if ([...key].length === 1) return key;
83 if (ARROW_KEYS[key]) return ARROW_KEYS[key];
84 return NAMED_KEYS.has(key) || /^F(?:[1-9]|1\d|2[0-4])$/u.test(key) ? key : null;
85};
86
87/** Electron derives text from keyCode, so typed text needs separate char events. */
88export const toKeyboardInputEvents = (
89 params: Record<string, unknown>,
90): Array<Electron.KeyboardInputEvent> => {
91 const bits = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
92 const modifiers = MODIFIER_BITS.flatMap(([bit, name]) => (bits & bit ? [name] : []));
93 const text = typeof params["text"] === "string" ? params["text"] : "";
94 const chars = [...text].map((char) => ({ type: "char" as const, keyCode: char, modifiers }));
95 const keyCode = keyCodeFor(typeof params["key"] === "string" ? params["key"] : "");
96 switch (params["type"]) {
97 case "keyDown":
98 return [...(keyCode ? [{ type: "rawKeyDown" as const, keyCode, modifiers }] : []), ...chars];
99 case "rawKeyDown":
100 case "keyUp":
101 return keyCode ? [{ type: params["type"], keyCode, modifiers }] : [];
102 case "char":
103 return chars;
104 default:
105 return [];
106 }
107};
108
109const evaluate = async (debuggee: Electron.Debugger, expression: string) => {
110 const reply = (await debuggee.sendCommand("Runtime.evaluate", {
111 expression,
112 returnByValue: true,
113 })) as { readonly result?: { readonly value?: unknown } };
114 return reply.result?.value;
115};
116
117/** Host focus shared by the presses in flight in one window, so a later press keeps the field an earlier one saved. */
118const HOST_FOCUS = "globalThis.__t3PreviewFocus";
119
120/** A CDP pointer press focuses the guest's native view even with focus emulation enabled. */
121const sendPointerPress = async (
122 webContents: Electron.WebContents,
123 dispatch: () => Promise<unknown>,
124) => {
125 const host = webContents.hostWebContents;
126 if (!host || host.isDestroyed() || webContents.focusedFrame) return dispatch();
127 // Focus in a webview with a press in flight came from that press, so keep the earlier save.
128 await host.executeJavaScript(`(() => {
129 const state = (${HOST_FOCUS} ??= { saved: null, presses: [] });
130 const active = document.activeElement;
131 let pressed = false;
132 try {
133 pressed = active?.tagName === "WEBVIEW" && state.presses.includes(active.getWebContentsId());
134 } catch {}
135 if (!pressed) {
136 state.saved = active && active !== document.body && active.tagName !== "WEBVIEW" ? active : null;
137 }
138 state.presses.push(${webContents.id});
139 })()`);
140 try {
141 return await dispatch();
142 } finally {
143 if (!host.isDestroyed()) {
144 // Membership check: a host reload starts a new state without this press.
145 await host.executeJavaScript(`(() => {
146 const state = ${HOST_FOCUS};
147 const index = state ? state.presses.indexOf(${webContents.id}) : -1;
148 if (index < 0) return;
149 state.presses.splice(index, 1);
150 if (state.presses.length === 0) delete ${HOST_FOCUS};
151 const current = document.activeElement;
152 try {
153 if (state.saved?.isConnected && current?.tagName === "WEBVIEW" &&
154 current.getWebContentsId() === ${webContents.id}) state.saved.focus({ preventScroll: true });
155 } catch {}
156 })()`);
157 }
158 }
159};
160
161/** Calls `listener` once the frame session detaches, at once if it already has; returns a stop. */
162export type FrameDetachWatch = (sessionId: string, listener: () => void) => () => void;
163
164interface FrameRoute {
165 readonly params: Record<string, unknown>;
166 readonly sessionId: string;
167 readonly onDetach: FrameDetachWatch;
168}
169
170/** Moves a page point into the cross-site frame under it, if one has a session; null when none does. */
171export type PointerRoute = (params: Record<string, unknown>) => Promise<FrameRoute | null>;
172
173const FRAME_GONE_MESSAGE =
174 "The frame went away before it took this input. Check the page before retrying.";
175
176const MAX_FRAME_DEPTH = 8;
177const ROUTE_DEADLINE = "1 second";
178
179/**
180 * Chromium picks a pointer event's frame by hit-testing what the window composites, so on a
181 * guest the window does not show, input over a cross-site frame lands on the page instead.
182 * That frame's own session takes the event at frame-local coordinates.
183 */
184export const routeMouseToFrame =
185 (
186 debuggee: Electron.Debugger,
187 frameSessions: ReadonlyMap<string, string>,
188 onDetach: FrameDetachWatch,
189 ): PointerRoute =>
190 async (params) => {
191 // A wheel over a frame that cannot scroll would no longer reach the page behind it.
192 if (params["type"] === "mouseWheel" || frameSessions.size === 0) return null;
193 // Chromium never answers a lookup on a frame that detaches mid-navigation; the page takes it.
194 const routed = await Effect.runPromise(
195 Effect.promise(() => locateFrame(debuggee, frameSessions, params)).pipe(
196 Effect.timeoutOption(ROUTE_DEADLINE),
197 Effect.map(Option.getOrNull),
198 ),
199 );
200 if (!routed || ![...frameSessions.values()].includes(routed.sessionId)) return null;
201 return { ...routed, onDetach };
202 };
203
204/** Finds the cross-site frame holding an unfocused guest's focus, if it has a session; null when none does. */
205export type KeyRoute = (params: Record<string, unknown>) => Promise<FrameRoute | null>;
206
207/**
208 * Direct input cannot reach a cross-site frame, and the page session's CDP keys follow window
209 * focus into the app. The focused frame's own session delivers them to that frame.
210 */
211export const routeKeysToFrame =
212 (
213 debuggee: Electron.Debugger,
214 frameSessions: ReadonlyMap<string, string>,
215 onDetach: FrameDetachWatch,
216 ): KeyRoute =>
217 async (params) => {
218 if (frameSessions.size === 0) return null;
219 const sessionId = await Effect.runPromise(
220 Effect.promise(() => locateFocusedFrame(debuggee, frameSessions)).pipe(
221 Effect.timeoutOption(ROUTE_DEADLINE),
222 Effect.map(Option.getOrNull),
223 ),
224 );
225 if (!sessionId) return null;
226 const commands = editingCommands(params);
227 return { params: commands ? { ...params, commands } : params, sessionId, onDetach };
228 };
229
230const locateFocusedFrame = async (
231 debuggee: Electron.Debugger,
232 frameSessions: ReadonlyMap<string, string>,
233) => {
234 let sessionId: string | undefined;
235 for (let depth = 0; depth < MAX_FRAME_DEPTH; depth++) {
236 try {
237 const { result } = (await debuggee.sendCommand(
238 "Runtime.evaluate",
239 { expression: FOCUSED_CROSS_SITE_FRAME },
240 sessionId,
241 )) as { readonly result: { readonly objectId?: string } };
242 if (result.objectId === undefined) return sessionId ?? null;
243 const { objectId } = result;
244 const { node } = (await debuggee
245 .sendCommand("DOM.describeNode", { objectId }, sessionId)
246 .finally(() => {
247 debuggee.sendCommand("Runtime.releaseObject", { objectId }, sessionId).catch(() => {});
248 })) as { readonly node: { readonly frameId?: string } };
249 // A cross-site frame's target id is its frame id.
250 const frameSession = node.frameId === undefined ? undefined : frameSessions.get(node.frameId);
251 if (frameSession === undefined) return null;
252 sessionId = frameSession;
253 } catch {
254 return null;
255 }
256 }
257 return null;
258};
259
260/** Chromium can drop the reply to input on a frame that detaches before acknowledging it. */
261const sendToFrame = (debuggee: Electron.Debugger, method: string, route: FrameRoute) =>
262 new Promise<unknown>((resolve, reject) => {
263 let gone = false;
264 const stop = route.onDetach(route.sessionId, () => {
265 gone = true;
266 reject(new Error(FRAME_GONE_MESSAGE));
267 });
268 if (gone) return;
269 debuggee.sendCommand(method, route.params, route.sessionId).then(resolve, reject).finally(stop);
270 });
271
272const locateFrame = async (
273 debuggee: Electron.Debugger,
274 frameSessions: ReadonlyMap<string, string>,
275 params: Record<string, unknown>,
276) => {
277 let { x, y } = params;
278 if (typeof x !== "number" || typeof y !== "number") return null;
279 let sessionId: string | undefined;
280 for (let depth = 0; depth < MAX_FRAME_DEPTH; depth++) {
281 try {
282 const { cssLayoutViewport: scroll } = (await debuggee.sendCommand(
283 "Page.getLayoutMetrics",
284 {},
285 sessionId,
286 )) as { readonly cssLayoutViewport: { readonly pageX: number; readonly pageY: number } };
287 // The lookup takes whole document pixels; the event and box model use the viewport.
288 const { backendNodeId } = (await debuggee.sendCommand(
289 "DOM.getNodeForLocation",
290 {
291 x: Math.round(x + scroll.pageX),
292 y: Math.round(y + scroll.pageY),
293 includeUserAgentShadowDOM: true,
294 },
295 sessionId,
296 )) as { readonly backendNodeId: number };
297 const { node } = (await debuggee.sendCommand(
298 "DOM.describeNode",
299 { backendNodeId },
300 sessionId,
301 )) as { readonly node: { readonly frameId?: string } };
302 // A cross-site frame's target id is its frame id; a same-site frame has no session,
303 // and a document's own root element names the frame it is already in.
304 const frameSession = node.frameId === undefined ? undefined : frameSessions.get(node.frameId);
305 if (frameSession === undefined || frameSession === sessionId) break;
306 const { model } = (await debuggee.sendCommand(
307 "DOM.getBoxModel",
308 { backendNodeId },
309 sessionId,
310 )) as { readonly model: { readonly content: ReadonlyArray<number> } };
311 const xs = model.content.filter((_, index) => index % 2 === 0);
312 const ys = model.content.filter((_, index) => index % 2 === 1);
313 const left = Math.min(...xs);
314 const top = Math.min(...ys);
315 // The frame owner's border and padding belong to the page.
316 if (x < left || x >= Math.max(...xs) || y < top || y >= Math.max(...ys)) break;
317 x -= left;
318 y -= top;
319 sessionId = frameSession;
320 } catch {
321 break;
322 }
323 }
324 return sessionId === undefined ? null : { params: { ...params, x, y }, sessionId };
325};
326
327const pointerCommands = new WeakMap<Electron.WebContents, Promise<unknown>>();
328
329/** Focus capture crosses processes; later pointer events must not overtake the press. */
330const sendPointerCommand = async (
331 webContents: Electron.WebContents,
332 debuggee: Electron.Debugger,
333 method: string,
334 params: Record<string, unknown>,
335 sessionId: string | undefined,
336 route: PointerRoute | undefined,
337 beforeDispatch: (() => void) | undefined,
338) => {
339 const previous = pointerCommands.get(webContents) ?? Promise.resolve();
340 const current = previous
341 .catch(() => {})
342 .then(async () => {
343 const routed = route && sessionId === undefined ? await route(params) : null;
344 const dispatch = () => {
345 beforeDispatch?.();
346 return routed
347 ? sendToFrame(debuggee, method, routed)
348 : debuggee.sendCommand(method, params, sessionId);
349 };
350 return params["type"] === "mousePressed" || params["type"] === "touchStart"
351 ? sendPointerPress(webContents, dispatch)
352 : dispatch();
353 });
354 pointerCommands.set(webContents, current);
355 try {
356 return await current;
357 } finally {
358 if (pointerCommands.get(webContents) === current) pointerCommands.delete(webContents);
359 }
360};
361
362const keyCommands = new WeakMap<Electron.WebContents, Promise<unknown>>();
363
364/**
365 * Electron's input skips a key's editing commands, so they run here unless the page prevented
366 * its keydown, as Chromium does. Keys queue so each reads only its own keydown.
367 */
368const sendKeyCommand = async (
369 webContents: Electron.WebContents,
370 debuggee: Electron.Debugger,
371 params: Record<string, unknown>,
372 beforeDispatch: (() => void) | undefined,
373) => {
374 const commands = editingCommands(params) ?? [];
375 const previous = keyCommands.get(webContents) ?? Promise.resolve();
376 const current = previous
377 .catch(() => {})
378 .then(async () => {
379 // The window's capture listener sees the keydown before any page listener can stop it.
380 if (commands.length > 0) {
381 await evaluate(
382 debuggee,
383 `(() => { const view = ${FOCUSED_DOCUMENT}?.defaultView; if (!view) return 0;
384 const watch = { view, event: null, listener: (event) => { watch.event ??= event; } };
385 ${KEY_DOWN} = watch; view.addEventListener("keydown", watch.listener, true); return 0; })()`,
386 );
387 }
388 const release = `(() => { const watch = ${KEY_DOWN}; delete ${KEY_DOWN};
389 watch?.view.removeEventListener("keydown", watch.listener, true); return watch; })()`;
390 try {
391 beforeDispatch?.();
392 for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event);
393 } catch (error) {
394 if (commands.length > 0) await evaluate(debuggee, `${release}, 0`);
395 throw error;
396 }
397 // Runs after the page handles the keys, so the reply also waits for them.
398 await evaluate(
399 debuggee,
400 commands.length === 0
401 ? "0"
402 : `(() => { if (${release}?.event?.defaultPrevented) return 0;
403 const doc = ${FOCUSED_DOCUMENT}; for (const name of ${JSON.stringify(commands)}) doc?.execCommand(name); return 0; })()`,
404 );
405 return {};
406 });
407 keyCommands.set(webContents, current);
408 try {
409 return await current;
410 } finally {
411 if (keyCommands.get(webContents) === current) keyCommands.delete(webContents);
412 }
413};
414
415/**
416 * Sends one command to the guest's page, keeping reloads and input inside it. Input that waits
417 * before it reaches the guest calls `beforeDispatch` once the wait ends, which throws to drop it.
418 */
419export const sendPageCommand = async (
420 webContents: Electron.WebContents,
421 debuggee: Electron.Debugger,
422 method: string,
423 params: Record<string, unknown>,
424 sessionId?: string,
425 routeMouse?: PointerRoute,
426 beforeDispatch?: () => void,
427 routeKeys?: KeyRoute,
428): Promise<unknown> => {
429 if (method === "Input.dispatchMouseEvent") {
430 return sendPointerCommand(
431 webContents,
432 debuggee,
433 method,
434 params,
435 sessionId,
436 routeMouse,
437 beforeDispatch,
438 );
439 }
440 if (method === "Input.dispatchTouchEvent") {
441 return sendPointerCommand(
442 webContents,
443 debuggee,
444 method,
445 params,
446 sessionId,
447 undefined,
448 beforeDispatch,
449 );
450 }
451 if (sessionId !== undefined) return debuggee.sendCommand(method, params, sessionId);
452 // Electron's debugger routes Page.reload on a webview to its embedder window.
453 if (method === "Page.reload") {
454 if (params["ignoreCache"] === true) webContents.reloadIgnoringCache();
455 else webContents.reload();
456 return {};
457 }
458 if (method === "Page.stopLoading") {
459 webContents.stop();
460 return {};
461 }
462 if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) {
463 return debuggee.sendCommand(method, params);
464 }
465 if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) {
466 const routed = routeKeys ? await routeKeys(params) : null;
467 if (!routed) throw new Error(CROSS_SITE_FOCUS_MESSAGE);
468 beforeDispatch?.();
469 return sendToFrame(debuggee, method, routed);
470 }
471 switch (method) {
472 case "Input.insertText":
473 beforeDispatch?.();
474 await webContents.insertText(typeof params["text"] === "string" ? params["text"] : "");
475 return {};
476 case "Input.dispatchKeyEvent":
477 return sendKeyCommand(webContents, debuggee, params, beforeDispatch);
478 default:
479 throw new Error(`${method} needs the preview to have focus.`);
480 }
481};