({
onFocusChange,
onSupportDetected,
}: UseTerminalFocusOptions)
| 67 | * - \x1b[O on focus lost |
| 68 | */ |
| 69 | export function useTerminalFocus({ |
| 70 | onFocusChange, |
| 71 | onSupportDetected, |
| 72 | }: UseTerminalFocusOptions): void { |
| 73 | useEffect(() => { |
| 74 | const stdin = getStdin() |
| 75 | if (!stdin) { |
| 76 | return |
| 77 | } |
| 78 | |
| 79 | let supportDetected = false |
| 80 | |
| 81 | // Enable focus reporting |
| 82 | enableFocusReporting() |
| 83 | |
| 84 | // Listen for data events on stdin to catch focus in/out sequences |
| 85 | const handleData = (chunk: Buffer | string) => { |
| 86 | const data = chunk.toString() |
| 87 | |
| 88 | // Use includes() instead of strict equality to handle cases where |
| 89 | // terminal batches multiple sequences or keystrokes together |
| 90 | if (data.includes(FOCUS_IN_EVENT)) { |
| 91 | // First focus event confirms terminal support |
| 92 | if (!supportDetected) { |
| 93 | supportDetected = true |
| 94 | onSupportDetected?.() |
| 95 | } |
| 96 | onFocusChange(true) |
| 97 | } else if (data.includes(FOCUS_OUT_EVENT)) { |
| 98 | // First focus event confirms terminal support |
| 99 | if (!supportDetected) { |
| 100 | supportDetected = true |
| 101 | onSupportDetected?.() |
| 102 | } |
| 103 | onFocusChange(false) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | stdin.on('data', handleData) |
| 108 | |
| 109 | // Cleanup: disable focus reporting and remove listener |
| 110 | return () => { |
| 111 | stdin.off('data', handleData) |
| 112 | disableFocusReporting() |
| 113 | } |
| 114 | }, [onFocusChange, onSupportDetected]) |
| 115 | } |
no test coverage detected