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

GuestInput.ts

359 lines12.7 KB

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