react-cool-onclickoutside
Version:
React hook to listen for clicks outside of the component(s).
2 lines (1 loc) • 1.96 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),n=function(e,n){var t;return null==(t=e.classList)?void 0:t.contains(n)},t=function(e,t){for(var r=e.target||e;r;){if(Array.isArray(t)){if(t.some((function(e){return n(r,e)})))return!0}else if(n(r,t))return!0;r=r.parentElement}return!1},r=function(e){return!(!e.includes("touch")||!function(){if("undefined"==typeof window||"function"!=typeof window.addEventListener)return!1;var e=!1,n=Object.defineProperty({},"passive",{get:function(){e=!0}}),t=function(){return null};return window.addEventListener("test",t,n),window.removeEventListener("test",t,n),e}())&&{passive:!0}};exports.DEFAULT_IGNORE_CLASS="ignore-onclickoutside",exports.default=function(n,u){var i=void 0===u?{}:u,o=i.refs,c=i.disabled,s=i.eventTypes,f=void 0===s?["mousedown","touchstart"]:s,d=i.excludeScrollbar,a=i.ignoreClass,l=void 0===a?"ignore-onclickoutside":a,v=i.detectIFrame,m=void 0===v||v,E=e.useState([]),w=E[0],p=E[1],g=e.useRef(n);g.current=n;var h=e.useCallback((function(e){return p((function(n){return[].concat(n,[{current:e}])}))}),[]);return e.useEffect((function(){if(null!=o&&o.length||w.length){var e=function(){var e=[];return(o||w).forEach((function(n){var t=n.current;return t&&e.push(t)})),e},n=function(n){t(n,l)||d&&function(e){return document.documentElement.clientWidth<=e.clientX||document.documentElement.clientHeight<=e.clientY}(n)||!e().every((function(e){return!e.contains(n.target)}))||g.current(n)},u=function(n){return setTimeout((function(){var r=document.activeElement;"IFRAME"!==(null==r?void 0:r.tagName)||t(r,l)||e().includes(r)||g.current(n)}),0)},i=function(){f.forEach((function(e){return document.removeEventListener(e,n,r(e))})),m&&window.removeEventListener("blur",u)};if(!c)return f.forEach((function(e){return document.addEventListener(e,n,r(e))})),m&&window.addEventListener("blur",u),function(){return i()};i()}}),[w,l,d,c,m,JSON.stringify(f)]),h};