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

GuestInput.ts

198 lines6.7 KB

1// CDP input follows shared window focus; send directly to unfocused guests to avoid typing into the app.
2​
3const FOCUS_ROUTED_INPUT = new Set([
4 "Input.insertText",
5 "Input.dispatchKeyEvent",
6 "Input.imeSetComposition",
7]);
8​
9/** Direct input reaches only the main-frame process; insertText crashes when a cross-site frame has focus. */
10const FOCUSED_DOCUMENT = `(() => {
11 let doc = document;
12 for (;;) {
13 const active = doc.activeElement;
14 if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return doc;
15 if (!active.contentDocument) return null;
16 doc = active.contentDocument;
17 }
18})()`;
19​
20/** Electron runs editing commands only for CDP keys; exclude clipboard commands to preserve the user's clipboard. */
21const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]);
22​
23const CROSS_SITE_FOCUS_MESSAGE =
24 "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first.";
25​
26const ARROW_KEYS: Record<string, string> = {
27 ArrowUp: "Up",
28 ArrowDown: "Down",
29 ArrowLeft: "Left",
30 ArrowRight: "Right",
31};
32const NAMED_KEYS = new Set([
33 "Backspace",
34 "Tab",
35 "Enter",
36 "Escape",
37 "Delete",
38 "Insert",
39 "Home",
40 "End",
41 "PageUp",
42 "PageDown",
43 "Shift",
44 "Control",
45 "Alt",
46 "Meta",
47 "CapsLock",
48 "NumLock",
49 "ScrollLock",
50 "PrintScreen",
51]);
52const MODIFIER_BITS = [
53 [1, "alt"],
54 [2, "control"],
55 [4, "meta"],
56 [8, "shift"],
57] as const;
58​
59const keyCodeFor = (key: string) => {
60 if ([...key].length === 1) return key;
61 if (ARROW_KEYS[key]) return ARROW_KEYS[key];
62 return NAMED_KEYS.has(key) || /^F(?:[1-9]|1\d|2[0-4])$/u.test(key) ? key : null;
63};
64​
65/** Electron derives text from keyCode, so typed text needs separate char events. */
66export const toKeyboardInputEvents = (
67 params: Record<string, unknown>,
68): Array<Electron.KeyboardInputEvent> => {
69 const bits = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
70 const modifiers = MODIFIER_BITS.flatMap(([bit, name]) => (bits & bit ? [name] : []));
71 const text = typeof params["text"] === "string" ? params["text"] : "";
72 const chars = [...text].map((char) => ({ type: "char" as const, keyCode: char, modifiers }));
73 const keyCode = keyCodeFor(typeof params["key"] === "string" ? params["key"] : "");
74 switch (params["type"]) {
75 case "keyDown":
76 return [...(keyCode ? [{ type: "rawKeyDown" as const, keyCode, modifiers }] : []), ...chars];
77 case "rawKeyDown":
78 case "keyUp":
79 return keyCode ? [{ type: params["type"], keyCode, modifiers }] : [];
80 case "char":
81 return chars;
82 default:
83 return [];
84 }
85};
86​
87const evaluate = async (debuggee: Electron.Debugger, expression: string) => {
88 const reply = (await debuggee.sendCommand("Runtime.evaluate", {
89 expression,
90 returnByValue: true,
91 })) as { readonly result?: { readonly value?: unknown } };
92 return reply.result?.value;
93};
94​
95let focusSequence = 0;
96​
97/** A CDP pointer press focuses the guest's native view even with focus emulation enabled. */
98const sendPointerPress = async (
99 webContents: Electron.WebContents,
100 debuggee: Electron.Debugger,
101 method: string,
102 params: Record<string, unknown>,
103 sessionId: string | undefined,
104) => {
105 const host = webContents.hostWebContents;
106 if (!host || host.isDestroyed() || webContents.focusedFrame) {
107 return debuggee.sendCommand(method, params, sessionId);
108 }
109 const key = JSON.stringify(`__t3PreviewFocus${++focusSequence}`);
110 await host.executeJavaScript(`(() => {
111 const active = document.activeElement;
112 if (!active || active === document.body || active.tagName === "WEBVIEW") return;
113 globalThis[${key}] = () => {
114 delete globalThis[${key}];
115 const current = document.activeElement;
116 if (active.isConnected && current?.tagName === "WEBVIEW" &&
117 current.getWebContentsId() === ${webContents.id}) active.focus({ preventScroll: true });
118 };
119 })()`);
120 try {
121 return await debuggee.sendCommand(method, params, sessionId);
122 } finally {
123 if (!host.isDestroyed()) {
124 await host.executeJavaScript(`globalThis[${key}]?.()`);
125 }
126 }
127};
128​
129const pointerCommands = new WeakMap<Electron.WebContents, Promise<unknown>>();
130​
131/** Focus capture crosses processes; later pointer events must not overtake the press. */
132const sendPointerCommand = async (
133 webContents: Electron.WebContents,
134 debuggee: Electron.Debugger,
135 method: string,
136 params: Record<string, unknown>,
137 sessionId: string | undefined,
138) => {
139 const previous = pointerCommands.get(webContents) ?? Promise.resolve();
140 const current = previous
141 .catch(() => {})
142 .then(() =>
143 params["type"] === "mousePressed" || params["type"] === "touchStart"
144 ? sendPointerPress(webContents, debuggee, method, params, sessionId)
145 : debuggee.sendCommand(method, params, sessionId),
146 );
147 pointerCommands.set(webContents, current);
148 try {
149 return await current;
150 } finally {
151 if (pointerCommands.get(webContents) === current) pointerCommands.delete(webContents);
152 }
153};
154​
155/** Sends one command to the guest's page, keeping reloads and input inside it. */
156export const sendPageCommand = async (
157 webContents: Electron.WebContents,
158 debuggee: Electron.Debugger,
159 method: string,
160 params: Record<string, unknown>,
161 sessionId?: string,
162): Promise<unknown> => {
163 if (method === "Input.dispatchMouseEvent" || method === "Input.dispatchTouchEvent") {
164 return sendPointerCommand(webContents, debuggee, method, params, sessionId);
165 }
166 if (sessionId !== undefined) return debuggee.sendCommand(method, params, sessionId);
167 // Electron's debugger routes Page.reload on a webview to its embedder window.
168 if (method === "Page.reload") {
169 if (params["ignoreCache"] === true) webContents.reloadIgnoringCache();
170 else webContents.reload();
171 return {};
172 }
173 if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) {
174 return debuggee.sendCommand(method, params);
175 }
176 if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) {
177 throw new Error(CROSS_SITE_FOCUS_MESSAGE);
178 }
179 switch (method) {
180 case "Input.insertText":
181 await webContents.insertText(typeof params["text"] === "string" ? params["text"] : "");
182 return {};
183 case "Input.dispatchKeyEvent": {
184 for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event);
185 const commands = Array.isArray(params["commands"])
186 ? params["commands"].filter((command) => EDITING_COMMANDS.has(command))
187 : [];
188 // Runs after the page handles the keys, so the reply also waits for them.
189 await evaluate(
190 debuggee,
191 `(() => { const doc = ${FOCUSED_DOCUMENT}; for (const name of ${JSON.stringify(commands)}) doc?.execCommand(name); return 0; })()`,
192 );
193 return {};
194 }
195 default:
196 throw new Error(`${method} needs the preview to have focus.`);
197 }
198};