UNPKG

react-screen-wake-lock

Version:

React implementation of the Screen Wake Lock API. It provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.

3 lines (2 loc) 2.07 kB
import*as e from"react";function r(e,r){try{var n=e()}catch(e){return r(e)}return n&&n.then?n.then(void 0,r):n}var n=function(e){return console.warn("[react-screen-wake-lock]: "+e)},t=function(t){var i=void 0===t?{}:t,o=i.onError,u=i.onRequest,c=i.onRelease,s=i.reacquireOnPageVisible,a=void 0!==s&&s,l=e.useState(),f=l[0],v=l[1],h=e.useRef(null),d="undefined"!=typeof window&&"wakeLock"in navigator,m=e.useCallback(function(e){void 0===e&&(e="screen");try{var t=null!=h.current;if(!d)return Promise.resolve(n("Calling the `request` function has no effect, Wake Lock Screen API isn't supported"));if(t)return Promise.resolve(n("Calling `request` multiple times without `release` has no effect"));var i=r(function(){return Promise.resolve(navigator.wakeLock.request(e)).then(function(e){h.current=e,h.current.onrelease=function(e){v(h.current&&h.current.released||!0),c&&c(e),h.current=null},u&&u(),v(h.current&&h.current.released||!1)})},function(e){o&&o(e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},[d,u,o,c]),P=e.useCallback(function(){try{return Promise.resolve(d?null===h.current?n("Calling `release` before `request` has no effect."):h.current?Promise.resolve(h.current.release()).then(function(e){}):void 0:n("Calling the `release` function has no effect, Wake Lock Screen API isn't supported"))}catch(e){return Promise.reject(e)}},[d]);return e.useEffect(function(){if(a){var e=function(){try{var e=function(){if(null===h.current&&"visible"===document.visibilityState){var e=r(function(){return Promise.resolve(m()).then(function(){})},function(e){null==o||o(e)});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(e&&e.then?e.then(function(){}):void 0)}catch(e){return Promise.reject(e)}};return document.addEventListener("visibilitychange",e),function(){document.removeEventListener("visibilitychange",e)}}},[a,m,o]),{isSupported:d,request:m,released:f,release:P,type:h.current&&h.current.type||void 0}};export{t as useWakeLock}; //# sourceMappingURL=react-screen-wake-lock.esm.js.map