import { n as useFocusableElements } from "./useFocusableElements.js";
import { t as getDocumentActiveElement } from "./focus.js";
import { useEffect } from "react";
const useFocusTrap = (ref, trapFocus = true) => {
	const focusableElementList = useFocusableElements(ref);
	const handleKeyboardEvent = (e) => {
		if (trapFocus && ref.current && focusableElementList?.length && e.key === "Tab") {
			const activeElement = getDocumentActiveElement(ref.current);
			const firstElement = focusableElementList[0];
			const lastElement = focusableElementList.length === 1 ? firstElement : focusableElementList[focusableElementList.length - 1];
			if (e.shiftKey && activeElement === firstElement) {
				lastElement.focus();
				e.preventDefault();
			} else if (!e.shiftKey && activeElement === lastElement) {
				firstElement.focus();
				e.preventDefault();
			}
		}
	};
	useEffect(() => {
		ref.current?.addEventListener("keydown", handleKeyboardEvent);
		return () => {
			ref.current?.removeEventListener("keydown", handleKeyboardEvent);
		};
	}, [
		ref,
		trapFocus,
		focusableElementList
	]);
};
var useFocusTrap_default = useFocusTrap;
export { useFocusTrap_default as n, useFocusTrap as t };

//# sourceMappingURL=useFocusTrap.js.map