1- import { useCallback , useEffect } from "react" ;
1+ import { useCallback , useEffect , useRef } from "react" ;
22import { useHotkeys } from "react-hotkeys-hook" ;
33
44export interface Hotkey {
@@ -50,6 +50,9 @@ export const hotkeys: Record<string, Hotkey> = {
5050export const useMarkdownHotkeys = (
5151 textareaRef : React . RefObject < HTMLTextAreaElement > ,
5252) => {
53+ const currentTextareaRef = useRef < HTMLTextAreaElement | null > ( null ) ;
54+ const handlerRef = useRef < ( e : KeyboardEvent ) => void > ( ) ;
55+
5356 // Create a single callback for all hotkeys
5457 const handleHotkey = useCallback (
5558 ( hotkey : Hotkey ) => ( e : KeyboardEvent ) => {
@@ -150,12 +153,8 @@ export const useMarkdownHotkeys = (
150153 [ textareaRef ] ,
151154 ) ;
152155
153- // Use useEffect to bind event listeners directly to the textarea
154156 useEffect ( ( ) => {
155- const textarea = textareaRef . current ;
156- if ( ! textarea ) return ;
157-
158- const keydownHandler = ( e : KeyboardEvent ) => {
157+ handlerRef . current = ( e : KeyboardEvent ) => {
159158 // Check if it's a meta/ctrl key combination
160159 if ( ! e . metaKey && ! e . ctrlKey ) return ;
161160
@@ -170,11 +169,31 @@ export const useMarkdownHotkeys = (
170169 handleHotkey ( matchingHotkey ) ( e ) ;
171170 }
172171 } ;
172+ } , [ handleHotkey ] ) ;
173173
174- textarea . addEventListener ( 'keydown' , keydownHandler ) ;
174+ useEffect ( ( ) => {
175+ const textarea = textareaRef . current ;
176+
177+ if ( textarea === currentTextareaRef . current ) return ;
178+
179+ // Clean up previous event listener
180+ if ( currentTextareaRef . current && handlerRef . current ) {
181+ currentTextareaRef . current . removeEventListener ( 'keydown' , handlerRef . current ) ;
182+ }
183+
184+ // Set up new event listener if textarea exists
185+ if ( textarea && handlerRef . current ) {
186+ textarea . addEventListener ( 'keydown' , handlerRef . current ) ;
187+ currentTextareaRef . current = textarea ;
188+ } else {
189+ currentTextareaRef . current = null ;
190+ }
175191
176192 return ( ) => {
177- textarea . removeEventListener ( 'keydown' , keydownHandler ) ;
193+ if ( currentTextareaRef . current && handlerRef . current ) {
194+ currentTextareaRef . current . removeEventListener ( 'keydown' , handlerRef . current ) ;
195+ currentTextareaRef . current = null ;
196+ }
178197 } ;
179- } , [ textareaRef , handleHotkey ] ) ;
198+ } ) ;
180199} ;
0 commit comments