UNPKG

@rainbow-me/rainbowkit

Version:
62 lines (59 loc) 1.56 kB
"use client"; // src/components/Dialog/FocusTrap.tsx import React, { useCallback, useEffect, useRef } from "react"; var moveFocusWithin = (element, position) => { const focusableElements = element.querySelectorAll( "button:not(:disabled), a[href]" ); if (focusableElements.length === 0) return; focusableElements[position === "end" ? focusableElements.length - 1 : 0].focus(); }; function FocusTrap(props) { const contentRef = useRef(null); useEffect(() => { const previouslyActiveElement = document.activeElement; return () => { previouslyActiveElement.focus?.(); }; }, []); useEffect(() => { if (contentRef.current) { const elementToFocus = contentRef.current.querySelector("[data-auto-focus]"); if (elementToFocus) { elementToFocus.focus(); } else { contentRef.current.focus(); } } }, []); return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement( "div", { onFocus: useCallback( () => contentRef.current && moveFocusWithin(contentRef.current, "end"), [] ), tabIndex: 0 } ), /* @__PURE__ */ React.createElement( "div", { ref: contentRef, style: { outline: "none" }, tabIndex: -1, ...props } ), /* @__PURE__ */ React.createElement( "div", { onFocus: useCallback( () => contentRef.current && moveFocusWithin(contentRef.current, "start"), [] ), tabIndex: 0 } )); } export { FocusTrap };