| 24 | * custom overlay components that don't use Radix primitives. |
| 25 | */ |
| 26 | export function FocusTrap({ children, active = true }: FocusTrapProps) { |
| 27 | const containerRef = useRef<HTMLDivElement>(null); |
| 28 | |
| 29 | useEffect(() => { |
| 30 | if (!active) return; |
| 31 | |
| 32 | const container = containerRef.current; |
| 33 | if (!container) return; |
| 34 | |
| 35 | const focusable = () => |
| 36 | Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTORS)).filter( |
| 37 | (el) => !el.closest("[aria-hidden='true']") |
| 38 | ); |
| 39 | |
| 40 | const handleKeyDown = (e: KeyboardEvent) => { |
| 41 | if (e.key !== "Tab") return; |
| 42 | const els = focusable(); |
| 43 | if (els.length === 0) return; |
| 44 | |
| 45 | const first = els[0]; |
| 46 | const last = els[els.length - 1]; |
| 47 | |
| 48 | if (e.shiftKey) { |
| 49 | if (document.activeElement === first) { |
| 50 | e.preventDefault(); |
| 51 | last.focus(); |
| 52 | } |
| 53 | } else { |
| 54 | if (document.activeElement === last) { |
| 55 | e.preventDefault(); |
| 56 | first.focus(); |
| 57 | } |
| 58 | } |
| 59 | }; |
| 60 | |
| 61 | // Move focus into the trap on mount |
| 62 | const els = focusable(); |
| 63 | if (els.length > 0 && !container.contains(document.activeElement)) { |
| 64 | els[0].focus(); |
| 65 | } |
| 66 | |
| 67 | document.addEventListener("keydown", handleKeyDown); |
| 68 | return () => document.removeEventListener("keydown", handleKeyDown); |
| 69 | }, [active]); |
| 70 | |
| 71 | return <div ref={containerRef}>{children}</div>; |
| 72 | } |