Skip to content

Commit 6ee449e

Browse files
Iurii Karpovcursoragent
andcommitted
Add useModalEscHandler composable for centralized ESC key handling in modals
Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent a5f95d9 commit 6ee449e

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import store from '@/store';
2+
3+
type ModalCloseCallback = (options: { hasUnderlying: boolean }) => void;
4+
5+
interface ModalRegistration {
6+
id: string;
7+
close: ModalCloseCallback;
8+
}
9+
10+
const modalRegistry: ModalRegistration[] = [];
11+
let isListenerRegistered = false;
12+
let lastCloseTimestamp = 0;
13+
const DEBOUNCE_MS = 1000;
14+
15+
function handleGlobalEscape(e: KeyboardEvent) {
16+
if (e.key !== 'Escape') return;
17+
18+
const now = Date.now();
19+
if (now - lastCloseTimestamp < DEBOUNCE_MS) return;
20+
21+
const openRadixDialog = document.querySelector(
22+
'[data-state="open"][role="dialog"]'
23+
);
24+
if (openRadixDialog) {
25+
return;
26+
}
27+
28+
const stack = store.state.modalStack;
29+
if (stack.length === 0 || modalRegistry.length === 0) {
30+
return;
31+
}
32+
33+
e.preventDefault();
34+
e.stopImmediatePropagation();
35+
36+
lastCloseTimestamp = now;
37+
38+
const topmostId = stack[stack.length - 1];
39+
const topmost = modalRegistry.find((modal) => modal.id === topmostId);
40+
if (!topmost) {
41+
return;
42+
}
43+
44+
const hasUnderlying = modalRegistry.length > 1;
45+
topmost.close({ hasUnderlying });
46+
}
47+
48+
export function useModalEscHandler() {
49+
function registerModal(id: string, closeCallback: ModalCloseCallback) {
50+
const existing = modalRegistry.find((modal) => modal.id === id);
51+
if (existing) {
52+
existing.close = closeCallback;
53+
} else {
54+
modalRegistry.push({ id, close: closeCallback });
55+
}
56+
if (!isListenerRegistered) {
57+
document.addEventListener('keydown', handleGlobalEscape, true);
58+
isListenerRegistered = true;
59+
}
60+
}
61+
62+
function unregisterModal(id: string) {
63+
const index = modalRegistry.findIndex((m) => m.id === id);
64+
if (index > -1) {
65+
modalRegistry.splice(index, 1);
66+
}
67+
if (modalRegistry.length === 0 && isListenerRegistered) {
68+
document.removeEventListener('keydown', handleGlobalEscape, true);
69+
isListenerRegistered = false;
70+
}
71+
}
72+
73+
return { registerModal, unregisterModal };
74+
}

0 commit comments

Comments
 (0)