import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef } from "react";
import Styles from "./ScrollAndFocusLock.module.scss";
/**
 * This utilitary component shall be used to lock the focus and disable scroll over the wrapped component
 **/
export default function ScrollAndFocusLock({ open, children, }) {
    const firstAnchor = useRef(null);
    const lastAnchor = useRef(null);
    const startOfModal = useRef(null);
    useEffect(() => {
        if (open)
            startOfModal.current.focus();
    }, []);
    useEffect(() => {
        if (open) {
            startOfModal.current.focus();
            document.body.classList.add(Styles.lockClass);
            return () => {
                document.body.classList.remove(Styles.lockClass);
            };
        }
    }, [open]);
    function onFocusAnchors(e) {
        const focusOnStartOfModal = () => {
            const nextSibling = firstAnchor.current.nextElementSibling;
            if (nextSibling instanceof HTMLDivElement)
                nextSibling.focus();
        };
        if (e.target === firstAnchor.current) {
            if (e.relatedTarget === startOfModal.current)
                lastAnchor.current.focus();
            else
                focusOnStartOfModal();
        }
        else if (e.target === lastAnchor.current &&
            e.relatedTarget !== firstAnchor.current) {
            focusOnStartOfModal();
        }
    }
    return (_jsxs(_Fragment, { children: [_jsx("div", { ref: firstAnchor, tabIndex: 0, onFocus: onFocusAnchors }), _jsx("div", { ref: startOfModal, tabIndex: 0 }), children, _jsx("div", { ref: lastAnchor, tabIndex: 0, onFocus: onFocusAnchors })] }));
}
//# sourceMappingURL=ScrollAndFocusLock.js.map