UNPKG

focus-trap

Version:
7 lines (6 loc) 11.5 kB
/*! * focus-trap 7.6.5 * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE */ import{tabbable as e,focusable as t,isTabbable as n,getTabIndex as o,isFocusable as r}from"tabbable";function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function i(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?u(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function c(e){return function(e){if(Array.isArray(e))return a(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return a(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var l=function(e,t){if(e.length>0){var n=e[e.length-1];n!==t&&n._setPausedState(!0)}var o=e.indexOf(t);-1===o||e.splice(o,1),e.push(t)},d=function(e,t){var n=e.indexOf(t);-1!==n&&e.splice(n,1),e.length>0&&!e[e.length-1]._isManuallyPaused()&&e[e.length-1]._setPausedState(!1)},f=function(e){return"Tab"===(null==e?void 0:e.key)||9===(null==e?void 0:e.keyCode)},b=function(e){return f(e)&&!e.shiftKey},v=function(e){return f(e)&&e.shiftKey},p=function(e){return setTimeout(e,0)},m=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return"function"==typeof e?e.apply(void 0,n):e},y=function(e){return e.target.shadowRoot&&"function"==typeof e.composedPath?e.composedPath()[0]:e.target},h=[],w=function(a,i){var u,w=(null==i?void 0:i.document)||document,g=(null==i?void 0:i.trapStack)||h,N=s({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:b,isKeyBackward:v},i),F={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},O=function(e,t,n){return e&&void 0!==e[t]?e[t]:N[n||t]},P=function(e,t){var n="function"==typeof(null==t?void 0:t.composedPath)?t.composedPath():void 0;return F.containerGroups.findIndex((function(t){var o=t.container,r=t.tabbableNodes;return o.contains(e)||(null==n?void 0:n.includes(o))||r.find((function(t){return t===e}))}))},k=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.hasFallback,o=void 0!==n&&n,r=t.params,a=void 0===r?[]:r,i=N[e];if("function"==typeof i&&(i=i.apply(void 0,c(a))),!0===i&&(i=void 0),!i){if(void 0===i||!1===i)return i;throw new Error("`".concat(e,"` was specified but was not a node, or did not return a node"))}var u=i;if("string"==typeof i){try{u=w.querySelector(i)}catch(t){throw new Error("`".concat(e,'` appears to be an invalid selector; error="').concat(t.message,'"'))}if(!u&&!o)throw new Error("`".concat(e,"` as selector refers to no known node"))}return u},E=function(){var e=k("initialFocus",{hasFallback:!0});if(!1===e)return!1;if(void 0===e||e&&!r(e,N.tabbableOptions))if(P(w.activeElement)>=0)e=w.activeElement;else{var t=F.tabbableGroups[0];e=t&&t.firstTabbableNode||k("fallbackFocus")}else null===e&&(e=k("fallbackFocus"));if(!e)throw new Error("Your focus-trap needs to have at least one focusable element");return e},T=function(){if(F.containerGroups=F.containers.map((function(r){var a=e(r,N.tabbableOptions),i=t(r,N.tabbableOptions),u=a.length>0?a[0]:void 0,s=a.length>0?a[a.length-1]:void 0,c=i.find((function(e){return n(e)})),l=i.slice().reverse().find((function(e){return n(e)})),d=!!a.find((function(e){return o(e)>0}));return{container:r,tabbableNodes:a,focusableNodes:i,posTabIndexesFound:d,firstTabbableNode:u,lastTabbableNode:s,firstDomTabbableNode:c,lastDomTabbableNode:l,nextTabbableNode:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=a.indexOf(e);return o<0?t?i.slice(i.indexOf(e)+1).find((function(e){return n(e)})):i.slice(0,i.indexOf(e)).reverse().find((function(e){return n(e)})):a[o+(t?1:-1)]}}})),F.tabbableGroups=F.containerGroups.filter((function(e){return e.tabbableNodes.length>0})),F.tabbableGroups.length<=0&&!k("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");if(F.containerGroups.find((function(e){return e.posTabIndexesFound}))&&F.containerGroups.length>1)throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.")},D=function(e){var t=e.activeElement;if(t)return t.shadowRoot&&null!==t.shadowRoot.activeElement?D(t.shadowRoot):t},G=function(e){!1!==e&&e!==D(document)&&(e&&e.focus?(e.focus({preventScroll:!!N.preventScroll}),F.mostRecentlyFocusedNode=e,function(e){return e.tagName&&"input"===e.tagName.toLowerCase()&&"function"==typeof e.select}(e)&&e.select()):G(E()))},x=function(e){var t=k("setReturnFocus",{params:[e]});return t||!1!==t&&e},S=function(e){var t=e.target,a=e.event,i=e.isBackward,u=void 0!==i&&i;t=t||y(a),T();var s=null;if(F.tabbableGroups.length>0){var c=P(t,a),l=c>=0?F.containerGroups[c]:void 0;if(c<0)s=u?F.tabbableGroups[F.tabbableGroups.length-1].lastTabbableNode:F.tabbableGroups[0].firstTabbableNode;else if(u){var d=F.tabbableGroups.findIndex((function(e){var n=e.firstTabbableNode;return t===n}));if(d<0&&(l.container===t||r(t,N.tabbableOptions)&&!n(t,N.tabbableOptions)&&!l.nextTabbableNode(t,!1))&&(d=c),d>=0){var b=0===d?F.tabbableGroups.length-1:d-1,v=F.tabbableGroups[b];s=o(t)>=0?v.lastTabbableNode:v.lastDomTabbableNode}else f(a)||(s=l.nextTabbableNode(t,!1))}else{var p=F.tabbableGroups.findIndex((function(e){var n=e.lastTabbableNode;return t===n}));if(p<0&&(l.container===t||r(t,N.tabbableOptions)&&!n(t,N.tabbableOptions)&&!l.nextTabbableNode(t))&&(p=c),p>=0){var m=p===F.tabbableGroups.length-1?0:p+1,h=F.tabbableGroups[m];s=o(t)>=0?h.firstTabbableNode:h.firstDomTabbableNode}else f(a)||(s=l.nextTabbableNode(t))}}else s=k("fallbackFocus");return s},R=function(e){var t=y(e);P(t,e)>=0||(m(N.clickOutsideDeactivates,e)?u.deactivate({returnFocus:N.returnFocusOnDeactivate}):m(N.allowOutsideClick,e)||e.preventDefault())},j=function(e){var t=y(e),n=P(t,e)>=0;if(n||t instanceof Document)n&&(F.mostRecentlyFocusedNode=t);else{var r;e.stopImmediatePropagation();var a=!0;if(F.mostRecentlyFocusedNode)if(o(F.mostRecentlyFocusedNode)>0){var i=P(F.mostRecentlyFocusedNode),u=F.containerGroups[i].tabbableNodes;if(u.length>0){var s=u.findIndex((function(e){return e===F.mostRecentlyFocusedNode}));s>=0&&(N.isKeyForward(F.recentNavEvent)?s+1<u.length&&(r=u[s+1],a=!1):s-1>=0&&(r=u[s-1],a=!1))}}else F.containerGroups.some((function(e){return e.tabbableNodes.some((function(e){return o(e)>0}))}))||(a=!1);else a=!1;a&&(r=S({target:F.mostRecentlyFocusedNode,isBackward:N.isKeyBackward(F.recentNavEvent)})),G(r||(F.mostRecentlyFocusedNode||E()))}F.recentNavEvent=void 0},I=function(e){(N.isKeyForward(e)||N.isKeyBackward(e))&&function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];F.recentNavEvent=e;var n=S({event:e,isBackward:t});n&&(f(e)&&e.preventDefault(),G(n))}(e,N.isKeyBackward(e))},A=function(e){var t;"Escape"!==(null==(t=e)?void 0:t.key)&&"Esc"!==(null==t?void 0:t.key)&&27!==(null==t?void 0:t.keyCode)||!1===m(N.escapeDeactivates,e)||(e.preventDefault(),u.deactivate())},L=function(e){var t=y(e);P(t,e)>=0||m(N.clickOutsideDeactivates,e)||m(N.allowOutsideClick,e)||(e.preventDefault(),e.stopImmediatePropagation())},B=function(){if(F.active)return l(g,u),F.delayInitialFocusTimer=N.delayInitialFocus?p((function(){G(E())})):G(E()),w.addEventListener("focusin",j,!0),w.addEventListener("mousedown",R,{capture:!0,passive:!1}),w.addEventListener("touchstart",R,{capture:!0,passive:!1}),w.addEventListener("click",L,{capture:!0,passive:!1}),w.addEventListener("keydown",I,{capture:!0,passive:!1}),w.addEventListener("keydown",A),u},C=function(){if(F.active)return w.removeEventListener("focusin",j,!0),w.removeEventListener("mousedown",R,!0),w.removeEventListener("touchstart",R,!0),w.removeEventListener("click",L,!0),w.removeEventListener("keydown",I,!0),w.removeEventListener("keydown",A),u},K="undefined"!=typeof window&&"MutationObserver"in window?new MutationObserver((function(e){e.some((function(e){return Array.from(e.removedNodes).some((function(e){return e===F.mostRecentlyFocusedNode}))}))&&G(E())})):void 0,_=function(){K&&(K.disconnect(),F.active&&!F.paused&&F.containers.map((function(e){K.observe(e,{subtree:!0,childList:!0})})))};return u={get active(){return F.active},get paused(){return F.paused},activate:function(e){if(F.active)return this;var t=O(e,"onActivate"),n=O(e,"onPostActivate"),o=O(e,"checkCanFocusTrap");o||T(),F.active=!0,F.paused=!1,F.nodeFocusedBeforeActivation=D(w),null==t||t();var r=function(){o&&T(),B(),_(),null==n||n()};return o?(o(F.containers.concat()).then(r,r),this):(r(),this)},deactivate:function(e){if(!F.active)return this;var t=s({onDeactivate:N.onDeactivate,onPostDeactivate:N.onPostDeactivate,checkCanReturnFocus:N.checkCanReturnFocus},e);clearTimeout(F.delayInitialFocusTimer),F.delayInitialFocusTimer=void 0,C(),F.active=!1,F.paused=!1,_(),d(g,u);var n=O(t,"onDeactivate"),o=O(t,"onPostDeactivate"),r=O(t,"checkCanReturnFocus"),a=O(t,"returnFocus","returnFocusOnDeactivate");null==n||n();var i=function(){p((function(){a&&G(x(F.nodeFocusedBeforeActivation)),null==o||o()}))};return a&&r?(r(x(F.nodeFocusedBeforeActivation)).then(i,i),this):(i(),this)},pause:function(e){return F.active?(F.manuallyPaused=!0,this._setPausedState(!0,e)):this},unpause:function(e){return F.active?(F.manuallyPaused=!1,g[g.length-1]!==this?this:this._setPausedState(!1,e)):this},updateContainerElements:function(e){var t=[].concat(e).filter(Boolean);return F.containers=t.map((function(e){return"string"==typeof e?w.querySelector(e):e})),F.active&&T(),_(),this}},Object.defineProperties(u,{_isManuallyPaused:{value:function(){return F.manuallyPaused}},_setPausedState:{value:function(e,t){if(F.paused===e)return this;if(F.paused=e,e){var n=O(t,"onPause"),o=O(t,"onPostPause");null==n||n(),C(),_(),null==o||o()}else{var r=O(t,"onUnpause"),a=O(t,"onPostUnpause");null==r||r(),T(),B(),_(),null==a||a()}return this}}}),u.updateContainerElements(a),u};export{w as createFocusTrap}; //# sourceMappingURL=focus-trap.esm.min.js.map