From 5a78da16bb5ea0c24ab20f1ea1b79082054dcfe4 Mon Sep 17 00:00:00 2001 From: ClarkChen Date: Sun, 15 Nov 2026 12:44:55 +0800 Subject: [PATCH] fix(settings): end shortcut recording on click-away so global shortcuts resume (#42400) After a rejected chord (conflict or invalid), the Shortcuts recorder keeps listening, but keys only reach it while it has focus. Clicking elsewhere left the row stuck on "Press keys..." and kept setShortcutRecorderFocused(true), so main-process window shortcuts stayed suspended. While recording, a capture-phase window click listener now ends recording when focus has moved off the recorder. Window/app switches keep recording as before. The row error stays mounted (and copyable) after click-away; starting any recorder clears stale errors. While recording, a rejected chord now shows "Press another shortcut, or Esc to cancel." next to the error. Fixes #42398 Co-authored-by: Neil --- .../shortcuts/ShortcutCommandBlock.tsx | 26 ++++--- .../shortcuts/ShortcutRecorderButton.tsx | 20 ++++- ...ShortcutsPane.recorder-click-away.test.tsx | 77 +++++++++++++++++++ .../settings/shortcuts/ShortcutsPane.tsx | 5 +- src/renderer/src/i18n/locales/de.json | 1 + src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/es.json | 1 + src/renderer/src/i18n/locales/fr.json | 1 + src/renderer/src/i18n/locales/ja.json | 1 + src/renderer/src/i18n/locales/ko.json | 1 + src/renderer/src/i18n/locales/pt.json | 1 + src/renderer/src/i18n/locales/ru.json | 1 + src/renderer/src/i18n/locales/tr.json | 1 + src/renderer/src/i18n/locales/zh-Hant.json | 1 + src/renderer/src/i18n/locales/zh.json | 1 + 15 files changed, 127 insertions(+), 12 deletions(-) create mode 100644 src/renderer/src/components/settings/shortcuts/ShortcutsPane.recorder-click-away.test.tsx diff --git a/src/renderer/src/components/settings/shortcuts/ShortcutCommandBlock.tsx b/src/renderer/src/components/settings/shortcuts/ShortcutCommandBlock.tsx index e5922155245..5d94aacd126 100644 --- a/src/renderer/src/components/settings/shortcuts/ShortcutCommandBlock.tsx +++ b/src/renderer/src/components/settings/shortcuts/ShortcutCommandBlock.tsx @@ -79,14 +79,17 @@ export function ShortcutCommandBlock({ 'Press a shortcut, or double-tap a modifier (e.g. {{value0}}). Esc cancels.', { value0: doubleTapHint } ) - const helperMessage = error + // A rejected chord keeps the recorder listening, so pair the error with a retry hint. + const recordingHint = isRecording ? error - : isRecording - ? recordingMessage - : warnings.length > 0 - ? warnings.join(' ') - : '' - const helperTone = error || (!isRecording && warnings.length > 0) ? 'error' : 'muted' + ? t( + 'auto.components.settings.ShortcutCommandBlock.retryAfterError', + 'Press another shortcut, or Esc to cancel.' + ) + : recordingMessage + : '' + const warningMessage = !error && !isRecording ? warnings.join(' ') : '' + const helperTone = error || warningMessage ? 'error' : 'muted' const recorderFor = (binding: string | null, index: number): React.JSX.Element => ( - {helperMessage ? ( + {error || recordingHint || warningMessage ? ( - {helperMessage} + {/* Separate nodes so ending recording keeps the error text (and a selection on it) mounted. */} + {error ? {error} : null} + {recordingHint ? ( + {recordingHint} + ) : null} + {warningMessage} ) : null} diff --git a/src/renderer/src/components/settings/shortcuts/ShortcutRecorderButton.tsx b/src/renderer/src/components/settings/shortcuts/ShortcutRecorderButton.tsx index 78a4ad7ecc3..ba4f23d2a29 100644 --- a/src/renderer/src/components/settings/shortcuts/ShortcutRecorderButton.tsx +++ b/src/renderer/src/components/settings/shortcuts/ShortcutRecorderButton.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useRef } from 'react' +import React, { useEffect, useEffectEvent, useRef } from 'react' import { formatKeybinding } from '../../../../../shared/keybindings/formatting' import { isDoubleTapBinding } from '../../../../../shared/keybindings/normalization' import type { KeybindingActionId, KeybindingInput } from '../../../../../shared/keybindings/types' @@ -70,6 +70,24 @@ export function ShortcutRecorderButton({ // ShortcutsPane owns the global recorder-focus flag across rows. }, [recording]) + // Leave the row error in place so it can still be read or copied; Esc or the next recording clears it. + const cancelIfClickedAway = useEffectEvent((): void => { + if (document.activeElement !== recordButtonRef.current) { + onCancelRecording() + } + }) + + // Keys only reach a focused recorder, so a click elsewhere would strand it recording. Cancel on + // click, not blur: window switches keep recording, and the row only collapses after the click + // has landed. Capture phase runs before the clicked control's own handler. + useEffect(() => { + if (!recording) { + return + } + window.addEventListener('click', cancelIfClickedAway, true) + return () => window.removeEventListener('click', cancelIfClickedAway, true) + }, [recording]) + const handleRecordKeyDown = (event: React.KeyboardEvent): void => { if (!recording) { if (event.key === 'Enter' || event.key === ' ') { diff --git a/src/renderer/src/components/settings/shortcuts/ShortcutsPane.recorder-click-away.test.tsx b/src/renderer/src/components/settings/shortcuts/ShortcutsPane.recorder-click-away.test.tsx new file mode 100644 index 00000000000..29acc1df0ba --- /dev/null +++ b/src/renderer/src/components/settings/shortcuts/ShortcutsPane.recorder-click-away.test.tsx @@ -0,0 +1,77 @@ +// @vitest-environment happy-dom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store/index' +import { TooltipProvider } from '@/components/ui/tooltip' +import { ShortcutsPane } from './ShortcutsPane' + +vi.hoisted(() => vi.stubGlobal('navigator', { userAgent: 'Macintosh' })) +const fixtures = vi.hoisted(() => ({ empty: [] })) +vi.mock('@/store/plugins/catalog/plugin-contribution-catalog', () => ({ + useEditablePluginCommands: () => fixtures.empty +})) +vi.mock('./use-mac-captured-digit-chords', () => ({ + useMacCapturedDigitChords: () => fixtures.empty +})) +vi.mock('./KeybindingsFileActions', () => ({ KeybindingsFileActions: () => null })) +vi.mock('./ShortcutTerminalPolicyControl', () => ({ ShortcutTerminalPolicyControl: () => null })) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +async function renderPaneWithConflict(): Promise { + useAppStore.setState({ + keybindings: { 'worktree.palette': ['Mod+J'], 'terminal.clear': ['Mod+K'] }, + keybindingSnapshot: null + }) + render( + + + + ) + const recorder = screen.getByRole('button', { name: 'Change shortcut for Switch worktree' }) + fireEvent.click(recorder) + await act(async () => { + fireEvent.keyDown(recorder, { key: 'k', code: 'KeyK', metaKey: true }) + }) + expect(screen.queryByText(/conflicts with/)).not.toBeNull() + return recorder +} + +it('keeps recording across a window switch and stops on a click elsewhere, keeping the error', async () => { + const setShortcutRecorderFocused = vi.fn() + vi.stubGlobal('api', { ui: { setShortcutRecorderFocused } }) + const recorder = await renderPaneWithConflict() + const errorNode = screen.getByText(/conflicts with/) + + // Window/app switch: the recorder blurs but gets focus back on return, so it keeps listening. + act(() => recorder.blur()) + expect(recorder.getAttribute('aria-pressed')).toBe('true') + + fireEvent.click(document.body) + + expect(recorder.getAttribute('aria-pressed')).toBe('false') + expect(setShortcutRecorderFocused).toHaveBeenLastCalledWith(false) + expect(errorNode.isConnected).toBe(true) + expect(screen.queryByText('Press another shortcut, or Esc to cancel.')).toBeNull() +}) + +it('clears a click-away error when another recorder starts', async () => { + vi.stubGlobal('api', { ui: { setShortcutRecorderFocused: vi.fn() } }) + const first = await renderPaneWithConflict() + const second = screen.getByRole('button', { name: 'Change shortcut for Clear active pane' }) + + act(() => second.focus()) + expect(first.getAttribute('aria-pressed')).toBe('true') + + fireEvent.click(second) + expect(first.getAttribute('aria-pressed')).toBe('false') + expect(second.getAttribute('aria-pressed')).toBe('true') + expect(screen.queryByText(/conflicts with/)).toBeNull() + + // A second click on the active recorder must not cancel it. + fireEvent.click(second) + expect(second.getAttribute('aria-pressed')).toBe('true') +}) diff --git a/src/renderer/src/components/settings/shortcuts/ShortcutsPane.tsx b/src/renderer/src/components/settings/shortcuts/ShortcutsPane.tsx index 4e6e8ead313..8e91591a328 100644 --- a/src/renderer/src/components/settings/shortcuts/ShortcutsPane.tsx +++ b/src/renderer/src/components/settings/shortcuts/ShortcutsPane.tsx @@ -373,13 +373,14 @@ export function ShortcutsPane(): React.JSX.Element { onStartRecordingAt={(actionId, index) => { setRecordingActionId(actionId) setRecordingBindingIndex(index) - clearError(actionId) + // Click-away keeps a row's error; drop every stale one once any new recording starts. + setErrors({}) }} onAppendBinding={(actionId) => { const current = effectiveBindingsForAction(actionId) setRecordingActionId(actionId) setRecordingBindingIndex(current.length) - clearError(actionId) + setErrors({}) }} onCancelRecording={() => { setRecordingActionId(null) diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index ea7b411da0d..ba04c88f9d3 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -11582,6 +11582,7 @@ "e27c8d45bf": "Die Diagnose ist durch eine Umgebungsvariable deaktiviert." }, "ShortcutCommandBlock": { + "retryAfterError": "Ein anderes Tastenkürzel drücken oder mit Esc abbrechen.", "eb72c52c28": "Ein Tastenkürzel drücken oder eine Zusatztaste zweimal antippen (z. B. {{value0}}). Esc bricht ab.", "70b5d25583": "Tastenkürzel für {{value0}}", "287e07ddde": "Geändert", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 95e2e58d675..3ea23c9bf20 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -12368,6 +12368,7 @@ "e27c8d45bf": "Diagnostics are disabled by an environment variable." }, "ShortcutCommandBlock": { + "retryAfterError": "Press another shortcut, or Esc to cancel.", "eb72c52c28": "Press a shortcut, or double-tap a modifier (e.g. {{value0}}). Esc cancels.", "70b5d25583": "{{value0}} shortcut", "287e07ddde": "Modified", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index d5b06a29538..47d469e96aa 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -11214,6 +11214,7 @@ "e27c8d45bf": "Los diagnósticos están desactivados por una variable de entorno." }, "ShortcutCommandBlock": { + "retryAfterError": "Pulsa otro atajo o Esc para cancelar.", "eb72c52c28": "Pulsa un atajo o toca dos veces una tecla modificadora (p. ej., {{value0}}). Esc cancela.", "70b5d25583": "Atajo de {{value0}}", "287e07ddde": "Modificado", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index d13aa0c50ef..7b088353ef9 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -11463,6 +11463,7 @@ "e27c8d45bf": "Les diagnostics sont désactivés par une variable d'environnement." }, "ShortcutCommandBlock": { + "retryAfterError": "Appuyez sur un autre raccourci, ou sur Échap pour annuler.", "eb72c52c28": "Appuyez sur un raccourci, ou appuyez deux fois sur une touche modificatrice (ex. {{value0}}). Échap annule.", "70b5d25583": "Raccourci {{value0}}", "287e07ddde": "Modifié", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 85d2b44f5b3..b1cc70599bc 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -10939,6 +10939,7 @@ "e27c8d45bf": "環境変数により診断は無効になっています。" }, "ShortcutCommandBlock": { + "retryAfterError": "別のショートカットを押すか、Esc でキャンセルします。", "eb72c52c28": "ショートカットを押すか、修飾キーを 2 回続けて押してください(例: {{value0}})。Esc でキャンセルします。", "70b5d25583": "{{value0}} のショートカット", "287e07ddde": "修正済み", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index e187b9cfb07..4d77070dc61 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -10936,6 +10936,7 @@ "e27c8d45bf": "환경 변수로 인해 진단이 비활성화되었습니다." }, "ShortcutCommandBlock": { + "retryAfterError": "다른 단축키를 누르거나 Esc를 눌러 취소하세요.", "eb72c52c28": "단축키를 누르거나 수정자 키를 두 번 탭하세요(예: {{value0}}). Esc 키로 취소합니다.", "70b5d25583": "{{value0}} 단축키", "287e07ddde": "변경됨", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 343adefacfc..5e85e3ae786 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -8004,6 +8004,7 @@ "b2c384cfd6": "Nenhuma interface encontrada" }, "ShortcutCommandBlock": { + "retryAfterError": "Pressione outro atalho ou Esc para cancelar.", "eb72c52c28": "Pressione um atalho, ou toque duas vezes em um modificador (ex.: {{value0}}). Esc cancela.", "70b5d25583": "Atalho de {{value0}}", "287e07ddde": "Modificado", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 749a792b470..867c720f71c 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -11923,6 +11923,7 @@ "e27c8d45bf": "Диагностика отключена переменной окружения." }, "ShortcutCommandBlock": { + "retryAfterError": "Нажмите другое сочетание клавиш или Esc для отмены.", "eb72c52c28": "Нажмите сочетание клавиш или дважды нажмите модификатор, например {{value0}}. Esc отменяет ввод.", "70b5d25583": "Сочетание клавиш из группы «{{value0}}»", "287e07ddde": "Изменено", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 894106e58cc..497390ba1b7 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -11559,6 +11559,7 @@ "e27c8d45bf": "Tanılama bir ortam değişkeni tarafından devre dışı bırakıldı." }, "ShortcutCommandBlock": { + "retryAfterError": "Başka bir kısayola basın veya iptal etmek için Esc tuşuna basın.", "eb72c52c28": "Bir kısayola basın veya bir değiştirici tuşa iki kez dokunun (ör. {{value0}}). Esc iptal eder.", "70b5d25583": "{{value0}} kısayolu", "287e07ddde": "Değiştirildi", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 7446b15a6ba..bbde714f3b4 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -11405,6 +11405,7 @@ "e27c8d45bf": "診斷已被環境變數停用。" }, "ShortcutCommandBlock": { + "retryAfterError": "按下其他快速鍵,或按 Esc 取消。", "eb72c52c28": "按下快速鍵,或雙擊修飾鍵(例如 {{value0}})。Esc 取消。", "70b5d25583": "{{value0}} 快速鍵", "287e07ddde": "已修改", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 5ee7f8eac17..2f896e47b97 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -11173,6 +11173,7 @@ "e27c8d45bf": "诊断已被环境变量停用" }, "ShortcutCommandBlock": { + "retryAfterError": "按下其他快捷键,或按 Esc 取消", "eb72c52c28": "按下快捷键,或双击修饰键(例如 {{value0}}),Esc 取消", "70b5d25583": "{{value0}} 快捷键", "287e07ddde": "已修改",