From 8dc979ec2f350118b2332414be2570bb8381f289 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 14:12:01 +0700 Subject: [PATCH] Shift+Tab in the iPad composer no longer inserts a tab (#9561) * Shift+Tab in the iPad composer no longer inserts a tab On iPad with a hardware keyboard, Shift+Tab in the composer cycled the agent mode and the composer also inserted a tab. The native window reports presses to JavaScript after the text control has handled them, so the shortcut pipeline cannot prevent the default. The hardware keyboard source now claims, up front, the Shift and Option shortcuts whose binding is active in the current focus scope, and recomputes the claims when the focus surface or command center changes. iOS registers them as key commands so the text control never sees them. The window still emits the press, so the shortcut runs once. Closes #9468 * Claim every step of a rebound chord shortcut A binding rebound to a chord such as Mod+J Shift+Tab only claimed its first step, so finishing the chord in the iPad composer still typed a tab. * Claim only the first step of a chord shortcut Claiming every step of a chord held keys like Shift+A for as long as the chord's binding was active, so the composer could no longer type a capital A. A later step is a shortcut only while its chord is in progress. * Expect no Option claims now that iPad tab switching uses Cmd+Shift Main moved tab switching on Apple platforms with desktop bindings to Cmd+Shift+[ / ], which text controls do not type, so the default claims are only Shift+Tab while the composer is focused. --- docs/keyboard-shortcuts.md | 13 +- .../ios/PaseoHardwareKeyboardModule.swift | 63 ++++++++- .../src/keyboard/internal/focus-surfaces.ts | 18 ++- .../src/keyboard/internal/sources/contract.ts | 2 + .../internal/sources/electron-browser.test.ts | 8 +- .../internal/sources/hardware.android.ts | 5 +- .../keyboard/internal/sources/hardware.ios.ts | 6 +- .../src/keyboard/internal/sources/hardware.ts | 7 + .../src/keyboard/internal/sources/index.ts | 24 ++-- .../keyboard/internal/sources/index.web.ts | 3 +- .../src/keyboard/internal/sources/native.ts | 105 +++++++++++---- .../keyboard/native-shortcuts.browser.test.ts | 1 + .../app/src/keyboard/native-shortcuts.test.ts | 123 +++++++++++++++--- packages/app/src/keyboard/use-shortcuts.ts | 6 +- .../app/src/lib/overlay-root.browser.test.tsx | 1 + 15 files changed, 325 insertions(+), 60 deletions(-) diff --git a/docs/keyboard-shortcuts.md b/docs/keyboard-shortcuts.md index dd93f03b4..21d0152d4 100644 --- a/docs/keyboard-shortcuts.md +++ b/docs/keyboard-shortcuts.md @@ -20,9 +20,16 @@ settings the native composer does not implement. ## Native sources -Use the iOS window press stream for hardware keys. `UIKeyCommand` only takes keys -that must bypass the focused text control: composer Return and the top overlay's -Enter and arrows. Keep the stream as the sole shortcut emitter: a command-owned +Use the iOS window press stream for hardware keys. The stream reaches JavaScript +after the focused text control has already handled the press, so the pipeline's +`preventDefault` cannot stop a key from typing. A key the text control would type +must be claimed up front. `UIKeyCommand` takes only those keys: composer Return, the +top overlay's Enter and arrows, and the Shift or Option shortcuts whose binding is +active in the current focus scope, such as Shift+Tab in the composer. +`sources/native.ts` computes the claims from the published bindings and recomputes +them when the focus scope changes. Cmd and Ctrl combos are never claimed, because +text controls do not type them. Android takes no claims: a focused `EditText` +types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned press is still observed by the window. The source spike used an iPad Pro 11-inch (M4) simulator on iOS 18.6 with a diff --git a/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift b/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift index 446e1d98c..b6d463742 100644 --- a/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift +++ b/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift @@ -8,6 +8,7 @@ private let hardwareShortcutEventName = "onHardwareKeyboardShortcut" private weak var activeModule: PaseoHardwareKeyboardModule? private var isHardwareSubmitEnabled = false private var overlayKeys: Set = [] +private var claimedShortcuts: [ClaimedShortcut] = [] /// UIKit spells non-character keys as sentinel input strings rather than as the /// character they would type. JS sends the DOM `code` and the mapping lives @@ -19,6 +20,42 @@ private let namedKeyInputs: [String: String] = [ "Enter": "\r", ] +/// A shortcut the window takes from the focused text control: Shift+Tab would +/// otherwise insert a tab, and Option+Shift+[ would type a quote. +private struct ClaimedShortcut { + let input: String + let modifierFlags: UIKeyModifierFlags +} + +struct ClaimedShortcutRecord: Record { + @Field var code: String = "" + @Field var shift: Bool = false + @Field var alt: Bool = false +} + +private let claimableKeyInputs: [String: String] = [ + "Tab": "\t", "Space": " ", "Enter": "\r", "Escape": UIKeyCommand.inputEscape, + "ArrowUp": UIKeyCommand.inputUpArrow, "ArrowDown": UIKeyCommand.inputDownArrow, + "ArrowLeft": UIKeyCommand.inputLeftArrow, "ArrowRight": UIKeyCommand.inputRightArrow, + "Minus": "-", "Equal": "=", "BracketLeft": "[", "BracketRight": "]", "Backslash": "\\", + "Semicolon": ";", "Quote": "'", "Backquote": "`", "Comma": ",", "Period": ".", "Slash": "/", +] + +/// UIKit matches a key command against the unmodified character, so +/// Option+Shift+[ is registered as "[" with both modifier flags. +private func claimedShortcut(_ record: ClaimedShortcutRecord) -> ClaimedShortcut? { + let code = record.code + let input: String? + if code.count == 4 && code.hasPrefix("Key") { input = code.suffix(1).lowercased() } + else if code.count == 6 && code.hasPrefix("Digit") { input = String(code.suffix(1)) } + else { input = claimableKeyInputs[code] } + guard let input else { return nil } + var modifierFlags: UIKeyModifierFlags = [] + if record.shift { modifierFlags.insert(.shift) } + if record.alt { modifierFlags.insert(.alternate) } + return ClaimedShortcut(input: input, modifierFlags: modifierFlags) +} + /// Whether the first responder is mid-IME-composition. /// /// A committing key has to stay out of the way while a CJK candidate is being @@ -62,6 +99,14 @@ public class PaseoHardwareKeyboardModule: Module { } } + Function("setClaimedShortcuts") { (shortcuts: [ClaimedShortcutRecord]) in + let claimed = shortcuts.compactMap(claimedShortcut) + DispatchQueue.main.async { + claimedShortcuts = claimed + UIMenuSystem.main.setNeedsRebuild() + } + } + OnDestroy { self.keyboardObservers.forEach(NotificationCenter.default.removeObserver) self.keyboardObservers = [] @@ -69,6 +114,7 @@ public class PaseoHardwareKeyboardModule: Module { activeModule = nil isHardwareSubmitEnabled = false overlayKeys = [] + claimedShortcuts = [] } } } @@ -139,7 +185,10 @@ public final class PaseoHardwareKeyboardWindow: UIWindow { { commands.append(makeSubmitCommand()) } - if !isComposingText() { commands.append(contentsOf: overlayKeys.compactMap(makeShortcutCommand)) } + if !isComposingText() { + commands.append(contentsOf: overlayKeys.compactMap(makeShortcutCommand)) + commands.append(contentsOf: claimedShortcuts.map(makeClaimedCommand)) + } return commands } @@ -172,6 +221,18 @@ public final class PaseoHardwareKeyboardWindow: UIWindow { return command } + /// The window's press stream still emits the shortcut; the command only keeps + /// the key away from the text control. + private func makeClaimedCommand(_ shortcut: ClaimedShortcut) -> UIKeyCommand { + let command = UIKeyCommand( + input: shortcut.input, + modifierFlags: shortcut.modifierFlags, + action: #selector(handleHardwareKeyboardShortcut(_:)) + ) + if #available(iOS 15.0, *) { command.wantsPriorityOverSystemBehavior = true } + return command + } + @objc private func handleHardwareKeyboardSubmit(_ sender: UIKeyCommand) { guard canSubmitCurrentTextInput() else { diff --git a/packages/app/src/keyboard/internal/focus-surfaces.ts b/packages/app/src/keyboard/internal/focus-surfaces.ts index 5bdeb6fa0..e13526176 100644 --- a/packages/app/src/keyboard/internal/focus-surfaces.ts +++ b/packages/app/src/keyboard/internal/focus-surfaces.ts @@ -4,20 +4,32 @@ export type KeyboardFocusSurface = "message-input" | "terminal"; export function createKeyboardFocusScope(hasEditableFocus: () => boolean = () => false) { const surfaces = new Map(); + const listeners = new Set<() => void>(); + const notify = () => { + for (const listener of listeners) listener(); + }; return { declare(surface: KeyboardFocusSurface) { const token = Symbol(surface); surfaces.set(token, surface); + notify(); return () => { - surfaces.delete(token); + if (surfaces.delete(token)) notify(); }; }, - resolve(commandCenterOpen: boolean): KeyboardFocusScope { + /** Pass `editableFocused` to resolve for a text control that is not a declared surface. */ + resolve(commandCenterOpen: boolean, editableFocused = hasEditableFocus()): KeyboardFocusScope { if (commandCenterOpen) return "command-center"; - let focused: KeyboardFocusScope = hasEditableFocus() ? "editable" : "other"; + let focused: KeyboardFocusScope = editableFocused ? "editable" : "other"; for (const surface of surfaces.values()) focused = surface; return focused; }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, }; } export const focusSurfaces = createKeyboardFocusScope(hasFocusedTextInput); diff --git a/packages/app/src/keyboard/internal/sources/contract.ts b/packages/app/src/keyboard/internal/sources/contract.ts index 886dbc354..69de22f09 100644 --- a/packages/app/src/keyboard/internal/sources/contract.ts +++ b/packages/app/src/keyboard/internal/sources/contract.ts @@ -10,6 +10,7 @@ export interface KeyboardSourceHandlers { keyUp(event: KeyboardInputEvent): void; blur(): void; commandCenterOpen(): boolean; + subscribeCommandCenter(listener: () => void): () => void; } export function nativeKeyboardInput( event: KeyboardInputEvent, @@ -23,5 +24,6 @@ export interface KeyboardPolicyInput { bindings: readonly ParsedShortcutBinding[]; chordState?: ChordState; isMac: boolean; + usesDesktopBindings: boolean; enabled: boolean; } diff --git a/packages/app/src/keyboard/internal/sources/electron-browser.test.ts b/packages/app/src/keyboard/internal/sources/electron-browser.test.ts index abcc98b7f..8ac3ac994 100644 --- a/packages/app/src/keyboard/internal/sources/electron-browser.test.ts +++ b/packages/app/src/keyboard/internal/sources/electron-browser.test.ts @@ -366,7 +366,13 @@ describe("Electron guest source through shared resolution", () => { }, captureFocusRestore: (id) => restored.push(id), }, - { keyDown: pipeline.keyDown, keyUp() {}, blur() {}, commandCenterOpen: () => false }, + { + keyDown: pipeline.keyDown, + keyUp() {}, + blur() {}, + commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, + }, ); receive({ browserId: "tab-1", diff --git a/packages/app/src/keyboard/internal/sources/hardware.android.ts b/packages/app/src/keyboard/internal/sources/hardware.android.ts index cfe7a15cb..b0e0d4115 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.android.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.android.ts @@ -1,5 +1,5 @@ import { requireNativeModule } from "expo-modules-core"; -import type { HardwareKeyboardEvent } from "./hardware"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeyboardModule { getHardwareKeyboardPresent(): boolean; addListener(event: "onHardwareKeyboardPresenceChanged", handler: () => void): { remove(): void }; @@ -19,6 +19,9 @@ export function subscribeHardwareKeyboard( export function setHardwareKeyboardOverlayKeys(keys: readonly string[]): void { module.setOverlayKeys(keys); } +// A focused Android EditText types nothing for Tab, Shift+Tab or Alt+Shift+[, +// so there is no character to take from it. +export function setHardwareKeyboardClaimedShortcuts(_shortcuts: readonly ClaimedShortcut[]): void {} export function getHardwareKeyboardPresent(): boolean { return module.getHardwareKeyboardPresent(); diff --git a/packages/app/src/keyboard/internal/sources/hardware.ios.ts b/packages/app/src/keyboard/internal/sources/hardware.ios.ts index cfe7a15cb..2745b51ba 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.ios.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.ios.ts @@ -1,9 +1,10 @@ import { requireNativeModule } from "expo-modules-core"; -import type { HardwareKeyboardEvent } from "./hardware"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeyboardModule { getHardwareKeyboardPresent(): boolean; addListener(event: "onHardwareKeyboardPresenceChanged", handler: () => void): { remove(): void }; setOverlayKeys(keys: readonly string[]): void; + setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void; addListener( event: "onHardwareKeyboardShortcut", handler: (event: HardwareKeyboardEvent) => void, @@ -19,6 +20,9 @@ export function subscribeHardwareKeyboard( export function setHardwareKeyboardOverlayKeys(keys: readonly string[]): void { module.setOverlayKeys(keys); } +export function setHardwareKeyboardClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void { + module.setClaimedShortcuts(shortcuts); +} export function getHardwareKeyboardPresent(): boolean { return module.getHardwareKeyboardPresent(); diff --git a/packages/app/src/keyboard/internal/sources/hardware.ts b/packages/app/src/keyboard/internal/sources/hardware.ts index c6631886d..33afb7eab 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.ts @@ -3,12 +3,19 @@ export interface HardwareKeyboardEvent extends KeyboardShortcutInput { isComposing: boolean; phase: "down" | "up"; } +/** A shortcut the native window takes from the focused text control, by DOM `code`. */ +export interface ClaimedShortcut { + code: string; + shift: boolean; + alt: boolean; +} export function subscribeHardwareKeyboard( _handler: (event: HardwareKeyboardEvent) => void, ): () => void { return () => {}; } export function setHardwareKeyboardOverlayKeys(_keys: readonly string[]): void {} +export function setHardwareKeyboardClaimedShortcuts(_shortcuts: readonly ClaimedShortcut[]): void {} export function getHardwareKeyboardPresent(): boolean { return false; diff --git a/packages/app/src/keyboard/internal/sources/index.ts b/packages/app/src/keyboard/internal/sources/index.ts index 5d886b979..570251a08 100644 --- a/packages/app/src/keyboard/internal/sources/index.ts +++ b/packages/app/src/keyboard/internal/sources/index.ts @@ -1,11 +1,19 @@ -import type { KeyboardSourceHandlers } from "./contract"; -import { setHardwareKeyboardOverlayKeys, subscribeHardwareKeyboard } from "./hardware"; -import { attachHardwareKeyboardSource } from "./native"; +import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract"; +import { + setHardwareKeyboardClaimedShortcuts, + setHardwareKeyboardOverlayKeys, + subscribeHardwareKeyboard, +} from "./hardware"; +import { createHardwareKeyboardSource } from "./native"; +const hardwareKeyboard = createHardwareKeyboardSource({ + subscribe: subscribeHardwareKeyboard, + setOverlayKeys: setHardwareKeyboardOverlayKeys, + setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts, +}); export function attachKeyboardSources(handlers: KeyboardSourceHandlers): () => void { - return attachHardwareKeyboardSource( - { subscribe: subscribeHardwareKeyboard, setOverlayKeys: setHardwareKeyboardOverlayKeys }, - handlers, - ); + return hardwareKeyboard.attach(handlers); } -export function publishKeyboardPolicy(_input: import("./contract").KeyboardPolicyInput): void {} +export function publishKeyboardPolicy(input: KeyboardPolicyInput): void { + hardwareKeyboard.publishPolicy(input); +} diff --git a/packages/app/src/keyboard/internal/sources/index.web.ts b/packages/app/src/keyboard/internal/sources/index.web.ts index da6023be5..e915c3818 100644 --- a/packages/app/src/keyboard/internal/sources/index.web.ts +++ b/packages/app/src/keyboard/internal/sources/index.web.ts @@ -1,4 +1,3 @@ -import { usesDesktopBindings } from "../conventions"; import { getDesktopHost } from "@/desktop/host"; import { getResidentBrowserWebview } from "@/desktop/browser/resident-webviews"; import { setCommandCenterFocusRestoreElement } from "@/utils/command-center-focus-restore"; @@ -26,7 +25,7 @@ export function attachKeyboardSources(handlers: KeyboardSourceHandlers): () => v } export function publishKeyboardPolicy(input: import("./contract").KeyboardPolicyInput): void { const policy = input.enabled - ? buildBrowserKeyboardPolicy({ ...input, usesDesktopBindings: usesDesktopBindings }) + ? buildBrowserKeyboardPolicy(input) : { menuPrefixes: [], prefixes: [] }; void getDesktopHost()?.browser?.setShortcutPolicy?.(policy); } diff --git a/packages/app/src/keyboard/internal/sources/native.ts b/packages/app/src/keyboard/internal/sources/native.ts index 995e9df49..9d76abe0a 100644 --- a/packages/app/src/keyboard/internal/sources/native.ts +++ b/packages/app/src/keyboard/internal/sources/native.ts @@ -1,31 +1,92 @@ +import { matchesKeyboardShortcutContext } from "../../keyboard-shortcuts"; import { focusSurfaces } from "../focus-surfaces"; import { overlays } from "../overlays"; -import { nativeKeyboardInput, type KeyboardSourceHandlers } from "./contract"; -import type { HardwareKeyboardEvent } from "./hardware"; +import { + nativeKeyboardInput, + type KeyboardPolicyInput, + type KeyboardSourceHandlers, +} from "./contract"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeySource { subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void; setOverlayKeys(keys: readonly string[]): void; + setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void; } -export function attachHardwareKeyboardSource( - source: HardwareKeySource, - handlers: KeyboardSourceHandlers, -): () => void { - const updateKeys = () => source.setOverlayKeys(overlays.getKeys()); - updateKeys(); - const unsubscribeOverlays = overlays.subscribe(updateKeys); - const unsubscribeHardware = source.subscribe((input) => { - const event = { ...input, preventDefault() {}, stopPropagation() {} }; - if (input.phase === "up") { - handlers.keyUp(event); - return; + +const DIGIT_CODES = Array.from({ length: 9 }, (_, index) => `Digit${index + 1}`); + +/** + * The shortcuts a focused text control would otherwise type or act on. + * + * The native window observes every press but cannot wait for the pipeline to + * decide, so it has to claim these keys up front: without a claim, Shift+Tab + * cycles the agent mode and the composer also inserts a tab. Cmd and Ctrl + * combos do not type, and the platform's own editing combos stay with the text + * control through `editable: false`. Unmodified keys belong to overlays and the + * composer's Return. + */ +function claimedShortcuts( + policy: KeyboardPolicyInput | null, + commandCenterOpen: boolean, +): ClaimedShortcut[] { + if (!policy?.enabled) return []; + const context = { + isMac: policy.isMac, + usesDesktopBindings: policy.usesDesktopBindings, + commandCenterOpen, + focusScope: focusSurfaces.resolve(commandCenterOpen, true), + }; + const claimed = new Map(); + for (const binding of policy.bindings) { + const combo = binding.parsedChord[0]; + if (!combo || binding.preventDefault === false) continue; + if (combo.meta || combo.ctrl || combo.mod || !(combo.shift || combo.alt)) continue; + if (!matchesKeyboardShortcutContext(binding.when, context)) continue; + const shift = combo.shift === true; + const alt = combo.alt === true; + for (const code of combo.code === "Digit" ? DIGIT_CODES : [combo.code]) { + claimed.set(`${code}:${shift}:${alt}`, { code, shift, alt }); } - handlers.keyDown( - nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())), - ); - }); - return () => { - unsubscribeHardware(); - unsubscribeOverlays(); - source.setOverlayKeys([]); + } + return [...claimed.values()]; +} + +export function createHardwareKeyboardSource(source: HardwareKeySource) { + let policy: KeyboardPolicyInput | null = null; + let updateClaims = () => {}; + return { + publishPolicy(next: KeyboardPolicyInput) { + policy = next; + updateClaims(); + }, + attach(handlers: KeyboardSourceHandlers): () => void { + const updateKeys = () => source.setOverlayKeys(overlays.getKeys()); + updateClaims = () => + source.setClaimedShortcuts(claimedShortcuts(policy, handlers.commandCenterOpen())); + updateKeys(); + updateClaims(); + const unsubscribeOverlays = overlays.subscribe(updateKeys); + const unsubscribeFocus = focusSurfaces.subscribe(() => updateClaims()); + const unsubscribeCommandCenter = handlers.subscribeCommandCenter(() => updateClaims()); + const unsubscribeHardware = source.subscribe((input) => { + const event = { ...input, preventDefault() {}, stopPropagation() {} }; + if (input.phase === "up") { + handlers.keyUp(event); + return; + } + handlers.keyDown( + nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())), + ); + }); + return () => { + unsubscribeHardware(); + unsubscribeFocus(); + unsubscribeCommandCenter(); + unsubscribeOverlays(); + updateClaims = () => {}; + source.setOverlayKeys([]); + source.setClaimedShortcuts([]); + }; + }, }; } diff --git a/packages/app/src/keyboard/native-shortcuts.browser.test.ts b/packages/app/src/keyboard/native-shortcuts.browser.test.ts index 004eb912b..22bd6e16a 100644 --- a/packages/app/src/keyboard/native-shortcuts.browser.test.ts +++ b/packages/app/src/keyboard/native-shortcuts.browser.test.ts @@ -25,6 +25,7 @@ describe("DOM source adapter", () => { keyUp() {}, blur() {}, commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, }); const event = new KeyboardEvent("keydown", { key: "j", diff --git a/packages/app/src/keyboard/native-shortcuts.test.ts b/packages/app/src/keyboard/native-shortcuts.test.ts index e155fa2ba..d4c4edc24 100644 --- a/packages/app/src/keyboard/native-shortcuts.test.ts +++ b/packages/app/src/keyboard/native-shortcuts.test.ts @@ -130,7 +130,7 @@ describe("hardware source adapter", () => { it.each([true, false])( "delivers hardware down/up and declared focus with mac=%s", async (isMac) => { - const { attachHardwareKeyboardSource } = await import("./internal/sources/native"); + const { createHardwareKeyboardSource } = await import("./internal/sources/native"); const { focusSurfaces } = await import("./internal/focus-surfaces"); const actions: string[] = []; const releases: string[] = []; @@ -148,23 +148,22 @@ describe("hardware source adapter", () => { }, overlays: createOverlayRegistry(), }); - const detach = attachHardwareKeyboardSource( - { - subscribe(handler) { - events.add(handler); - return () => { - events.delete(handler); - }; - }, - setOverlayKeys() {}, + const detach = createHardwareKeyboardSource({ + subscribe(handler) { + events.add(handler); + return () => { + events.delete(handler); + }; }, - { - keyDown: pipeline.keyDown, - keyUp: (event) => releases.push(event.key), - blur() {}, - commandCenterOpen: () => false, - }, - ); + setOverlayKeys() {}, + setClaimedShortcuts() {}, + }).attach({ + keyDown: pipeline.keyDown, + keyUp: (event) => releases.push(event.key), + blur() {}, + commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, + }); const down = { ...keyboardEvent("k", "KeyK", isMac), isComposing: false, @@ -180,4 +179,94 @@ describe("hardware source adapter", () => { expect(events.size).toBe(0); }, ); + + it("claims the Shift and Option shortcuts a focused text control would otherwise type", async () => { + const { createHardwareKeyboardSource } = await import("./internal/sources/native"); + const { focusSurfaces } = await import("./internal/focus-surfaces"); + let claimed: string[] = []; + const source = createHardwareKeyboardSource({ + subscribe: () => () => {}, + setOverlayKeys() {}, + setClaimedShortcuts(shortcuts) { + claimed = shortcuts + .map(({ code, shift, alt }) => [alt && "Alt", shift && "Shift", code]) + .map((parts) => parts.filter(Boolean).join("+")) + .sort(); + }, + }); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + let commandCenterOpen = false; + const commandCenterListeners = new Set<() => void>(); + const detach = source.attach({ + keyDown() {}, + keyUp() {}, + blur() {}, + commandCenterOpen: () => commandCenterOpen, + subscribeCommandCenter(listener) { + commandCenterListeners.add(listener); + return () => commandCenterListeners.delete(listener); + }, + }); + const setCommandCenterOpen = (open: boolean) => { + commandCenterOpen = open; + for (const listener of commandCenterListeners) listener(); + }; + // iPad tab switching uses Cmd+Shift+[ / ], which no text control types. + expect(claimed).toEqual([]); + + const releaseComposer = focusSurfaces.declare("message-input"); + expect(claimed).toEqual(["Shift+Tab"]); + setCommandCenterOpen(true); + expect(claimed).toEqual([]); + setCommandCenterOpen(false); + expect(claimed).toEqual(["Shift+Tab"]); + releaseComposer(); + expect(claimed).toEqual([]); + + source.publishPolicy({ + bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Alt+M" }), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + const releaseRebound = focusSurfaces.declare("message-input"); + expect(claimed).toEqual(["Alt+KeyM"]); + releaseRebound(); + + // A chord's later step is only a shortcut while the chord is in progress; + // claiming it always would stop the composer typing a capital A. + source.publishPolicy({ + bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Mod+J Shift+A" }), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + const releaseChord = focusSurfaces.declare("message-input"); + expect(claimed).toEqual([]); + releaseChord(); + + const releaseFinal = focusSurfaces.declare("message-input"); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: false, + }); + expect(claimed).toEqual([]); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + expect(claimed).toEqual(["Shift+Tab"]); + detach(); + expect(claimed).toEqual([]); + releaseFinal(); + }); }); diff --git a/packages/app/src/keyboard/use-shortcuts.ts b/packages/app/src/keyboard/use-shortcuts.ts index b762d8dfc..73e06f2ea 100644 --- a/packages/app/src/keyboard/use-shortcuts.ts +++ b/packages/app/src/keyboard/use-shortcuts.ts @@ -62,7 +62,7 @@ export function useKeyboardShortcuts({ const keyboardWorkspaceSelectionRef = useRef(null); const publishBrowserShortcutPolicy = useCallback( (chordState?: ChordState) => { - publishKeyboardPolicy({ bindings, chordState, isMac, enabled }); + publishKeyboardPolicy({ bindings, chordState, isMac, usesDesktopBindings, enabled }); }, [bindings, enabled, isMac], ); @@ -265,6 +265,10 @@ export function useKeyboardShortcuts({ keyUp: handleKeyUp, blur: resetModifiers, commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen, + subscribeCommandCenter: (listener) => + useKeyboardShortcutsStore.subscribe((state, previous) => { + if (state.commandCenterOpen !== previous.commandCenterOpen) listener(); + }), }); return () => { detach(); diff --git a/packages/app/src/lib/overlay-root.browser.test.tsx b/packages/app/src/lib/overlay-root.browser.test.tsx index 7f0d5115a..299c036fc 100644 --- a/packages/app/src/lib/overlay-root.browser.test.tsx +++ b/packages/app/src/lib/overlay-root.browser.test.tsx @@ -134,6 +134,7 @@ describe("DOM source through the shared resolver", () => { keyUp() {}, blur() {}, commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, }); const event = new KeyboardEvent("keydown", { key: "j",