From c4cdeb9848861d0ff3c763673d009bb0f006984f Mon Sep 17 00:00:00 2001 From: Eric Engberg Date: Sat, 3 Oct 2026 15:43:12 -0500 Subject: [PATCH 1/2] fix(tui): ignore letter shortcuts when ctrl or alt is held Letter shortcuts compared the typed character without checking modifiers, so ctrl+letter and alt+letter ran the plain-letter action: ctrl+r toggled raw value, ctrl+d deleted a widget, and on macOS alt+arrow (sent as ESC + letter) fired whatever letter followed. A few handlers patched ctrl+s one key at a time with `&& !key.ctrl`; widget keybinds checked ctrl but not alt. Shortcuts now compare against getPlainInput(), which is empty while ctrl or alt/option is held, across the line editor, widget keybinds, Edit Colors, Global Overrides, Powerline setup/themes/separators, the line selector and the hide-state checklist. Arrows, Enter, ESC, shift and text entry are unchanged, and modifier combos are free for bindings of their own. --- src/tui/components/ColorMenu.tsx | 24 ++- src/tui/components/GlobalOverridesMenu.tsx | 30 +-- src/tui/components/HideStatesEditor.tsx | 4 +- src/tui/components/LineSelector.tsx | 4 +- .../components/PowerlineSeparatorEditor.tsx | 18 +- src/tui/components/PowerlineSetup.tsx | 10 +- src/tui/components/PowerlineThemeSelector.tsx | 4 +- .../__tests__/hotkey-modifiers.test.ts | 188 ++++++++++++++++++ .../__tests__/input-handlers.test.ts | 53 +++++ .../components/items-editor/input-handlers.ts | 25 ++- src/utils/__tests__/input-guards.test.ts | 19 +- src/utils/input-guards.ts | 7 + 12 files changed, 337 insertions(+), 49 deletions(-) create mode 100644 src/tui/components/__tests__/hotkey-modifiers.test.ts diff --git a/src/tui/components/ColorMenu.tsx b/src/tui/components/ColorMenu.tsx index 41a941b43..0a67fc751 100644 --- a/src/tui/components/ColorMenu.tsx +++ b/src/tui/components/ColorMenu.tsx @@ -16,7 +16,10 @@ import { getAvailableColorsForUI } from '../../utils/colors'; import { GRADIENT_PRESET_NAMES } from '../../utils/gradient'; -import { shouldInsertInput } from '../../utils/input-guards'; +import { + getPlainInput, + shouldInsertInput +} from '../../utils/input-guards'; import { getWidget } from '../../utils/widgets'; import { ConfirmDialog } from './ConfirmDialog'; @@ -68,6 +71,7 @@ export const ColorMenu: React.FC = ({ widgets, lineIndex, settin // Handle keyboard input const hasNoItems = colorableWidgets.length === 0; useInput((input, key) => { + const shortcut = getPlainInput(input, key); // If no items, any key goes back if (hasNoItems) { onBack(); @@ -228,19 +232,19 @@ export const ColorMenu: React.FC = ({ widgets, lineIndex, settin } else { onBack(); } - } else if (input === 'h' || input === 'H') { + } else if (shortcut === 'h' || shortcut === 'H') { // Enter hex input mode (only in truecolor mode) if (highlightedItemId && highlightedItemId !== 'back' && settings.colorLevel === 3) { setHexInputMode(true); setHexInput(''); } - } else if (input === 'a' || input === 'A') { + } else if (shortcut === 'a' || shortcut === 'A') { // Enter ansi256 input mode (only in 256 color mode) if (highlightedItemId && highlightedItemId !== 'back' && settings.colorLevel === 2) { setAnsi256InputMode(true); setAnsi256Input(''); } - } else if (input === 'g' || input === 'G') { + } else if (shortcut === 'g' || shortcut === 'G') { // Enter gradient selection mode (foreground only, needs a real color palette) if (highlightedItemId && highlightedItemId !== 'back' && !editingBackground && settings.colorLevel >= 2) { setGradientMode(true); @@ -249,18 +253,18 @@ export const ColorMenu: React.FC = ({ widgets, lineIndex, settin setGradientStartHex(''); setGradientHexInput(''); } - } else if ((input === 's' || input === 'S') && !key.ctrl) { + } else if (shortcut === 's' || shortcut === 'S') { // Toggle show separators (only if not in powerline mode and no default separator) if (!settings.powerline.enabled && !settings.defaultSeparator) { setShowSeparators(!showSeparators); // The highlighted item ID will be maintained, and we'll recalculate // the initial index when rendering the SelectInput } - } else if (input === 'f' || input === 'F') { + } else if (shortcut === 'f' || shortcut === 'F') { if (colorableWidgets.length > 0) { setEditingBackground(!editingBackground); } - } else if (input === 'b' || input === 'B') { + } else if (shortcut === 'b' || shortcut === 'B') { if (highlightedItemId && highlightedItemId !== 'back') { // Toggle bold for the highlighted item const selectedWidget = colorableWidgets.find(widget => widget.id === highlightedItemId); @@ -269,7 +273,7 @@ export const ColorMenu: React.FC = ({ widgets, lineIndex, settin onUpdate(newItems); } } - } else if (input === 'd' || input === 'D') { + } else if (shortcut === 'd' || shortcut === 'D') { if (highlightedItemId && highlightedItemId !== 'back') { // Cycle dim for the highlighted item: off -> whole -> parens -> off const selectedWidget = colorableWidgets.find(widget => widget.id === highlightedItemId); @@ -278,7 +282,7 @@ export const ColorMenu: React.FC = ({ widgets, lineIndex, settin onUpdate(newItems); } } - } else if (input === 'r' || input === 'R') { + } else if (shortcut === 'r' || shortcut === 'R') { if (highlightedItemId && highlightedItemId !== 'back') { // Reset all styling (color, background, and bold) for the highlighted item const selectedWidget = colorableWidgets.find(widget => widget.id === highlightedItemId); @@ -287,7 +291,7 @@ export const ColorMenu: React.FC = ({ widgets, lineIndex, settin onUpdate(newItems); } } - } else if (input === 'c' || input === 'C') { + } else if (shortcut === 'c' || shortcut === 'C') { // Show clear all confirmation setShowClearConfirm(true); } else if (key.leftArrow || key.rightArrow) { diff --git a/src/tui/components/GlobalOverridesMenu.tsx b/src/tui/components/GlobalOverridesMenu.tsx index 785576924..8805e4f45 100644 --- a/src/tui/components/GlobalOverridesMenu.tsx +++ b/src/tui/components/GlobalOverridesMenu.tsx @@ -23,7 +23,10 @@ import { getColorDisplayName } from '../../utils/colors'; import { GRADIENT_PRESET_NAMES } from '../../utils/gradient'; -import { shouldInsertInput } from '../../utils/input-guards'; +import { + getPlainInput, + shouldInsertInput +} from '../../utils/input-guards'; import { getNextNumberStyle } from '../../utils/number-format'; import { ConfirmDialog } from './ConfirmDialog'; @@ -90,6 +93,7 @@ export const GlobalOverridesMenu: React.FC = ({ settin const currentFgIndex = fgColors.indexOf(settings.overrideForegroundColor ?? 'none'); useInput((input, key) => { + const shortcut = getPlainInput(input, key); if (editingPadding) { if (key.return) { const updatedSettings = { @@ -213,11 +217,11 @@ export const GlobalOverridesMenu: React.FC = ({ settin } else { if (key.escape) { onBack(); - } else if (input === 'p' || input === 'P') { + } else if (shortcut === 'p' || shortcut === 'P') { setEditingPadding(true); - } else if ((input === 's' || input === 'S') && !isPowerlineEnabled && !key.ctrl) { + } else if ((shortcut === 's' || shortcut === 'S') && !isPowerlineEnabled) { setEditingSeparator(true); - } else if ((input === 'i' || input === 'I') && !isPowerlineEnabled) { + } else if ((shortcut === 'i' || shortcut === 'I') && !isPowerlineEnabled) { const newInheritColors = !inheritColors; setInheritColors(newInheritColors); const updatedSettings = { @@ -225,7 +229,7 @@ export const GlobalOverridesMenu: React.FC = ({ settin inheritSeparatorColors: newInheritColors }; onUpdate(updatedSettings); - } else if ((input === 'b' || input === 'B') && !isPowerlineEnabled) { + } else if ((shortcut === 'b' || shortcut === 'B') && !isPowerlineEnabled) { // Cycle through background colors const nextIndex = (currentBgIndex + 1) % bgColors.length; const nextBgColor = bgColors[nextIndex]; @@ -234,14 +238,14 @@ export const GlobalOverridesMenu: React.FC = ({ settin overrideBackgroundColor: nextBgColor === 'none' ? undefined : nextBgColor }; onUpdate(updatedSettings); - } else if ((input === 'c' || input === 'C') && !isPowerlineEnabled) { + } else if ((shortcut === 'c' || shortcut === 'C') && !isPowerlineEnabled) { // Clear override background color const updatedSettings = { ...settings, overrideBackgroundColor: undefined }; onUpdate(updatedSettings); - } else if (input === 'o' || input === 'O') { + } else if (shortcut === 'o' || shortcut === 'O') { // Toggle global bold const newGlobalBold = !globalBold; setGlobalBold(newGlobalBold); @@ -250,7 +254,7 @@ export const GlobalOverridesMenu: React.FC = ({ settin globalBold: newGlobalBold }; onUpdate(updatedSettings); - } else if (input === 'm' || input === 'M') { + } else if (shortcut === 'm' || shortcut === 'M') { // Toggle minimalist mode const newMinimalistMode = !minimalistMode; setMinimalistMode(newMinimalistMode); @@ -259,10 +263,10 @@ export const GlobalOverridesMenu: React.FC = ({ settin minimalistMode: newMinimalistMode }; onUpdate(updatedSettings); - } else if (input === 'n' || input === 'N') { + } else if (shortcut === 'n' || shortcut === 'N') { setNumberFormatMode(true); setNumberFormatKindIndex(0); - } else if (input === 'f' || input === 'F') { + } else if (shortcut === 'f' || shortcut === 'F') { // Cycle through foreground colors const nextIndex = (currentFgIndex + 1) % fgColors.length; const nextFgColor = fgColors[nextIndex]; @@ -271,21 +275,21 @@ export const GlobalOverridesMenu: React.FC = ({ settin overrideForegroundColor: nextFgColor === 'none' ? undefined : nextFgColor }; onUpdate(updatedSettings); - } else if (input === 'g' || input === 'G') { + } else if (shortcut === 'g' || shortcut === 'G') { // Enter gradient selection mode setGradientMode(true); setGradientIndex(0); setGradientCustomStep(null); setGradientStartHex(''); setGradientHexInput(''); - } else if (input === 'x' || input === 'X') { + } else if (shortcut === 'x' || shortcut === 'X') { // Clear override foreground color const updatedSettings = { ...settings, overrideForegroundColor: undefined }; onUpdate(updatedSettings); - } else if (input === 'd' || input === 'D') { + } else if (shortcut === 'd' || shortcut === 'D') { // Cycle through padding sides: both -> left -> right -> both const paddingSides = DefaultPaddingSideSchema.options; const currentIndex = paddingSides.indexOf(settings.defaultPaddingSide); diff --git a/src/tui/components/HideStatesEditor.tsx b/src/tui/components/HideStatesEditor.tsx index 921a03187..7f3b6bfaa 100644 --- a/src/tui/components/HideStatesEditor.tsx +++ b/src/tui/components/HideStatesEditor.tsx @@ -9,6 +9,7 @@ import type { HideableState, WidgetItem } from '../../types/Widget'; +import { getPlainInput } from '../../utils/input-guards'; import { MERGE_TARGET_HIDDEN_HIDEABLE_STATE, getEnabledHideStates, @@ -27,6 +28,7 @@ export const HideStatesEditor: React.FC = ({ widget, stat const [enabledKeys, setEnabledKeys] = useState(() => getEnabledHideStates(widget, states)); useInput((input, key) => { + const shortcut = getPlainInput(input, key); if (key.return) { onComplete(setEnabledHideStates(widget, states, enabledKeys)); } else if (key.escape) { @@ -35,7 +37,7 @@ export const HideStatesEditor: React.FC = ({ widget, stat setSelectedIndex(selectedIndex - 1 < 0 ? states.length - 1 : selectedIndex - 1); } else if (key.downArrow && states.length > 0) { setSelectedIndex(selectedIndex + 1 > states.length - 1 ? 0 : selectedIndex + 1); - } else if (input === ' ') { + } else if (shortcut === ' ') { const state = states[selectedIndex]; if (state) { setEnabledKeys(enabledKeys.includes(state.key) diff --git a/src/tui/components/LineSelector.tsx b/src/tui/components/LineSelector.tsx index 5cb600f97..62068314b 100644 --- a/src/tui/components/LineSelector.tsx +++ b/src/tui/components/LineSelector.tsx @@ -12,6 +12,7 @@ import React, { import type { Settings } from '../../types/Settings'; import type { WidgetItem } from '../../types/Widget'; +import { getPlainInput } from '../../utils/input-guards'; import { ConfirmDialog } from './ConfirmDialog'; import { List } from './List'; @@ -86,6 +87,7 @@ const LineSelector: React.FC = ({ // Handle keyboard input useInput((input, key) => { + const shortcut = getPlainInput(input, key); if (showDeleteDialog) { return; } @@ -125,7 +127,7 @@ const LineSelector: React.FC = ({ return; } - switch (input) { + switch (shortcut) { case 'a': if (allowEditing) { appendLine(); diff --git a/src/tui/components/PowerlineSeparatorEditor.tsx b/src/tui/components/PowerlineSeparatorEditor.tsx index eaf71b085..11fa8ec18 100644 --- a/src/tui/components/PowerlineSeparatorEditor.tsx +++ b/src/tui/components/PowerlineSeparatorEditor.tsx @@ -6,7 +6,10 @@ import { import React, { useState } from 'react'; import type { Settings } from '../../types/Settings'; -import { shouldInsertInput } from '../../utils/input-guards'; +import { + getPlainInput, + shouldInsertInput +} from '../../utils/input-guards'; export type EditorMode = 'separator' | 'startCap' | 'endCap'; @@ -111,6 +114,7 @@ export const PowerlineSeparatorEditor: React.FC = }; useInput((input, key) => { + const shortcut = getPlainInput(input, key); if (hexInputMode) { // Hex input mode if (key.escape) { @@ -184,7 +188,7 @@ export const PowerlineSeparatorEditor: React.FC = } updateSeparators(newSeparators, mode === 'separator' ? newInvertBgs : undefined); - } else if (input === 'a' || input === 'A') { + } else if (shortcut === 'a' || shortcut === 'A') { // Add after current const newSeparators = [...separators]; const newInvertBgs = mode === 'separator' ? [...invertBgs] : []; @@ -207,7 +211,7 @@ export const PowerlineSeparatorEditor: React.FC = updateSeparators(newSeparators, newInvertBgs); setSelectedIndex(selectedIndex + 1); } - } else if (input === 'i' || input === 'I') { + } else if (shortcut === 'i' || shortcut === 'I') { // Insert before current const newSeparators = [...separators]; const newInvertBgs = mode === 'separator' ? [...invertBgs] : []; @@ -230,13 +234,13 @@ export const PowerlineSeparatorEditor: React.FC = updateSeparators(newSeparators, newInvertBgs); // Keep selection on the newly inserted item (which is now at selectedIndex) } - } else if ((input === 'd' || input === 'D') && (mode !== 'separator' || separators.length > 1)) { + } else if ((shortcut === 'd' || shortcut === 'D') && (mode !== 'separator' || separators.length > 1)) { // Delete current (min 1 for separator, no min for caps) const newSeparators = separators.filter((_, i) => i !== selectedIndex); const newInvertBgs = mode === 'separator' ? invertBgs.filter((_, i) => i !== selectedIndex) : []; updateSeparators(newSeparators, newInvertBgs); setSelectedIndex(Math.min(selectedIndex, Math.max(0, newSeparators.length - 1))); - } else if (input === 'c' || input === 'C') { + } else if (shortcut === 'c' || shortcut === 'C') { // Clear all if (mode === 'separator') { // Reset to default right-facing separator with no inversion @@ -245,12 +249,12 @@ export const PowerlineSeparatorEditor: React.FC = updateSeparators([]); } setSelectedIndex(0); - } else if (input === 'h' || input === 'H') { + } else if (shortcut === 'h' || shortcut === 'H') { // Enter hex input mode setHexInputMode(true); setHexInput(''); setCursorPos(0); - } else if ((input === 't' || input === 'T') && mode === 'separator') { + } else if ((shortcut === 't' || shortcut === 'T') && mode === 'separator') { // Toggle background inversion (for all separators in separator mode) const newInvertBgs = [...invertBgs]; newInvertBgs[selectedIndex] = !(newInvertBgs[selectedIndex] ?? false); diff --git a/src/tui/components/PowerlineSetup.tsx b/src/tui/components/PowerlineSetup.tsx index 6703c20c3..f0a8249d7 100644 --- a/src/tui/components/PowerlineSetup.tsx +++ b/src/tui/components/PowerlineSetup.tsx @@ -8,6 +8,7 @@ import React, { useState } from 'react'; import type { PowerlineConfig } from '../../types/PowerlineConfig'; import type { Settings } from '../../types/Settings'; +import { getPlainInput } from '../../utils/input-guards'; import { type PowerlineFontStatus } from '../../utils/powerline'; import { buildEnabledPowerlineSettings } from '../../utils/powerline-settings'; @@ -173,6 +174,7 @@ export const PowerlineSetup: React.FC = ({ const globalOverrideMessage = hasGlobalFgOverride ? '⚠ Global override for FG active' : null; useInput((input, key) => { + const shortcut = getPlainInput(input, key); if (fontInstallMessage || installingFonts) { if (fontInstallMessage && !key.escape) { onClearMessage(); @@ -187,7 +189,7 @@ export const PowerlineSetup: React.FC = ({ if (screen === 'menu') { if (key.escape) { onBack(); - } else if (input === 't' || input === 'T') { + } else if (shortcut === 't' || shortcut === 'T') { if (!powerlineConfig.enabled) { if (hasManualSeparatorItems) { setConfirmingEnable(true); @@ -203,9 +205,9 @@ export const PowerlineSetup: React.FC = ({ } }); } - } else if (input === 'i' || input === 'I') { + } else if (shortcut === 'i' || shortcut === 'I') { setConfirmingFontInstall(true); - } else if ((input === 'a' || input === 'A') && powerlineConfig.enabled) { + } else if ((shortcut === 'a' || shortcut === 'A') && powerlineConfig.enabled) { onUpdate({ ...settings, powerline: { @@ -213,7 +215,7 @@ export const PowerlineSetup: React.FC = ({ autoAlign: !powerlineConfig.autoAlign } }); - } else if ((input === 'c' || input === 'C') && powerlineConfig.enabled) { + } else if ((shortcut === 'c' || shortcut === 'C') && powerlineConfig.enabled) { onUpdate({ ...settings, powerline: { diff --git a/src/tui/components/PowerlineThemeSelector.tsx b/src/tui/components/PowerlineThemeSelector.tsx index 72bfd4bb0..90de74e50 100644 --- a/src/tui/components/PowerlineThemeSelector.tsx +++ b/src/tui/components/PowerlineThemeSelector.tsx @@ -16,6 +16,7 @@ import { getPowerlineTheme, getPowerlineThemes } from '../../utils/colors'; +import { getPlainInput } from '../../utils/input-guards'; import { ConfirmDialog } from './ConfirmDialog'; import { @@ -135,6 +136,7 @@ export const PowerlineThemeSelector: React.FC = ({ }, [selectedIndex, themes]); useInput((input, key) => { + const shortcut = getPlainInput(input, key); if (showCustomizeConfirm) { return; } @@ -142,7 +144,7 @@ export const PowerlineThemeSelector: React.FC = ({ if (key.escape) { onUpdate(originalSettingsRef.current); onBack(); - } else if (input === 'c' || input === 'C') { + } else if (shortcut === 'c' || shortcut === 'C') { const currentThemeName = themes[selectedIndex]; if (currentThemeName && currentThemeName !== 'custom') { setShowCustomizeConfirm(true); diff --git a/src/tui/components/__tests__/hotkey-modifiers.test.ts b/src/tui/components/__tests__/hotkey-modifiers.test.ts new file mode 100644 index 000000000..ec35546a5 --- /dev/null +++ b/src/tui/components/__tests__/hotkey-modifiers.test.ts @@ -0,0 +1,188 @@ +import { render } from 'ink'; +import { PassThrough } from 'node:stream'; +import React from 'react'; +import stripAnsi from 'strip-ansi'; +import { + describe, + expect, + it, + vi, + type Mock +} from 'vitest'; + +import { DEFAULT_SETTINGS } from '../../../types/Settings'; +import type { WidgetItem } from '../../../types/Widget'; +import { ColorMenu } from '../ColorMenu'; +import { GlobalOverridesMenu } from '../GlobalOverridesMenu'; +import { HideStatesEditor } from '../HideStatesEditor'; +import { LineSelector } from '../LineSelector'; +import { PowerlineSeparatorEditor } from '../PowerlineSeparatorEditor'; +import { PowerlineSetup } from '../PowerlineSetup'; +import { PowerlineThemeSelector } from '../PowerlineThemeSelector'; + +class MockTtyStream extends PassThrough { + isTTY = true; + columns = 120; + rows = 40; + + setRawMode() { + return this; + } + + ref() { + return this; + } + + unref() { + return this; + } +} + +interface CapturedWriteStream extends NodeJS.WriteStream { getOutput: () => string } + +function createMockStdout(): CapturedWriteStream { + const stream = new MockTtyStream(); + const chunks: string[] = []; + + stream.on('data', (chunk: Buffer | string) => { + chunks.push(chunk.toString()); + }); + + return Object.assign(stream as unknown as NodeJS.WriteStream, { + getOutput() { + return chunks.join(''); + } + }); +} + +function flushInk() { + return new Promise((resolve) => { + setTimeout(resolve, 25); + }); +} + +const ENTER = '\r'; + +// The bytes a terminal sends: ctrl+letter is the letter's control character +// (ctrl+space is NUL), alt/option+key is ESC followed by the key +const MODIFIED: Record string> = { + ctrl: key => (key === ' ' ? '\x00' : String.fromCharCode(key.charCodeAt(0) - 96)), + alt: key => `\x1b${key}` +}; + +const powerlineOn = { ...DEFAULT_SETTINGS, powerline: { ...DEFAULT_SETTINGS.powerline, enabled: true } }; +const hideStates = [{ key: 'empty', label: 'When empty' }]; +const plainWidget: WidgetItem = { id: '1', type: 'model' }; + +interface ShortcutCase { + name: string; + shortcut: string; + // Keys pressed after the shortcut to make its effect observable + then?: string[]; + element: (spy: Mock) => React.ReactElement; + fired: (spy: Mock, output: string) => boolean; +} + +const calledSpy = (spy: Mock) => spy.mock.calls.length > 0; + +const cases: ShortcutCase[] = [ + { + name: 'Edit Colors: (b)old', + shortcut: 'b', + element: spy => React.createElement(ColorMenu, { widgets: [plainWidget], settings: DEFAULT_SETTINGS, onUpdate: spy, onBack: vi.fn() }), + fired: calledSpy + }, + { + // Not (i)nherit: ctrl+i is the same byte as Tab, so it can't be told apart + name: 'Global Overrides: (b)ackground cycle', + shortcut: 'b', + element: spy => React.createElement(GlobalOverridesMenu, { settings: DEFAULT_SETTINGS, onUpdate: spy, onBack: vi.fn() }), + fired: calledSpy + }, + { + name: 'Powerline Setup: (t)oggle', + shortcut: 't', + element: spy => React.createElement(PowerlineSetup, { + settings: powerlineOn, + powerlineFontStatus: { installed: true }, + onUpdate: spy, + onBack: vi.fn(), + onInstallFonts: vi.fn(), + installingFonts: false, + fontInstallMessage: null, + onClearMessage: vi.fn() + }), + fired: calledSpy + }, + { + name: 'Powerline themes: (c)ustomize', + shortcut: 'c', + element: spy => React.createElement(PowerlineThemeSelector, { + settings: { ...powerlineOn, powerline: { ...powerlineOn.powerline, theme: 'nord' } }, + onUpdate: spy, + onBack: vi.fn() + }), + fired: (_spy, output) => output.includes('Confirm Customization') + }, + { + name: 'Powerline separators: (a)dd', + shortcut: 'a', + element: spy => React.createElement(PowerlineSeparatorEditor, { settings: powerlineOn, mode: 'separator', onUpdate: spy, onBack: vi.fn() }), + fired: calledSpy + }, + { + name: 'Line selector: (a)ppend line', + shortcut: 'a', + element: spy => React.createElement(LineSelector, { + lines: [[plainWidget]], + onSelect: vi.fn(), + onBack: vi.fn(), + onLinesUpdate: spy, + allowEditing: true + }), + fired: calledSpy + }, + { + name: 'Hide states: Space toggles', + shortcut: ' ', + then: [ENTER], + element: spy => React.createElement(HideStatesEditor, { widget: plainWidget, states: hideStates, onComplete: spy, onCancel: vi.fn() }), + fired: spy => (spy.mock.calls[0]?.[0] as WidgetItem | undefined)?.metadata !== undefined + } +]; + +async function pressShortcut(testCase: ShortcutCase, keys: string): Promise { + const stdin = new MockTtyStream() as unknown as NodeJS.ReadStream; + const stdout = createMockStdout(); + const stderr = createMockStdout(); + const spy = vi.fn(); + const instance = render(testCase.element(spy), { stdin, stdout, stderr, debug: true, exitOnCtrlC: false, patchConsole: false }); + + try { + await flushInk(); + for (const input of [keys, ...(testCase.then ?? [])]) { + stdin.write(input); + await flushInk(); + } + return testCase.fired(spy, stripAnsi(stdout.getOutput())); + } finally { + instance.unmount(); + instance.cleanup(); + stdin.destroy(); + stdout.destroy(); + stderr.destroy(); + } +} + +describe('letter shortcuts ignore ctrl and alt combos', () => { + describe.each(cases)('$name', (testCase) => { + it('fires on the bare key', async () => { + expect(await pressShortcut(testCase, testCase.shortcut)).toBe(true); + }); + + it.each(Object.keys(MODIFIED))('does nothing with %s held', async (modifier) => { + const toBytes = MODIFIED[modifier] ?? ((key: string) => key); + expect(await pressShortcut(testCase, toBytes(testCase.shortcut))).toBe(false); + }); + }); +}); diff --git a/src/tui/components/items-editor/__tests__/input-handlers.test.ts b/src/tui/components/items-editor/__tests__/input-handlers.test.ts index 1c2d617cc..999040c6c 100644 --- a/src/tui/components/items-editor/__tests__/input-handlers.test.ts +++ b/src/tui/components/items-editor/__tests__/input-handlers.test.ts @@ -1089,4 +1089,57 @@ describe('items-editor input handlers', () => { expect(onUpdate).not.toHaveBeenCalled(); }); }); + + describe('modifier combos', () => { + function pressInNormalMode(input: string, key: Record, widgets: WidgetItem[]) { + const onUpdate = vi.fn(); + const openWidgetPicker = vi.fn(); + const setShowClearConfirm = vi.fn(); + + handleNormalInputMode({ + input, + key, + widgets, + selectedIndex: 0, + separatorChars: ['|'], + onBack: vi.fn(), + onUpdate, + setSelectedIndex: vi.fn(), + setMoveMode: vi.fn(), + setShowClearConfirm, + openWidgetPicker, + getCustomKeybindsForWidget: (widgetImpl, widget) => widgetImpl.getCustomKeybinds ? widgetImpl.getCustomKeybinds(widget) : [], + setCustomEditorWidget: vi.fn() + }); + + return { onUpdate, openWidgetPicker, setShowClearConfirm }; + } + + const commandWidget: WidgetItem = { id: '2', type: 'custom-command', commandPath: 'date' }; + const widgets: WidgetItem[] = [{ id: '1', type: 'model' }, commandWidget]; + + it.each([ + ['ctrl', { ctrl: true }], + ['alt', { meta: true }] + ])('ignores letter shortcuts while %s is held', (_name, key) => { + for (const letter of ['a', 'i', 'd', 'k', 'c', 'r', 'm']) { + const { onUpdate, openWidgetPicker, setShowClearConfirm } = pressInNormalMode(letter, key, widgets); + expect(onUpdate).not.toHaveBeenCalled(); + expect(openWidgetPicker).not.toHaveBeenCalled(); + expect(setShowClearConfirm).not.toHaveBeenCalled(); + } + }); + + it('still runs the shortcut for the bare letter', () => { + expect(pressInNormalMode('d', {}, widgets).onUpdate).toHaveBeenCalledWith([{ id: '2', type: 'custom-command', commandPath: 'date' }]); + }); + + it('ignores widget keybinds while alt is held, not just ctrl', () => { + const commandFirst = [commandWidget]; + + expect(pressInNormalMode('p', { meta: true }, commandFirst).onUpdate).not.toHaveBeenCalled(); + expect(pressInNormalMode('p', {}, commandFirst).onUpdate) + .toHaveBeenCalledWith([{ id: '2', type: 'custom-command', commandPath: 'date', preserveColors: true }]); + }); + }); }); diff --git a/src/tui/components/items-editor/input-handlers.ts b/src/tui/components/items-editor/input-handlers.ts index 2c7f52b2e..dc184658e 100644 --- a/src/tui/components/items-editor/input-handlers.ts +++ b/src/tui/components/items-editor/input-handlers.ts @@ -5,6 +5,7 @@ import type { WidgetItemType } from '../../../types/Widget'; import { generateGuid } from '../../../utils/guid'; +import { getPlainInput } from '../../../utils/input-guards'; import { CYCLE_NUMBER_STYLE_ACTION, cycleNumberStyle @@ -373,6 +374,8 @@ export function handleNormalInputMode({ setCustomEditorWidget, getUniqueBackgroundColor }: HandleNormalInputModeArgs): void { + const shortcut = getPlainInput(input, key); + if (key.upArrow && widgets.length > 0) { setSelectedIndex(selectedIndex - 1 < 0 ? widgets.length - 1 : selectedIndex - 1); } else if (key.downArrow && widgets.length > 0) { @@ -383,17 +386,17 @@ export function handleNormalInputMode({ openWidgetPicker('change'); } else if (key.return && widgets.length > 0) { setMoveMode(true); - } else if (input === 'a') { + } else if (shortcut === 'a') { openWidgetPicker('add'); - } else if (input === 'i') { + } else if (shortcut === 'i') { openWidgetPicker('insert'); - } else if (input === 'd' && widgets.length > 0) { + } else if (shortcut === 'd' && widgets.length > 0) { const newWidgets = widgets.filter((_, i) => i !== selectedIndex); onUpdate(newWidgets); if (selectedIndex >= newWidgets.length && selectedIndex > 0) { setSelectedIndex(selectedIndex - 1); } - } else if (input === 'k' && widgets.length > 0) { + } else if (shortcut === 'k' && widgets.length > 0) { const source = widgets[selectedIndex]; if (!source) { return; @@ -413,11 +416,11 @@ export function handleNormalInputMode({ ]; onUpdate(newWidgets); setSelectedIndex(insertIndex); - } else if (input === 'c') { + } else if (shortcut === 'c') { if (widgets.length > 0) { setShowClearConfirm(true); } - } else if (input === ' ' && widgets.length > 0) { + } else if (shortcut === ' ' && widgets.length > 0) { const currentWidget = widgets[selectedIndex]; if (currentWidget?.type === 'separator') { const currentChar = currentWidget.character ?? '|'; @@ -427,7 +430,7 @@ export function handleNormalInputMode({ newWidgets[selectedIndex] = { ...currentWidget, character: nextChar }; onUpdate(newWidgets); } - } else if (input === 'r' && widgets.length > 0) { + } else if (shortcut === 'r' && widgets.length > 0) { const currentWidget = widgets[selectedIndex]; if (currentWidget && currentWidget.type !== 'separator' && currentWidget.type !== 'flex-separator') { const widgetImpl = getWidget(currentWidget.type); @@ -438,7 +441,7 @@ export function handleNormalInputMode({ newWidgets[selectedIndex] = { ...currentWidget, rawValue: !currentWidget.rawValue }; onUpdate(newWidgets); } - } else if (input === 'm' && widgets.length > 0) { + } else if (shortcut === 'm' && widgets.length > 0) { const currentWidget = widgets[selectedIndex]; if (currentWidget && selectedIndex < widgets.length - 1 && currentWidget.type !== 'separator' && currentWidget.type !== 'flex-separator') { @@ -461,7 +464,7 @@ export function handleNormalInputMode({ } onUpdate(newWidgets); } - } else if (input === 'x' && widgets.length > 0) { + } else if (shortcut === 'x' && widgets.length > 0) { const currentWidget = widgets[selectedIndex]; if (canExcludeAlign && currentWidget && currentWidget.type !== 'separator' && currentWidget.type !== 'flex-separator') { const newWidgets = [...widgets]; @@ -484,9 +487,9 @@ export function handleNormalInputMode({ } const customKeybinds = getCustomKeybindsForWidget(widgetImpl, currentWidget); - const matchedKeybind = customKeybinds.find(kb => kb.key === input); + const matchedKeybind = customKeybinds.find(kb => kb.key === shortcut); - if (matchedKeybind && !key.ctrl) { + if (matchedKeybind) { // The hide-state checklist is rendered by the items editor for // every widget that declares hideable states, so it bypasses // widget-level action handling. diff --git a/src/utils/__tests__/input-guards.test.ts b/src/utils/__tests__/input-guards.test.ts index 5fb9bbe98..aef339592 100644 --- a/src/utils/__tests__/input-guards.test.ts +++ b/src/utils/__tests__/input-guards.test.ts @@ -4,7 +4,24 @@ import { it } from 'vitest'; -import { shouldInsertInput } from '../input-guards'; +import { + getPlainInput, + shouldInsertInput +} from '../input-guards'; + +describe('getPlainInput', () => { + it('passes bare keypresses through, shifted ones included', () => { + expect(getPlainInput('d', {})).toBe('d'); + expect(getPlainInput('D', { shift: true })).toBe('D'); + expect(getPlainInput(' ', {})).toBe(' '); + }); + + it('hides the letter while ctrl or alt/option (meta) is held', () => { + expect(getPlainInput('d', { ctrl: true })).toBe(''); + expect(getPlainInput('d', { meta: true })).toBe(''); + expect(getPlainInput('d', { ctrl: true, meta: true })).toBe(''); + }); +}); describe('shouldInsertInput', () => { it('allows regular printable input without modifiers', () => { diff --git a/src/utils/input-guards.ts b/src/utils/input-guards.ts index e017d1456..e4197efb0 100644 --- a/src/utils/input-guards.ts +++ b/src/utils/input-guards.ts @@ -7,6 +7,13 @@ export interface InputKeyLike { const CONTROL_CHAR_REGEX = /[\u0000-\u001F\u007F]/u; +// Letter shortcuts compare against this rather than the raw input, so ctrl and +// alt/option combos never trigger the plain-letter action (macOS terminals send +// alt+← as ESC b, i.e. meta+b) and stay free for bindings of their own +export function getPlainInput(input: string, key: InputKeyLike): string { + return key.ctrl || key.meta ? '' : input; +} + export const shouldInsertInput = (input: string, key: InputKeyLike): boolean => { if (!input) { return false; From a4d892034def4c0663534967d3640d70228c00e7 Mon Sep 17 00:00:00 2001 From: Eric Engberg Date: Sun, 4 Oct 2026 00:37:17 -0500 Subject: [PATCH 2/2] test(tui): wait for each shortcut's effect instead of a fixed delay The shortcut tests sent keys and checked the result after a fixed 25 ms. On a busy machine Ink can take longer, so the bare-key cases could fail even though the shortcut works. They now wait until the shortcut's effect shows (up to 3 s), and a follow-up key waits for the previous key's redraw. Checks that a modified key does nothing give it 150 ms to act. After each wait the test also gives React two setImmediate turns: React draws a frame, then attaches the new input listener in a scheduled effect, so a key sent the moment the frame shows could reach no listener. --- .../__tests__/hotkey-modifiers.test.ts | 56 ++++++++++++++++--- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/src/tui/components/__tests__/hotkey-modifiers.test.ts b/src/tui/components/__tests__/hotkey-modifiers.test.ts index ec35546a5..61a0e6f19 100644 --- a/src/tui/components/__tests__/hotkey-modifiers.test.ts +++ b/src/tui/components/__tests__/hotkey-modifiers.test.ts @@ -55,9 +55,36 @@ function createMockStdout(): CapturedWriteStream { }); } -function flushInk() { +// Lets work React has already queued run first. Its scheduler runs on +// setImmediate, and it attaches input listeners in an effect just after +// drawing a frame, so a key sent as soon as the frame shows could be lost. +async function letReactCatchUp() { + for (let turn = 0; turn < 2; turn++) { + await new Promise((resolve) => { + setImmediate(resolve); + }); + } +} + +// Polls until the condition holds; a fixed delay races Ink on a busy machine +async function waitUntil(condition: () => boolean, timeoutMs = 3000): Promise { + const deadline = Date.now() + timeoutMs; + do { + await new Promise((resolve) => { + setTimeout(resolve, 10); + }); + if (condition()) { + await letReactCatchUp(); + return true; + } + } while (Date.now() < deadline); + return false; +} + +// Long enough for a key to be handled, for checks that it did nothing +function settle() { return new Promise((resolve) => { - setTimeout(resolve, 25); + setTimeout(resolve, 150); }); } @@ -151,20 +178,31 @@ const cases: ShortcutCase[] = [ } ]; -async function pressShortcut(testCase: ShortcutCase, keys: string): Promise { +async function pressShortcut(testCase: ShortcutCase, keys: string, expectFired: boolean): Promise { const stdin = new MockTtyStream() as unknown as NodeJS.ReadStream; const stdout = createMockStdout(); const stderr = createMockStdout(); const spy = vi.fn(); const instance = render(testCase.element(spy), { stdin, stdout, stderr, debug: true, exitOnCtrlC: false, patchConsole: false }); + const fired = () => testCase.fired(spy, stripAnsi(stdout.getOutput())); + try { - await flushInk(); - for (const input of [keys, ...(testCase.then ?? [])]) { + await waitUntil(() => stdout.getOutput().length > 0); + const inputs = [keys, ...(testCase.then ?? [])]; + for (const [index, input] of inputs.entries()) { + const drawn = stdout.getOutput().length; stdin.write(input); - await flushInk(); + // A follow-up key needs the previous key's redraw, or it acts on stale state + if (index < inputs.length - 1) { + await waitUntil(() => stdout.getOutput().length > drawn); + } + } + if (expectFired) { + return await waitUntil(fired); } - return testCase.fired(spy, stripAnsi(stdout.getOutput())); + await settle(); + return fired(); } finally { instance.unmount(); instance.cleanup(); @@ -177,12 +215,12 @@ async function pressShortcut(testCase: ShortcutCase, keys: string): Promise { describe.each(cases)('$name', (testCase) => { it('fires on the bare key', async () => { - expect(await pressShortcut(testCase, testCase.shortcut)).toBe(true); + expect(await pressShortcut(testCase, testCase.shortcut, true)).toBe(true); }); it.each(Object.keys(MODIFIED))('does nothing with %s held', async (modifier) => { const toBytes = MODIFIED[modifier] ?? ((key: string) => key); - expect(await pressShortcut(testCase, toBytes(testCase.shortcut))).toBe(false); + expect(await pressShortcut(testCase, toBytes(testCase.shortcut), false)).toBe(false); }); }); });