fix(desktop): keep preview keystrokes out of the composer #11354
Mergedmaria-rcksmerged 11 commits into
main fromrefs/pull/11354/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -203,0 +211,21 @@211+ let element = document.activeElement;212+ while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;213+ if (!element) return;214+ const event = ${JSON.stringify(event)};215+ try {216+ if (!element.dispatchEvent(new KeyboardEvent("keydown", event))) return;217+ for (const command of ${JSON.stringify(sequence.commands ?? [])}) {218+ const inputType = command === "deleteToBeginningOfLine" ? "deleteSoftLineBackward"219+ : command === "undo" ? "historyUndo"220+ : command === "redo" ? "historyRedo" : null;221+ // execCommand emits input without beforeinput. Let controlled editors222+ // perform the edit before applying the browser's default operation.223+ if (inputType && !element.dispatchEvent(new InputEvent("beforeinput", {224+ inputType, bubbles: true, cancelable: true, composed: true,225+ }))) continue;226+ const selection = document.getSelection();227+ if (command === "deleteToBeginningOfLine") {228+ const collapsed = typeof element.selectionStart === "number"229+ ? element.selectionStart === element.selectionEnd230+ : selection?.isCollapsed;231+ if (collapsed) selection?.modify("extend", "backward", "lineboundary");apps/desktop/src/preview/Manager.ts lines 3934 to 3945OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3955,10 +3933,13 @@3955- yield* attempt(3956- { operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },3957- () => wc.focus(),3958- );3959- yield* send("Page.bringToFront");39603933 yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });39613934 yield* expectAgentInput(tabId, keySequence.signal);3962- keyDownAttempted = true;3963- yield* send("Input.dispatchKeyEvent", keySequence.keyDown);3964- }).pipe(Effect.ensuring(releaseInput));3935+ if (keySequence.commands?.length) {3936+ yield* evaluateWithDebugger(3937+ tabId,3938+ send,3939+ previewAutomationEditingCommandExpression(input, keySequence),3940+ true,3941+ );3942+ return;3943+ }3944+ yield* attempt(3945+ { operation: "automationPress.sendInputEvent", tabId, webContentsId: wc.id },apps/desktop/src/preview/PreviewKeyboard.ts line 264Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -203,0 +191,21 @@191+export function previewAutomationEditingCommandExpression(192+ input: PreviewAutomationPressInput,193+ sequence: PreviewAutomationKeySequence,194+): string {195+ const definition = resolveKeyDefinition(input);196+ const event = {197+ key: definition.key,198+ code: definition.code,199+ keyCode: definition.keyCode,200+ which: definition.keyCode,201+ location: definition.location ?? 0,202+ altKey: input.modifiers?.includes("Alt") ?? false,203+ ctrlKey: input.modifiers?.includes("Control") ?? false,204+ metaKey: input.modifiers?.includes("Meta") ?? false,205+ shiftKey: input.modifiers?.includes("Shift") ?? false,206+ bubbles: true,207+ cancelable: true,208+ composed: true,209+ };210+ return `(() => {211+ let element = document.activeElement;
- @@ -3959,6 +3933,17 @@3959- yield* send("Page.bringToFront");39603933 yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });39613934 yield* expectAgentInput(tabId, keySequence.signal);3962- keyDownAttempted = true;3963- yield* send("Input.dispatchKeyEvent", keySequence.keyDown);3964- }).pipe(Effect.ensuring(releaseInput));3935+ if (keySequence.commands?.length) {3936+ yield* evaluateWithDebugger(3937+ tabId,3938+ send,3939+ previewAutomationEditingCommandExpression(input, keySequence),3940+ true,3941+ );3942+ return;3943+ }3944+ yield* attempt(3945+ { operation: "automationPress.sendInputEvent", tabId, webContentsId: wc.id },3946+ () => {3947+ try {3948+ wc.sendInputEvent(keySequence.keyDown);3949+ if (keySequence.char) wc.sendInputEvent(keySequence.char);
- apps/desktop/src/preview/PreviewKeyboard.ts lines 245 to 246OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -202,0 +226,21 @@226+ const inputType = command === "deleteToBeginningOfLine" ? "deleteSoftLineBackward"227+ : command === "undo" ? "historyUndo"228+ : command === "redo" ? "historyRedo" : null;229+ // execCommand emits input without beforeinput. Let controlled editors230+ // perform the edit before applying the browser's default operation.231+ if (inputType && !element.dispatchEvent(new InputEvent("beforeinput", {232+ inputType, bubbles: true, cancelable: true, composed: true,233+ }))) continue;234+ const selection = document.getSelection();235+ if (command === "deleteToBeginningOfLine") {236+ const collapsed = typeof element.selectionStart === "number"237+ ? element.selectionStart === element.selectionEnd238+ : selection?.isCollapsed;239+ if (collapsed) selection?.modify("extend", "backward", "lineboundary");240+ document.execCommand("delete");241+ } else if (command.startsWith("moveTo")) {242+ const selectionElement = selection?.anchorNode?.nodeType === Node.ELEMENT_NODE243+ ? selection.anchorNode : selection?.anchorNode?.parentElement;244+ const editable = element.isContentEditable || selectionElement?.isContentEditable ||245+ ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) &&246+ !element.readOnly && !element.disabled);
- @@ -202,0 +250,21 @@250+ while (scrollable && !(scrollable.scrollHeight > scrollable.clientHeight &&251+ /^(auto|scroll|overlay)$/.test(getComputedStyle(scrollable).overflowY))) {252+ scrollable = scrollable.parentElement ?? scrollable.getRootNode().host;253+ }254+ scrollable ??= document.scrollingElement;255+ if (scrollable) scrollable.scrollTop = command === "moveToBeginningOfDocument"256+ ? 0 : scrollable.scrollHeight;257+ continue;258+ }259+ const direction = command.includes("Beginning") ? "backward"260+ : command.includes("Left") ? "left"261+ : command.includes("Right") ? "right" : "forward";262+ selection?.modify(263+ command.endsWith("AndModifySelection") ? "extend" : "move",264+ direction,265+ command.includes("Document") ? "documentboundary" : "lineboundary",266+ );267+ if (element instanceof HTMLInputElement && element.selectionStart !== null) {268+ if (command.includes("Left") || command.includes("Beginning")) element.scrollLeft = 0;269+ else element.scrollLeft = element.scrollWidth;270+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -3914,0 +4090,21 @@4090+ ...context,4091+ cause: new Error("The focused preview iframe context is unavailable."),4092+ });4093+ contextId = world.executionContextId;4094+ }4095+ }4096+ // Main-frame CDP keyboard input can retarget to the desktop. Only an4097+ // explicitly attached descendant renderer may receive these packets.4098+ if (!sessionId) return false;4099+ const targetSessionId = sessionId;4100+ const keys = makePreviewAutomationFrameKeySequence(input, { isMac: hostPlatform === "darwin" });4101+ yield* Effect.acquireRelease(Effect.void, () =>4102+ sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }, targetSessionId).pipe(4103+ Effect.ignore,4104+ ),4105+ );4106+ yield* send("Emulation.setFocusEmulationEnabled", { enabled: true }, targetSessionId);4107+ yield* Effect.acquireRelease(Effect.void, () =>4108+ sendCleanup("Input.dispatchKeyEvent", keys.keyUp, targetSessionId).pipe(Effect.ignore),4109+ );4110+ yield* send("Input.dispatchKeyEvent", keys.keyDown, targetSessionId);@@ -3914,0 +3951,21 @@3951+ ),3952+ );3953+ yield* Effect.gen(function* () {3954+ for (const frame of frames) {3955+ yield* checkControl;3956+ yield* Effect.tryPromise({3957+ try: (_signal) =>3958+ frame.executeJavaScript(`(() => {3959+ const receiptKey = ${receiptKey};3960+ const signal = ${signalJson};3961+ let settle;3962+ const promise = new Promise(resolve => { settle = resolve; });3963+ const finish = delivered => {3964+ window.removeEventListener("keyup", onKeyUp, true);3965+ window.removeEventListener("pagehide", onPageHide, true);3966+ settle(delivered);3967+ };3968+ const onKeyUp = event => {3969+ if (event.isTrusted && event.key === signal.key && event.code === signal.code) finish(true);3970+ };3971+ const onPageHide = () => finish(false);apps/desktop/src/preview/Manager.ts line 4231Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3960,5 +4226,17 @@4226+ return activeChild;4227+ },4228+ );4229+ }4230+ }39604231 yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });3961- yield* expectAgentInput(tabId, keySequence.signal);3962- keyDownAttempted = true;3963- yield* send("Input.dispatchKeyEvent", keySequence.keyDown);3964- }).pipe(Effect.ensuring(releaseInput));4232+ yield* withNativeKeyReceipt(4233+ tabId,4234+ wc,4235+ keySequence.signal,4236+ Effect.gen(function* () {4237+ yield* expectAgentInput(tabId, keySequence.signal);4238+ yield* attempt(4239+ { operation: "automationPress.sendInputEvent", tabId, webContentsId: wc.id },4240+ () => {4241+ try {4242+ wc.sendInputEvent(keySequence.keyDown);
- apps/desktop/src/preview/Manager.ts lines 4085 to 4098Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3914,0 +4073,21 @@4073+ sendCleanup("Target.detachFromTarget", { sessionId: attachedSessionId }).pipe(4074+ Effect.ignore,4075+ ),4076+ );4077+ yield* checkControl;4078+ contextId = undefined;4079+ } else {4080+ const world = (yield* send(4081+ "Page.createIsolatedWorld",4082+ {4083+ frameId,4084+ worldName: "t3-preview-key-target",4085+ },4086+ sessionId,4087+ )) as { executionContextId?: number };4088+ if (typeof world.executionContextId !== "number")4089+ return yield* new PreviewOperationError({4090+ ...context,4091+ cause: new Error("The focused preview iframe context is unavailable."),4092+ });4093+ contextId = world.executionContextId;@@ -3964,0 +4200,21 @@4200+ wc,4201+ keySequence.signal,4202+ Effect.gen(function* () {4203+ yield* expectAgentInput(tabId, keySequence.signal);4204+ yield* attempt(4205+ { operation: "automationPress.sendInputEvent", tabId, webContentsId: wc.id },4206+ () => {4207+ try {4208+ wc.sendInputEvent(keySequence.keyDown);4209+ if (keySequence.char) wc.sendInputEvent(keySequence.char);4210+ } finally {4211+ wc.sendInputEvent(keySequence.keyUp);4212+ }4213+ },4214+ );4215+ }),4216+ checkControl,4217+ );4218+ }).pipe(4219+ Effect.ensuring(4220+ sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(Effect.ignore),
- @@ -3959,0 +4176,21 @@4176+ // and selection across focus handlers without focusing the desktop.4177+ yield* Effect.acquireUseRelease(4178+ evaluate(`(() => {4179+ let element = document.activeElement;4180+ while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;4181+ const selection = document.getSelection();4182+ const ranges = Array.from({ length: selection?.rangeCount ?? 0 }, (_, i) => selection.getRangeAt(i).cloneRange());4183+ const start = element?.selectionStart;4184+ const end = element?.selectionEnd;4185+ const direction = element?.selectionDirection;4186+ globalThis[${selectionKey}] = () => {4187+ element?.focus({ preventScroll: true });4188+ if (typeof start === "number") element.setSelectionRange(start, end, direction);4189+ else { selection?.removeAllRanges(); ranges.forEach(range => selection?.addRange(range)); }4190+ };4191+ })()`),4192+ () =>4193+ Effect.gen(function* () {4194+ yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });4195+ yield* evaluate(`globalThis[${selectionKey}]();${expression}`);4196+ }),apps/desktop/src/preview/PreviewKeyboard.ts lines 261 to 267OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -203,0 +247,21 @@247+ composed: true,248+ };249+ return `(async () => {250+ let element = document.activeElement;251+ while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;252+ if (!element) return;253+ const event = ${JSON.stringify(event)};254+ try {255+ if (!element.dispatchEvent(new KeyboardEvent("keydown", event))) return;256+ for (const command of ${JSON.stringify(sequence.commands ?? [])}) {257+ // Chromium disables DOM execCommand("paste"). Read the permitted browser258+ // clipboard and let the page's paste handler consume its original formats.259+ if (command === "paste") {260+ const transfer = new DataTransfer();261+ for (const item of await navigator.clipboard.read()) {262+ for (const type of item.types) {263+ const blob = await item.getType(type);264+ if (type.startsWith("text/")) transfer.setData(type, await blob.text());265+ else transfer.items.add(new File([blob], "clipboard", { type }));266+ }267+ }
- apps/desktop/src/preview/PreviewKeyboard.ts lines 295 to 296Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -203,0 +258,21 @@258+ // Main-process clipboard reads also work on insecure HTTP previews.259+ // Let the page's paste handler consume the original MIME formats.260+ if (command === "paste") {261+ const transfer = new DataTransfer();262+ for (const { type, data } of ${JSON.stringify(clipboardData)}) {263+ if (type.startsWith("text/")) transfer.setData(type, data);264+ else {265+ const bytes = Uint8Array.from(atob(data), character => character.charCodeAt(0));266+ transfer.items.add(new File([bytes], "clipboard", { type }));267+ }268+ }269+ if (!element.dispatchEvent(new ClipboardEvent("paste", {270+ clipboardData: transfer, bubbles: true, cancelable: true, composed: true,271+ }))) continue;272+ const text = transfer.getData("text/plain");273+ if (!element.dispatchEvent(new InputEvent("beforeinput", {274+ inputType: "insertFromPaste", data: text, dataTransfer: transfer,275+ bubbles: true, cancelable: true, composed: true,276+ }))) continue;277+ const html = element.isContentEditable ? transfer.getData("text/html") : "";278+ document.execCommand(html ? "insertHTML" : "insertText", false, html || text);
maria-rcks merged thise816064
maria-rcks closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed