All files / src/hooks useDialogAccessibility.ts

100% Statements 34/34
100% Branches 16/16
100% Functions 7/7
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                1494x 1494x   1494x 1494x     1494x 527x 527x 527x 527x         1494x 527x 508x   527x 527x       1494x 497x 5x 5x   4x     4x   3x 3x   3x 1x 1x 2x 1x 1x       1494x    
import { useEffect, useRef, useCallback } from "react";
 
/**
 * Provides focus trap, Escape key handling, and focus restore for modal dialogs.
 * Returns a ref to attach to the dialog container and a keydown handler for the
 * wrapper element to enable focus trapping.
 */
export function useDialogAccessibility(onClose: () => void) {
	const dialogRef = useRef<HTMLDivElement>(null);
	const previousFocusRef = useRef<HTMLElement | null>(null);
	// Keep onClose in a ref to avoid re-subscribing the Escape handler on every render
	const onCloseRef = useRef(onClose);
	onCloseRef.current = onClose;
 
	// Store previous focus and auto-focus dialog on mount; restore on unmount
	useEffect(() => {
		previousFocusRef.current = document.activeElement as HTMLElement;
		dialogRef.current?.focus();
		return () => {
			previousFocusRef.current?.focus();
		};
	}, []);
 
	// Escape key closes the dialog
	useEffect(() => {
		const handleKeyDown = (e: KeyboardEvent) => {
			if (e.key === "Escape") onCloseRef.current();
		};
		document.addEventListener("keydown", handleKeyDown);
		return () => document.removeEventListener("keydown", handleKeyDown);
	}, []);
 
	// Focus trap: wraps Tab/Shift+Tab at dialog boundaries
	const handleFocusTrap = useCallback((e: React.KeyboardEvent) => {
		if (e.key !== "Tab") return;
		const dialog = dialogRef.current;
		if (!dialog) return;
 
		const focusable = dialog.querySelectorAll<HTMLElement>(
			'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
		);
		if (focusable.length === 0) return;
 
		const first = focusable[0];
		const last = focusable[focusable.length - 1];
 
		if (e.shiftKey && document.activeElement === first) {
			e.preventDefault();
			last.focus();
		} else if (!e.shiftKey && document.activeElement === last) {
			e.preventDefault();
			first.focus();
		}
	}, []);
 
	return { dialogRef, handleFocusTrap };
}