Skip to content

Commit 4a1228d

Browse files
Fix: Hotkeys stop working after switching between preview and edit modes #1298 (#1300)
* hotkey fix for the editor * Fix hotkeys not working after preview mode toggle --------- Co-authored-by: Niall Maher <[email protected]>
1 parent d810785 commit 4a1228d

File tree

1 file changed

+28
-9
lines changed

1 file changed

+28
-9
lines changed

markdoc/editor/hotkeys/hotkeys.markdoc.ts

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useEffect } from "react";
1+
import { useCallback, useEffect, useRef } from "react";
22
import { useHotkeys } from "react-hotkeys-hook";
33

44
export interface Hotkey {
@@ -50,6 +50,9 @@ export const hotkeys: Record<string, Hotkey> = {
5050
export 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

Comments
 (0)