| 1 | import type { PermissionMode } from "../../permissions/types.js"; |
| 2 | import { logger } from "../../util/logger.js"; |
| 3 | |
| 4 | // Helper function to handle control keys |
| 5 | interface ControlKeysOptions { |
| 6 | input: string; |
| 7 | key: any; |
| 8 | exit: () => void; |
| 9 | showSlashCommands: boolean; |
| 10 | showFileSearch: boolean; |
| 11 | cycleModes: () => Promise<PermissionMode>; |
| 12 | clearInput?: () => void; |
| 13 | } |
| 14 | |
| 15 | export function handleControlKeys(options: ControlKeysOptions): boolean { |
| 16 | const { |
| 17 | input, |
| 18 | key, |
| 19 | exit, |
| 20 | showSlashCommands, |
| 21 | showFileSearch, |
| 22 | cycleModes, |
| 23 | clearInput, |
| 24 | } = options; |
| 25 | |
| 26 | // Handle Ctrl+C to clear input |
| 27 | if (key.ctrl && input === "c" && clearInput) { |
| 28 | clearInput(); |
| 29 | return true; |
| 30 | } |
| 31 | |
| 32 | // Handle Ctrl+D to exit |
| 33 | if (key.ctrl && input === "d") { |
| 34 | exit(); |
| 35 | return true; |
| 36 | } |
| 37 | |
| 38 | // Handle Ctrl+L to refresh screen (clear terminal artifacts) |
| 39 | if (key.ctrl && input === "l") { |
| 40 | process.stdout.write("\x1b[2J\x1b[H"); |
| 41 | return true; |
| 42 | } |
| 43 | |
| 44 | // Handle Shift+Tab to cycle through modes |
| 45 | if (key.tab && key.shift && !showSlashCommands && !showFileSearch) { |
| 46 | cycleModes().catch((error) => { |
| 47 | logger.error("Failed to cycle modes:", error); |
| 48 | }); |
| 49 | return true; |
| 50 | } |
| 51 | |
| 52 | return false; |
| 53 | } |
| 54 | |
| 55 | // Helper to update text buffer state |
| 56 | interface TextBufferStateOptions { |
| 57 | handled: boolean; |
| 58 | textBuffer: any; |
| 59 | setInputText: (text: string) => void; |
| 60 | setCursorPosition: (pos: number) => void; |
| 61 | updateSlashCommandState: (text: string, cursor: number) => void; |
| 62 | updateFileSearchState: (text: string, cursor: number) => void; |
| 63 | inputHistory: any; |
| 64 | } |
| 65 | |
| 66 | export function updateTextBufferState(options: TextBufferStateOptions) { |
| 67 | const { |
| 68 | handled, |
| 69 | textBuffer, |
| 70 | setInputText, |
| 71 | setCursorPosition, |
| 72 | updateSlashCommandState, |
| 73 | updateFileSearchState, |
| 74 | inputHistory, |
| 75 | } = options; |
| 76 | |
| 77 | // Skip state updates during rapid input mode to avoid conflicts with timer-based updates |
| 78 | if (handled && !textBuffer.isInRapidInputMode()) { |
| 79 | const newText = textBuffer.text; |
| 80 | const newCursor = textBuffer.cursor; |
| 81 | setInputText(newText); |
| 82 | setCursorPosition(newCursor); |
| 83 | updateSlashCommandState(newText, newCursor); |
| 84 | updateFileSearchState(newText, newCursor); |
| 85 | inputHistory.resetNavigation(); |
| 86 | } |
| 87 | } |