forked from Creditra/Creditra-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFocusTrap.ts
More file actions
126 lines (108 loc) · 3.88 KB
/
Copy pathuseFocusTrap.ts
File metadata and controls
126 lines (108 loc) · 3.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import { useEffect, useRef } from 'react';
interface UseFocusTrapOptions {
/** Whether the trap is active */
isActive: boolean;
/** Ref to the trigger element that opened the modal (for return focus) */
triggerRef?: React.RefObject<HTMLElement | null>;
/** Callback when Escape is pressed */
onEscape?: () => void;
}
/**
* Query selector for focusable elements within a container.
* Includes: buttons, links, inputs, selects, textareas, and elements with tabindex="0"
*/
const FOCUSABLE_SELECTOR = [
'button:not([disabled]):not([tabindex="-1"])',
'a[href]:not([tabindex="-1"])',
'input:not([disabled]):not([tabindex="-1"])',
'select:not([disabled]):not([tabindex="-1"])',
'textarea:not([disabled]):not([tabindex="-1"])',
'[tabindex="0"]',
].join(', ');
/**
* Trap keyboard focus inside a container while the trap is active.
*
* On activation, focus moves to the first focusable element in the
* container. Tab and Shift+Tab cycle within the container. Escape calls
* the provided `onEscape` handler. On deactivation, focus returns to
* `triggerRef` if supplied, otherwise to the element that had focus
* before the trap was activated.
*
* Returns a ref to attach to the container element.
*/
export function useFocusTrap({ isActive, triggerRef, onEscape }: UseFocusTrapOptions) {
const containerRef = useRef<HTMLDivElement>(null);
const previousActiveElement = useRef<HTMLElement | null>(null);
// Store the element that had focus before the modal opened
useEffect(() => {
if (isActive) {
previousActiveElement.current = document.activeElement as HTMLElement;
}
}, [isActive]);
// Handle focus trap and Escape key
useEffect(() => {
if (!isActive) return;
const container = containerRef.current;
if (!container) return;
// Get all focusable elements
const getFocusableElements = (): HTMLElement[] => {
return Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR));
};
// Focus the first focusable element when opened
const focusableElements = getFocusableElements();
if (focusableElements.length > 0) {
// Small delay to ensure DOM is ready
setTimeout(() => {
focusableElements[0].focus();
}, 50);
}
// Handle Tab key to trap focus
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') return;
const elements = getFocusableElements();
if (elements.length === 0) return;
const firstElement = elements[0];
const lastElement = elements[elements.length - 1];
// Shift + Tab: moving backwards
if (event.shiftKey) {
if (document.activeElement === firstElement) {
event.preventDefault();
lastElement.focus();
}
} else {
// Tab: moving forwards
if (document.activeElement === lastElement) {
event.preventDefault();
firstElement.focus();
}
}
};
// Handle Escape key
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape' && onEscape) {
event.preventDefault();
onEscape();
}
};
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keydown', handleEscape);
return () => {
document.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('keydown', handleEscape);
};
}, [isActive, onEscape]);
// Return focus to trigger or previous element on close or unmount
useEffect(() => {
if (!isActive) return; // only set up return-focus when active
return () => {
// Cleanup runs when isActive goes false → true or on unmount
if (triggerRef?.current) {
triggerRef.current.focus();
} else if (previousActiveElement.current) {
previousActiveElement.current.focus();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isActive]);
return containerRef;
}