-
Notifications
You must be signed in to change notification settings - Fork 1
feat: add escape key to cancel branch selection screen #33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ericanderson
wants to merge
1
commit into
main
Choose a base branch
from
fix/24-escape-key-cancel
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,217 @@ | ||
| import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; | ||
| import inquirer from 'inquirer'; | ||
| import readline from 'readline'; | ||
| import { promptWithCancel } from './promptWithCancel.js'; | ||
|
|
||
| // Mock modules | ||
| vi.mock('inquirer'); | ||
| vi.mock('readline'); | ||
|
|
||
| describe('promptWithCancel', () => { | ||
| let mockedInquirer: any; | ||
| let mockedReadline: any; | ||
| let mockStdin: any; | ||
| let mockStdout: any; | ||
| let keypressListener: ((str: string, key: any) => void) | null = null; | ||
|
|
||
| beforeEach(() => { | ||
| mockedInquirer = vi.mocked(inquirer); | ||
| mockedReadline = vi.mocked(readline); | ||
|
|
||
| // Mock stdin/stdout | ||
| mockStdin = { | ||
| isTTY: true, | ||
| isRaw: false, | ||
| setRawMode: vi.fn(), | ||
| on: vi.fn((event, handler) => { | ||
| if (event === 'keypress') { | ||
| keypressListener = handler; | ||
| } | ||
| }), | ||
| removeListener: vi.fn() | ||
| }; | ||
|
|
||
| mockStdout = { | ||
| write: vi.fn() | ||
| }; | ||
|
|
||
| // Replace process.stdin and process.stdout | ||
| vi.spyOn(process, 'stdin', 'get').mockReturnValue(mockStdin as any); | ||
| vi.spyOn(process, 'stdout', 'get').mockReturnValue(mockStdout as any); | ||
|
|
||
| // Mock readline.emitKeypressEvents | ||
| mockedReadline.emitKeypressEvents = vi.fn(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.clearAllMocks(); | ||
| keypressListener = null; | ||
| }); | ||
|
|
||
| it('should return prompt answers when completed normally', async () => { | ||
| const mockAnswers = { selectedBranches: ['branch1', 'branch2'] }; | ||
|
|
||
| mockedInquirer.prompt.mockResolvedValue(mockAnswers); | ||
|
|
||
| const result = await promptWithCancel([ | ||
| { | ||
| type: 'checkbox', | ||
| name: 'selectedBranches', | ||
| message: 'Select branches:', | ||
| choices: ['branch1', 'branch2', 'branch3'] | ||
| } | ||
| ]); | ||
|
|
||
| expect(result).toEqual(mockAnswers); | ||
| expect(mockedInquirer.prompt).toHaveBeenCalledTimes(1); | ||
| expect(mockStdin.setRawMode).toHaveBeenCalledWith(true); | ||
| expect(mockStdin.removeListener).toHaveBeenCalledWith('keypress', keypressListener); | ||
| }); | ||
|
|
||
| it('should return null when escape key is pressed', async () => { | ||
| // Setup promise that will never resolve (simulating ongoing prompt) | ||
| const promptPromise = new Promise(() => {}); | ||
| mockedInquirer.prompt.mockReturnValue(promptPromise); | ||
|
|
||
| // Start the prompt | ||
| const resultPromise = promptWithCancel([ | ||
| { | ||
| type: 'checkbox', | ||
| name: 'selectedBranches', | ||
| message: 'Select branches:', | ||
| choices: ['branch1', 'branch2'] | ||
| } | ||
| ]); | ||
|
|
||
| // Simulate escape key press after a small delay | ||
| await new Promise(resolve => setTimeout(resolve, 10)); | ||
| if (keypressListener) { | ||
| keypressListener('', { name: 'escape' }); | ||
| } | ||
|
|
||
| const result = await resultPromise; | ||
|
|
||
| expect(result).toBeNull(); | ||
| expect(mockStdout.write).toHaveBeenCalledWith('\n'); | ||
| expect(mockStdin.removeListener).toHaveBeenCalledWith('keypress', keypressListener); | ||
| }); | ||
|
|
||
| it('should handle non-TTY environments', async () => { | ||
| mockStdin.isTTY = false; | ||
| const mockAnswers = { selectedBranches: ['branch1'] }; | ||
|
|
||
| mockedInquirer.prompt.mockResolvedValue(mockAnswers); | ||
|
|
||
| const result = await promptWithCancel([ | ||
| { | ||
| type: 'checkbox', | ||
| name: 'selectedBranches', | ||
| message: 'Select branches:', | ||
| choices: ['branch1'] | ||
| } | ||
| ]); | ||
|
|
||
| expect(result).toEqual(mockAnswers); | ||
| expect(mockStdin.setRawMode).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should handle prompt errors gracefully', async () => { | ||
| const mockError = new Error('Some prompt error'); | ||
| mockedInquirer.prompt.mockRejectedValue(mockError); | ||
|
|
||
| await expect(promptWithCancel([ | ||
| { | ||
| type: 'input', | ||
| name: 'test', | ||
| message: 'Test:' | ||
| } | ||
| ])).rejects.toThrow('Some prompt error'); | ||
|
|
||
| expect(mockStdin.removeListener).toHaveBeenCalledWith('keypress', keypressListener); | ||
| }); | ||
|
|
||
| it('should exit process on Ctrl+C (ExitPromptError)', async () => { | ||
| const mockExit = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any); | ||
|
|
||
| const ctrlCError = new Error('User force closed'); | ||
| ctrlCError.name = 'ExitPromptError'; | ||
| mockedInquirer.prompt.mockRejectedValue(ctrlCError); | ||
|
|
||
| // Since process.exit is called, the promise won't resolve normally | ||
| // We just need to verify the side effects | ||
| promptWithCancel([ | ||
| { | ||
| type: 'input', | ||
| name: 'test', | ||
| message: 'Test:' | ||
| } | ||
| ]).catch(() => { | ||
| // Expected to throw since we mock process.exit | ||
| }); | ||
|
|
||
| // Wait for async operations | ||
| await new Promise(resolve => setTimeout(resolve, 10)); | ||
|
|
||
| expect(mockExit).toHaveBeenCalledWith(0); | ||
| expect(mockStdout.write).toHaveBeenCalledWith('\n'); | ||
|
|
||
| mockExit.mockRestore(); | ||
| }); | ||
|
|
||
| it('should not process escape key after prompt is resolved', async () => { | ||
| const mockAnswers = { test: 'value' }; | ||
| let resolvePrompt: ((value: any) => void) | null = null; | ||
|
|
||
| // Create a controlled promise | ||
| const promptPromise = new Promise((resolve) => { | ||
| resolvePrompt = resolve; | ||
| }); | ||
|
|
||
| mockedInquirer.prompt.mockReturnValue(promptPromise); | ||
|
|
||
| const resultPromise = promptWithCancel([ | ||
| { | ||
| type: 'input', | ||
| name: 'test', | ||
| message: 'Test:' | ||
| } | ||
| ]); | ||
|
|
||
| // Resolve the prompt first | ||
| if (resolvePrompt) { | ||
| (resolvePrompt as any)(mockAnswers); | ||
| } | ||
|
|
||
| // Wait for promise to resolve | ||
| await new Promise(resolve => setTimeout(resolve, 10)); | ||
|
|
||
| // Try to press escape after prompt resolved | ||
| if (keypressListener) { | ||
| keypressListener('', { name: 'escape' }); | ||
| } | ||
|
|
||
| const result = await resultPromise; | ||
|
|
||
| // Should return the answers, not null | ||
| expect(result).toEqual(mockAnswers); | ||
| expect(mockStdout.write).not.toHaveBeenCalled(); // No newline written for escape | ||
| }); | ||
|
|
||
| it('should restore original raw mode state', async () => { | ||
| mockStdin.isRaw = true; // Start with raw mode enabled | ||
| const mockAnswers = { test: 'value' }; | ||
|
|
||
| mockedInquirer.prompt.mockResolvedValue(mockAnswers); | ||
|
|
||
| await promptWithCancel([ | ||
| { | ||
| type: 'input', | ||
| name: 'test', | ||
| message: 'Test:' | ||
| } | ||
| ]); | ||
|
|
||
| // Should restore to original state (true) | ||
| expect(mockStdin.setRawMode).toHaveBeenCalledWith(true); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import inquirer from 'inquirer'; | ||
| import readline from 'readline'; | ||
|
|
||
| /** | ||
| * Wrapper for inquirer prompts that adds escape key cancellation support. | ||
| * Returns null if the user presses escape, otherwise returns the prompt answers. | ||
| */ | ||
| export async function promptWithCancel<T = any>( | ||
| questions: any | ||
| ): Promise<T | null> { | ||
| let cleanupFunction: (() => void) | undefined; | ||
| let promptResolved = false; | ||
|
|
||
| const result = await new Promise<T | null>((resolve, reject) => { | ||
| // Setup escape key handling | ||
| const originalRawMode = process.stdin.isRaw; | ||
| readline.emitKeypressEvents(process.stdin); | ||
|
|
||
| if (process.stdin.isTTY) { | ||
| process.stdin.setRawMode(true); | ||
| } | ||
|
|
||
| const keypressHandler = (_str: string, key: any) => { | ||
| if (key && key.name === 'escape' && !promptResolved) { | ||
| promptResolved = true; | ||
| // Emit newline to clean up the terminal display | ||
| process.stdout.write('\n'); | ||
| resolve(null); // Return null to indicate cancellation | ||
| } | ||
| }; | ||
|
|
||
| process.stdin.on('keypress', keypressHandler); | ||
|
|
||
| cleanupFunction = () => { | ||
| process.stdin.removeListener('keypress', keypressHandler); | ||
| if (process.stdin.isTTY && originalRawMode !== process.stdin.isRaw) { | ||
| process.stdin.setRawMode(originalRawMode); | ||
| } | ||
| }; | ||
|
|
||
| // Start the actual prompt | ||
| inquirer.prompt(questions) | ||
| .then((answers) => { | ||
| if (!promptResolved) { | ||
| promptResolved = true; | ||
| resolve(answers as T); | ||
| } | ||
| }) | ||
| .catch((error) => { | ||
| if (!promptResolved) { | ||
| promptResolved = true; | ||
| // Handle Ctrl+C gracefully | ||
| if (error.name === 'ExitPromptError' || error.message?.includes('User force closed')) { | ||
| process.stdout.write('\n'); | ||
| process.exit(0); | ||
| } | ||
| reject(error); | ||
| } | ||
| }); | ||
| }).finally(() => { | ||
| if (cleanupFunction) { | ||
| cleanupFunction(); | ||
| } | ||
| }); | ||
|
|
||
| return result; | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dont uses any. fix this to be proper types.