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