@@ -69,4 +69,58 @@ describe('useHotkeys', () => {
6969 unmount ( ) ;
7070 expect ( removeEventListenerSpy ) . toHaveBeenCalledWith ( 'keydown' , expect . any ( Function ) ) ;
7171 } ) ;
72+
73+ it ( 'should not call handler when key is pressed in an input element' , ( ) => {
74+ const callback = vi . fn ( ) ;
75+ renderHook ( ( ) => useHotkeys ( { a : callback } ) ) ;
76+
77+ const input = document . createElement ( 'input' ) ;
78+ document . body . appendChild ( input ) ;
79+ input . focus ( ) ;
80+
81+ fireKeyDown ( 'a' ) ;
82+ expect ( callback ) . not . toHaveBeenCalled ( ) ;
83+
84+ document . body . removeChild ( input ) ;
85+ } ) ;
86+
87+ it ( 'should call handler for Escape even when focus is in an input element' , ( ) => {
88+ const escapeCallback = vi . fn ( ) ;
89+ renderHook ( ( ) => useHotkeys ( { escape : escapeCallback } ) ) ;
90+
91+ const input = document . createElement ( 'input' ) ;
92+ document . body . appendChild ( input ) ;
93+ input . focus ( ) ;
94+
95+ fireKeyDown ( 'Escape' ) ;
96+ expect ( escapeCallback ) . toHaveBeenCalledOnce ( ) ;
97+
98+ document . body . removeChild ( input ) ;
99+ } ) ;
100+
101+ it ( 'should not call handler when key is pressed in a textarea element' , ( ) => {
102+ const callback = vi . fn ( ) ;
103+ renderHook ( ( ) => useHotkeys ( { r : callback } ) ) ;
104+
105+ const textarea = document . createElement ( 'textarea' ) ;
106+ document . body . appendChild ( textarea ) ;
107+ textarea . focus ( ) ;
108+
109+ fireKeyDown ( 'r' ) ;
110+ expect ( callback ) . not . toHaveBeenCalled ( ) ;
111+
112+ document . body . removeChild ( textarea ) ;
113+ } ) ;
114+
115+ it ( 'should handle null activeElement gracefully and still trigger handler' , ( ) => {
116+ const callback = vi . fn ( ) ;
117+ renderHook ( ( ) => useHotkeys ( { a : callback } ) ) ;
118+
119+ const activeElementSpy = vi . spyOn ( document , 'activeElement' , 'get' ) . mockReturnValue ( null ) ;
120+
121+ fireKeyDown ( 'a' ) ;
122+ expect ( callback ) . toHaveBeenCalledOnce ( ) ;
123+
124+ activeElementSpy . mockRestore ( ) ;
125+ } ) ;
72126} ) ;
0 commit comments