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

GuestInput.ts

150 lines5.0 KB

1/**
2 * Keyboard and text input for a preview tab's page that never lands outside it.
3 *
4 * Chromium sends a page's CDP key and text input to whichever frame holds focus
5 * in the window. A `<webview>` guest shares that focus with the app around it,
6 * so while a person works in the app, `Input.insertText` on the guest's own
7 * debugger types into the app's focused field. Such input goes through CDP only
8 * while the guest holds focus. Otherwise it goes straight to the guest's own
9 * widget, which nothing redirects.
10 */
11​
12/** CDP input Chromium delivers to the window's focused frame rather than the page's. */
13const FOCUS_ROUTED_INPUT = new Set([
14 "Input.insertText",
15 "Input.dispatchKeyEvent",
16 "Input.imeSetComposition",
17]);
18​
19/**
20 * Page script: the document holding the page's focus, or null when a cross-site
21 * frame holds it. Electron's direct input reaches only the main frame's process,
22 * and `insertText` crashes the page when focus is in another one.
23 */
24const FOCUSED_DOCUMENT = `(() => {
25 let doc = document;
26 for (;;) {
27 const active = doc.activeElement;
28 if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return doc;
29 if (!active.contentDocument) return null;
30 doc = active.contentDocument;
31 }
32})()`;
33​
34/**
35 * macOS editing commands a key press asks for (Cmd+A is `selectAll`), which
36 * Chromium runs only for CDP keys. Clipboard commands stay out: they would read
37 * or replace the person's clipboard.
38 */
39const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]);
40​
41const CROSS_SITE_FOCUS_MESSAGE =
42 "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first.";
43​
44const ARROW_KEYS: Record<string, string> = {
45 ArrowUp: "Up",
46 ArrowDown: "Down",
47 ArrowLeft: "Left",
48 ArrowRight: "Right",
49};
50const NAMED_KEYS = new Set([
51 "Backspace",
52 "Tab",
53 "Enter",
54 "Escape",
55 "Delete",
56 "Insert",
57 "Home",
58 "End",
59 "PageUp",
60 "PageDown",
61 "Shift",
62 "Control",
63 "Alt",
64 "Meta",
65 "CapsLock",
66 "NumLock",
67 "ScrollLock",
68 "PrintScreen",
69]);
70const MODIFIER_BITS = [
71 [1, "alt"],
72 [2, "control"],
73 [4, "meta"],
74 [8, "shift"],
75] as const;
76​
77/** Electron's accelerator name for a DOM key value, or null when it has none. */
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/**
85 * The Electron key events for one CDP `Input.dispatchKeyEvent`. Electron
86 * derives key, code, and a char's text from `keyCode`, so typed text travels
87 * as `char` events of its own.
88 */
89export const toKeyboardInputEvents = (
90 params: Record<string, unknown>,
91): Array<Electron.KeyboardInputEvent> => {
92 const bits = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
93 const modifiers = MODIFIER_BITS.flatMap(([bit, name]) => (bits & bit ? [name] : []));
94 const text = typeof params["text"] === "string" ? params["text"] : "";
95 const chars = [...text].map((char) => ({ type: "char" as const, keyCode: char, modifiers }));
96 const keyCode = keyCodeFor(typeof params["key"] === "string" ? params["key"] : "");
97 switch (params["type"]) {
98 case "keyDown":
99 return [...(keyCode ? [{ type: "rawKeyDown" as const, keyCode, modifiers }] : []), ...chars];
100 case "rawKeyDown":
101 case "keyUp":
102 return keyCode ? [{ type: params["type"], keyCode, modifiers }] : [];
103 case "char":
104 return chars;
105 default:
106 return [];
107 }
108};
109​
110const evaluate = async (debuggee: Electron.Debugger, expression: string) => {
111 const reply = (await debuggee.sendCommand("Runtime.evaluate", {
112 expression,
113 returnByValue: true,
114 })) as { readonly result?: { readonly value?: unknown } };
115 return reply.result?.value;
116};
117​
118/** Sends one command to the guest's page, keeping key and text input inside it. */
119export const sendPageCommand = async (
120 webContents: Electron.WebContents,
121 debuggee: Electron.Debugger,
122 method: string,
123 params: Record<string, unknown>,
124): Promise<unknown> => {
125 if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) {
126 return debuggee.sendCommand(method, params);
127 }
128 if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) {
129 throw new Error(CROSS_SITE_FOCUS_MESSAGE);
130 }
131 switch (method) {
132 case "Input.insertText":
133 await webContents.insertText(typeof params["text"] === "string" ? params["text"] : "");
134 return {};
135 case "Input.dispatchKeyEvent": {
136 for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event);
137 const commands = Array.isArray(params["commands"])
138 ? params["commands"].filter((command) => EDITING_COMMANDS.has(command))
139 : [];
140 // Runs after the page handles the keys, so the reply also waits for them.
141 await evaluate(
142 debuggee,
143 `(() => { const doc = ${FOCUSED_DOCUMENT}; for (const name of ${JSON.stringify(commands)}) doc?.execCommand(name); return 0; })()`,
144 );
145 return {};
146 }
147 default:
148 throw new Error(`${method} needs the preview to have focus.`);
149 }
150};