@styleless-ui/react
Version:
Completely unstyled, headless and accessible React UI components.
1 lines • 1.58 kB
JavaScript
import{jsx as e,Fragment as r,jsxs as t}from"react/jsx-runtime";import*as n from"react";import{visuallyHiddenCSSProperties as u}from"../internals";import{contains as c,isFocusable as i,useEventListener as o,useForkedRefs as l}from"../utils";export default function(a){var d,m=a.children,f=a.enabled,s=void 0!==f&&f,v=function(){try{if(!n.isValidElement(m))throw 0;return n.Children.only(m)}catch(e){throw new Error("[StylelessUI][FocusTrap]: The `children` prop has to be a single valid element.")}}(),h=n.useRef(!1),p=n.useRef(null),y=n.useRef(),E=l(y,null!==(d=v.ref)&&void 0!==d?d:null),x=function(e){var r=null!=e?e:y.current;if(!r)return!1;if(!i(r))return!1;h.current=!0;try{r.focus()}catch(e){}return h.current=!1,document.activeElement===r},b=function(e){var r=null!=e?e:y.current;return!!r&&Array.from(r.children).some((function(e){return x(e)||b(e)}))},g=function(e){var r=null!=e?e:y.current;return!!r&&Array.from(r.children).reverse().some((function(e){return x(e)||g(e)}))};n.useEffect((function(){s&&b()}),[s]);var j={ref:E};return"undefined"!=typeof document&&o({target:document,eventType:"focus",handler:function(e){var r;h.current||y.current&&(c(y.current,e.target)?p.current=e.target:(b(),document.activeElement===p.current&&g(),document.activeElement&&!c(y.current,document.activeElement)&&(null===(r=document.activeElement)||void 0===r||r.blur()),p.current=document.activeElement))},options:{capture:!0}},s),t(r,{children:[e("div",{"aria-hidden":"true",tabIndex:s?0:-1,style:u}),n.cloneElement(v,j),e("div",{"aria-hidden":"true",tabIndex:s?0:-1,style:u})]})}