react-recipes
Version:
A React Hooks utility library containing popular customized hooks
2 lines (1 loc) • 17.4 kB
JavaScript
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e=e||self).reactRecipes={},e.react)}(this,function(e,n){function t(e,t){var r=n.useState(function(){try{if("undefined"==typeof window)return t;var n=window.localStorage.getItem(e);return null!==n?JSON.parse(n):t}catch(e){return console.log(e),t}}),o=r[0],u=r[1];return[o,function(n){try{var t=n instanceof Function?n(o):n;u(t),window.localStorage.setItem(e,JSON.stringify(t))}catch(e){console.log(e)}}]}function r(e,t,r){var o=e.map(function(e){return window.matchMedia(e)}),u=function(){var e=o.findIndex(function(e){return e.matches});return void 0!==t[e]?t[e]:r},i=n.useState(u),c=i[0],a=i[1];return n.useEffect(function(){var e=function(){return a(u)};return o.forEach(function(n){return n.addListener(e)}),function(){return o.forEach(function(n){return n.removeListener(e)})}},[]),c}var o=!("undefined"==typeof window||!window.document||!window.document.createElement);function u(e,t,r){void 0===r&&(r=o?window:void 0);var u=n.useRef();n.useEffect(function(){u.current=t},[t]),n.useEffect(function(){if(r&&r.addEventListener){var n=function(e){return u.current(e)};return r.addEventListener(e,n),function(){r.removeEventListener(e,n)}}},[e,r])}function i(e){return e&&e.current?Boolean(document.fullscreenElement===e.current||document.mozFullScreenElement===e.current||document.webkitFullscreenElement===e.current||document.msFullscreenElement===e.current):Boolean(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement||document.fullscreen||document.mozFullScreen||document.webkitIsFullScreen||document.fullScreenMode)}function c(){return(c=Object.assign||function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e}).apply(this,arguments)}var a={enableHighAccuracy:!1,timeout:Infinity,maximumAge:0};function s(){return{pathname:window.location.pathname,search:window.location.search}}var f=[];function d(){var e=n.useState(s()),t=e[0],r=t.pathname,o=t.search,u=e[1];function i(){f.forEach(function(e){return e()})}function c(){u(s())}return n.useEffect(function(){return f.push(c),window.addEventListener("popstate",c),function(){f.splice(f.indexOf(c),1),window.removeEventListener("popstate",c)}},[]),{push:function(e){window.history.pushState(null,null,e),i()},replace:function(e){window.history.replaceState(null,null,e),i()},pathname:r,search:o}}var l={position:"absolute",zIndex:999999,backgroundColor:"white",top:0,bottom:0,left:0,right:0},v=[],m=function(e,t){var r=n.useRef(function(){throw new Error("Cannot call an event handler while rendering.")});return n.useEffect(function(){r.current=e},[e].concat(t)),n.useCallback(function(e){return(0,r.current)(e)},[r])};o&&(window.SpeechRecognition=window.SpeechRecognition||window.webkitSpeechRecognition);var w=function(){},p=function(){};e.useAdjustColor=function(e,t,r,o){return n.useMemo(function(){return function(e,n,t,r){var o,u,i,c,a,s,f,d=parseInt,l=Math.round,v="string"==typeof t;if("number"!=typeof e||e<-1||e>1||"string"!=typeof n||"r"!=n[0]&&"#"!=n[0]||t&&!v)return null;var m=function(e){var n=e.length,t={};if(n>9){var r;if(r=e=e.split(","),o=r[0],u=r[1],i=r[2],v=r[3],(n=e.length)<3||n>4)return null;t.r=d(o.slice("a"==o[3]?5:4)),t.g=d(u),t.b=d(i),t.a=v?parseFloat(v):-1}else{if(8==n||6==n||n<4)return null;n<6&&(e="#"+e[1]+e[1]+e[2]+e[2]+e[3]+e[3]+(n>4?e[4]+e[4]:"")),e=d(e.slice(1),16),9==n||5==n?(t.r=e>>24&255,t.g=e>>16&255,t.b=e>>8&255,t.a=l((255&e)/.255)/1e3):(t.r=e>>16,t.g=e>>8&255,t.b=255&e,t.a=-1)}return t};return f=n.length>9,f=v?t.length>9||"c"==t&&!f:f,a=m(n),c=e<0,s=t&&"c"!=t?m(t):c?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},c=1-(e=c?-1*e:e),a&&s?(r?(o=l(c*a.r+e*s.r),u=l(c*a.g+e*s.g),i=l(c*a.b+e*s.b)):(o=l(Math.pow(c*Math.pow(a.r,2)+e*Math.pow(s.r,2),.5)),u=l(Math.pow(c*Math.pow(a.g,2)+e*Math.pow(s.g,2),.5)),i=l(Math.pow(c*Math.pow(a.b,2)+e*Math.pow(s.b,2),.5))),s=s.a,v=(a=(v=a.a)>=0||s>=0)?v<0?s:s<0?v:v*c+s*e:0,f?"rgb"+(a?"a(":"(")+o+","+u+","+i+(a?","+l(1e3*v)/1e3:"")+")":"#"+(4294967296+16777216*o+65536*u+256*i+(a?l(255*v):0)).toString(16).slice(1,a?void 0:-2)):null}(e,t,r,o)},[e,t,r,o])},e.useArray=function(e){var t=n.useState(e),r=t[1];return{value:t[0],setValue:r,add:n.useCallback(function(e){return r(function(n){return[].concat(n,[e])})},[]),clear:n.useCallback(function(){return r(function(){return[]})},[]),removeById:n.useCallback(function(e){return r(function(n){return n.filter(function(n){return n&&n.id!==e})})},[]),removeIndex:n.useCallback(function(e){return r(function(n){return n.filter(function(n,t){return t!==e})})},[])}},e.useAsync=function(e,t){void 0===t&&(t=!0);var r=n.useState(!1),o=r[0],u=r[1],i=n.useState(null),c=i[0],a=i[1],s=n.useState(null),f=s[0],d=s[1],l=n.useCallback(function(){return d(null),u(!0),a(null),e().then(function(e){return a(e)}).catch(function(e){return d(e)}).finally(function(){return u(!1)})},[e]);return n.useEffect(function(){t&&l()},[l,t]),{error:f,execute:l,pending:o,value:c}},e.useCookie=function(e,t){var r=n.useState(function(){return n=e,document.cookie.split("; ").reduce(function(e,t){var r=t.split("=");return r[0]===n?decodeURIComponent(r[1]):e},"")||t;var n}),o=r[1],u=function(n,t,r){void 0===t&&(t=365),void 0===r&&(r="/"),o(n),function(e,n,t,r){var o=new Date(Date.now()+864e5*t).toUTCString();document.cookie=e+"="+encodeURIComponent(n)+"; expires="+o+"; path="+r}(e,n,t,r)};return[r[0],u,function(e){void 0===e&&(e="/"),u("",-1,e),o(null)}]},e.useCopyClipboard=function(e){void 0===e&&(e=2e3);var t=n.useState(!1),r=t[0],o=t[1];return n.useEffect(function(){if(r){var n=setTimeout(function(){o(!1)},e);return function(){return clearTimeout(n)}}},[r,e]),[r,function(e){var n=function(e){var n=document.createElement("textarea"),t=window.navigator.userAgent.match(/ipad|iphone/i),r=window.pageYOffset||document.documentElement.scrollTop;if(n.contentEditable=!0,n.readOnly=!1,n.value=e,n.style.border="0",n.style.padding="0",n.style.margin="0",n.style.position="absolute",n.style.top=r+"px",document.body.appendChild(n),t){var o=document.createRange();o.selectNodeContents(n);var u=window.getSelection();u.removeAllRanges(),u.addRange(o),n.setSelectionRange(0,999999)}else n.select();var i=!1;try{i=document.execCommand("copy")}catch(n){try{window.clipboardData.setData("text",e),i=!0}catch(e){console.error("unable to copy using clipboardData: ",e)}}return document.body.removeChild(n),i}(e);o(n)}]},e.useDarkMode=function(){var e=t("dark-mode-enabled"),o=e[0],u=e[1],i=r(["(prefers-color-scheme: dark)"],[!0],!1),c=void 0!==o?o:i;return n.useEffect(function(){var e=window.document.body;c?e.classList.add("dark-mode"):e.classList.remove("dark-mode")},[c]),[c,u]},e.useDebounce=function(e,t){var r=n.useState(e),o=r[0],u=r[1];return n.useEffect(function(){var n=setTimeout(function(){u(e)},t);return function(){clearTimeout(n)}},[e,t]),o},e.useDimensions=function(e,t,r,o){void 0===e&&(e=!0),void 0===t&&(t=250),void 0===r&&(r={}),void 0===o&&(o=[]);var u=n.useState(r),i=u[0],c=u[1],a=n.useState(null),s=a[0],f=a[1],d=n.useCallback(function(e){f(e)},[]);return n.useLayoutEffect(function(){if(s){var n,r,o,u=function(){window.requestAnimationFrame(function(){var e=s.getBoundingClientRect();c(e)})};if(u(),e){var i=(n=u,r=t,function(){var e=[].slice.call(arguments),t=this,u=function(){o=null,n.apply(t,e)},i=void 0;clearTimeout(o),o=setTimeout(u,r),i&&n.apply(t,e)});if("ResizeObserver"in window){var a=new ResizeObserver(i);return a.observe(s),window.addEventListener("scroll",i),function(){a.disconnect(),window.removeEventListener("scroll",i)}}return window.addEventListener("resize",i),window.addEventListener("scroll",i),function(){window.removeEventListener("resize",i),window.removeEventListener("scroll",i)}}}},[s,e].concat(o)),[d,i,s]},e.useEventListener=u,e.useFullScreen=function(e){var t=!!o&&i(e),r=n.useState(t),u=r[0],c=r[1];function a(){var n=e&&e.current||document.documentElement;return n.requestFullscreen?n.requestFullscreen():n.mozRequestFullScreen?n.mozRequestFullScreen():n.webkitRequestFullscreen?n.webkitRequestFullscreen():n.msRequestFullscreen?n.msRequestFullscreen():void 0}function s(){return document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.msExitFullscreen?document.msExitFullscreen():void 0}return n.useEffect(function(){function n(){c(i(e))}return document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1),document.addEventListener("msfullscreenchange",n,!1),document.addEventListener("MSFullscreenChange",n,!1),document.addEventListener("fullscreenchange",n,!1),function(){document.removeEventListener("webkitfullscreenchange",n),document.removeEventListener("mozfullscreenchange",n),document.removeEventListener("msfullscreenchange",n),document.removeEventListener("MSFullscreenChange",n),document.removeEventListener("fullscreenchange",n)}},[e]),{fullScreen:u,open:a,close:s,toggle:u?s:a}},e.useGeolocation=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=a);var r=n.useState({}),o=r[0],u=r[1],i=n.useState(null),s=i[0],f=i[1],d=function(e){var n=e.coords;u({latitude:n.latitude,longitude:n.longitude,accuracy:n.accuracy,timestamp:e.timestamp})},l=function(e){f(e.message)};return n.useEffect(function(){var n=navigator.geolocation;if(n){var r=null;return e?r=n.watchPosition(d,l,t):n.getCurrentPosition(d,l,t),function(){return r&&n.clearWatch(r)}}f("Geolocation is not supported")},[t]),c({},o,{error:s})},e.useHover=function(){var e=n.useState(!1),t=e[0],r=e[1],o=n.useCallback(function(){return r(!0)},[]),u=n.useCallback(function(){return r(!1)},[]),i=n.useRef();return[n.useCallback(function(e){i.current&&(i.current.removeEventListener("mouseover",o),i.current.removeEventListener("mouseout",u)),i.current=e,i.current&&(i.current.addEventListener("mouseover",o),i.current.addEventListener("mouseout",u))},[o,u]),t]},e.useInterval=function(e,t,r,o){void 0===r&&(r=!1),void 0===o&&(o=[]);var u=n.useRef();n.useEffect(function(){r&&e()},[].concat(o)),n.useEffect(function(){u.current=e},[e]),n.useEffect(function(){if(null!==t){var e=setInterval(function(){return u.current()},t);return function(){return clearInterval(e)}}},[t].concat(o))},e.useIsClient=function(){return o},e.useKeyPress=function(e){var t=n.useState(!1),r=t[0],o=t[1];return u("keydown",function(n){n.key===e&&o(!0)}),u("keyup",function(n){n.key===e&&o(!1)}),r},e.useLocalStorage=t,e.useLocation=d,e.useLockBodyScroll=function(){n.useLayoutEffect(function(){var e=window.getComputedStyle(document.body).overflow;return document.body.style.overflow="hidden",function(){document.body.style.overflow=e}},[])},e.useMedia=r,e.useMultiKeyPress=function(){var e=n.useState(new Set([])),t=e[0],r=e[1];return u("keydown",function(e){r(t.add(e.key))}),u("keyup",function(e){t.delete(e.key),r(t)}),t},e.useNotification=function(e,t){var r=n.useCallback(function(){"Notification"in window&&("granted"!==Notification.permission?Notification.requestPermission().then(function(n){"granted"===n&&Notification(e,t)}):Notification(e,t))},[]);if("Notification"in window)return r},e.useOnClickOutside=function(e,t){n.useEffect(function(){var n=function(n){e.current&&!e.current.contains(n.target)&&t(n)};return document.addEventListener("mousedown",n),document.addEventListener("touchstart",n),function(){document.removeEventListener("mousedown",n),document.removeEventListener("touchstart",n)}},[e,t])},e.useOnlineStatus=function(){var e=n.useState("undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine),t=e[0],r=e[1];return u("online",function(){return r(!0)}),u("offline",function(){return r(!1)}),t},e.usePrevious=function(e){var t=n.useRef();return n.useEffect(function(){t.current=e},[e]),t.current},e.usePrint=function(e){void 0===e&&(e={});var t=n.useRef(null);return n.useEffect(function(){var n,r=function(e){return Object.entries(e).map(function(e){var n=e[1];return[e[0].split(/(?=[A-Z])/).join("-").toLowerCase(),n].join(":")}).join(";")}(c({},l,e)),o=function(){console.log("hi"),(n=document.createElement("div")).style=r;var e=t.current.cloneNode(!0);n.appendChild(e),document.body.appendChild(n)},u=function(){n.parentNode.removeChild(n)};return window.addEventListener("beforeprint",o),window.addEventListener("afterprint",u),function(){window.removeEventListener("beforeprint",o),window.removeEventListener("afterprint",u)}},[t,e]),{ref:t,handlePrint:function(){window.print()}}},e.useQueryParams=function(){var e=d(),n=e.replace,t=e.search;return{getParams:function(){var e=new URLSearchParams(t);return Object.fromEntries(e.entries())},setParams:function(e){var t=new URLSearchParams(e).toString();n("?"+t)}}},e.useScript=function(e){var t=n.useState({loaded:!1,error:!1}),r=t[0],o=t[1];return n.useEffect(function(){if(!v.includes(e)){v.push(e);var n=document.createElement("script");n.src=e,n.async=!0;var t=function(){o({loaded:!0,error:!1})},r=function(){var t=v.indexOf(e);t>=0&&v.splice(t,1),n.remove(),o({loaded:!0,error:!0})};return n.addEventListener("load",t),n.addEventListener("error",r),document.body.appendChild(n),function(){n.removeEventListener("load",t),n.removeEventListener("error",r)}}o({loaded:!0,error:!1})},[e]),[r.loaded,r.error]},e.useSpeechRecognition=function(e){void 0===e&&(e={});var t=e.onEnd,r=void 0===t?w:t,o=e.onResult,u=void 0===o?w:o,i=e.onError,c=void 0===i?w:i,a=n.useRef(null),s=n.useState(!1),f=s[0],d=s[1],l=!!window.SpeechRecognition||!!window.webkitSpeechRecognition,v=function(e){var n=Array.from(e.results).map(function(e){return e[0]}).map(function(e){return e.transcript});u(n)},p=function(e){"not-allowed"===e.error&&(a.current.onend=function(){},d(!1)),c(e)},h=m(function(e){if(void 0===e&&(e={}),!f&&l){var n=e.lang,t=void 0===n?"":n,r=e.interimResults,o=void 0===r||r,u=e.continuous,i=void 0!==u&&u,c=e.maxAlternatives,s=void 0===c?1:c,m=e.grammars;d(!0),a.current.lang=t,a.current.interimResults=o,a.current.onresult=v,a.current.onerror=p,a.current.continuous=i,a.current.maxAlternatives=s,m&&(a.current.grammars=m),a.current.onend=function(){return a.current.start()},a.current.start()}},[f,l,a]),g=m(function(){f&&l&&(a.current.onresult=function(){},a.current.onend=function(){},a.current.onerror=function(){},d(!1),a.current.stop(),r())},[f,l,a,r]);return n.useEffect(function(){l&&(a.current=new window.SpeechRecognition)},[]),{listen:h,listening:f,stop:g,supported:l}},e.useSpeechSynthesis=function(e){void 0===e&&(e={});var t=e.onBoundary,r=e.onEnd,o=void 0===r?p:r,u=e.onError,i=void 0===u?p:u,c=e.onPause,a=void 0===c?p:c,s=e.onResume,f=void 0===s?p:s,d=n.useState([]),l=d[0],v=d[1],m=n.useState(!1),w=m[0],h=m[1],g=!!window.speechSynthesis,E=function(e){v(e)},y=function(){h(!1),o()},S=function(e){h(!1),i(e)};return n.useEffect(function(){var e;return g&&((e=window.speechSynthesis.getVoices()).length>0?E(e):window.speechSynthesis.onvoiceschanged=function(n){e=n.target.getVoices(),E(e)}),function(){g&&window.speechSynthesis.cancel()}},[]),{supported:g,speak:function(e){void 0===e&&(e={});var n=e.voice,r=void 0===n?null:n,o=e.text,u=void 0===o?"":o,i=e.rate,c=void 0===i?1:i,s=e.pitch,d=void 0===s?1:s,l=e.volume,v=void 0===l?1:l,m=e.lang,w=void 0===m?"en-US":m,p=e.continuous,E=void 0!==p&&p;if(g){window.speechSynthesis.cancel();var b=new window.SpeechSynthesisUtterance;b.lang=w,b.text=u,b.voice=r,b.rate=c,b.pitch=d,b.volume=v,b.continuous=E,b.onend=y,b.onerror=S,b.onpause=a,b.onresume=f,t&&(b.onboundary=t),window.speechSynthesis.speak(b),h(!0)}},speaking:w,voices:l,cancel:function(){g&&(h(!1),window.speechSynthesis.cancel())},pause:function(){w&&g&&(window.speechSynthesis.pause(),h(!1))},resume:function(){!w&&g&&(window.speechSynthesis.resume(),h(!0))}}},e.useThrottle=function(e,t){void 0===t&&(t=200);var r=n.useState(e),o=r[0],u=r[1],i=n.useRef(),c=n.useRef(null),a=n.useRef(0);return n.useEffect(function(){i.current?(c.current=e,a.current=!0):(u(e),i.current=setTimeout(function e(){a.current?(a.current=!1,u(c.current),i.current=setTimeout(e,t)):i.current=void 0},t))},[e]),n.useEffect(function(){return function(){return i.current&&clearTimeout(i.current)}}),o},e.useWhyDidYouUpdate=function(e,t){var r=n.useRef();n.useEffect(function(){if(r.current){var n=Object.keys(c({},r.current,t)),o={};n.forEach(function(e){r.current[e]!==t[e]&&(o[e]={from:r.current[e],to:t[e]})}),Object.keys(o).length&&console.log("[why-did-you-update]",e,o)}r.current=t})},e.useWindowScroll=function(){var e=n.useState({x:o?window.pageXOffset:0,y:o?window.pageYOffset:0}),t=e[0],r=e[1];return n.useEffect(function(){var e=function(){r({x:window.pageXOffset,y:window.pageYOffset})};return window.addEventListener("scroll",e,{capture:!1,passive:!0}),function(){window.removeEventListener("scroll",e)}},[]),t},e.useWindowSize=function(e,t){var r=n.useState({width:o?window.innerWidth:e,height:o?window.innerHeight:t}),i=r[0],c=r[1];return u("resize",function(){c({width:window.innerWidth,height:window.innerHeight})}),i},e.useWorker=function(e,t,r){var o=n.useState(void 0),u=o[0],i=o[1];return n.useEffect(function(){var n=new Worker(e,t);if(r)for(var o in r)n[o]=r[o];return i(n),function(){n.terminate(),i(void 0)}},[e]),u}});