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