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