@gmana/react-hooks
Version:
1 lines • 16 kB
JavaScript
import{useCallback as e,useEffect as t,useLayoutEffect as n,useMemo as r,useReducer as i,useRef as a,useState as o}from"react";function s(e){let[t,n]=o(e);function r(e){n(t=>[...t,e])}function i(e){n(t=>t.filter(e))}function a(e,t){n(n=>[...n.slice(0,e),t,...n.slice(e+1,n.length)])}function s(e){n(t=>[...t.slice(0,e),...t.slice(e+1,t.length)])}function c(){n([])}return{array:t,set:n,push:r,filter:i,update:a,remove:s,clear:c}}function c(e,n){t(()=>{let t=!1;return e(()=>t).catch(e=>{t||console.error(`Async effect error:`,e)}),()=>{t=!0}},[...n??[],e])}function l(e){let[t,n]=o(!!e);return{value:t,setValue:n,setTrue:()=>n(!0),setFalse:()=>n(!1),toggle:()=>n(e=>!e)}}function u(){let[t,n]=o(!1);return{isCopied:t,copyToClipboard:e(async e=>{if(typeof window>`u`||typeof navigator>`u`||typeof document>`u`){console.warn(`Clipboard API not available in server environment`),n(!1);return}if(navigator.clipboard&&window.isSecureContext)try{await navigator.clipboard.writeText(e),n(!0)}catch(e){console.error(e),n(!1)}else{let t=document.createElement(`textarea`);t.value=e,document.body.appendChild(t),t.focus(),t.select();try{n(document.execCommand(`copy`))}catch(e){console.error(e),n(!1)}document.body.removeChild(t)}},[])}}const d=typeof window<`u`,f=e=>{let{days:t,path:n,...r}=e,i=[];n&&i.push(`path=${n}`);for(let[e,t]of Object.entries(r))t===!0?i.push(e):t!==!1&&i.push(`${e}=${t}`);if(t){let e=new Date(Date.now()+t*864e5).toUTCString();i.push(`expires=${e}`)}return i.length?`; ${i.join(`; `)}`:``},p=(e,t,n={})=>{if(!d)return;let r={days:7,path:`/`,sameSite:`lax`,...n};document.cookie=`${e}=${encodeURIComponent(t)}${f(r)}`},m=(e,t=``)=>d?document.cookie.split(`; `).reduce((e,t)=>{let[n,r]=t.split(`=`,2);return e[n]=decodeURIComponent(r),e},{})[e]??t:t,h=e=>{d&&(document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`)};function g({timeout:e=2e3,onCopy:t}={}){let[n,r]=o(!1);return{isCopied:n,copyToClipboard:n=>{typeof window>`u`||!navigator.clipboard.writeText||n&&navigator.clipboard.writeText(n).then(()=>{r(!0),t&&t(),e!==0&&setTimeout(()=>{r(!1)},e)},console.error)}}}function _(n=60){let{initialTime:r=typeof n==`number`?n:60,onComplete:i,onTick:s}=typeof n==`number`?{initialTime:n}:n,[c,l]=o(0),[u,d]=o(!1),f=a(null),p=a(null),m=e(()=>{f.current&&=(clearInterval(f.current),null)},[]),h=e(()=>{m(),l(r),d(!0),p.current=Date.now()+r*1e3},[r,m]),g=e(()=>{m(),l(0),d(!1),p.current=null},[m]),_=e(()=>{m(),d(!1),p.current=null},[m]),v=e(()=>{c>0&&(d(!0),p.current=Date.now()+c*1e3)},[c]);return t(()=>{if(!u||c===0){m();return}return f.current=setInterval(()=>{if(!p.current)return;let e=Math.max(0,Math.ceil((p.current-Date.now())/1e3));l(e),s?.(e),e===0&&(d(!1),m(),p.current=null,i?.())},100),m},[u,m,i,s]),{timeLeft:c,isActive:u,startTimer:h,resetTimer:g,pauseTimer:_,resumeTimer:v,canResend:!u&&c===0}}function v(e){let[t,n]=o(e||0);return{count:t,increment:()=>n(e=>e+1),decrement:()=>n(e=>e-1),reset:()=>n(e||0),setCount:n}}const y=typeof window<`u`?n:t;function b(e,n,r){let i=a(n);y(()=>{i.current=n},[n]),t(()=>{if(typeof window>`u`)return;let t=r?.current||window;if(!t?.addEventListener)return;let n=e=>i.current(e);return t.addEventListener(e,n),()=>{t.removeEventListener(e,n)}},[e,r])}function x(n,r){let i=e(()=>{if(typeof window>`u`)return r;try{let e=window.localStorage.getItem(n);return e?S(e):r}catch(e){return console.warn(`Error reading localStorage key “${n}”:`,e),r}},[r,n]),[a,s]=o(i),c=e(e=>{typeof window>`u`&&console.warn(`Tried setting localStorage key “${n}” even though environment is not a client`);try{let t=e instanceof Function?e(a):e;window.localStorage.setItem(n,JSON.stringify(t)),s(t),window.dispatchEvent(new Event(`local-storage`))}catch(e){console.warn(`Error setting localStorage key “${n}”:`,e)}},[n,a]);t(()=>{s(i())},[i]);let l=e(()=>{s(i())},[i]);return b(`storage`,l),b(`local-storage`,l),[a,c]}function S(e){try{return e===`undefined`?void 0:JSON.parse(e??``)}catch{console.log(`parsing error on`,{value:e});return}}function C(e){let[n,r]=o(!1);return t(()=>{if(typeof window>`u`||!window.matchMedia)return;function t(e){r(e.matches)}let n=window.matchMedia(e);return n.addEventListener(`change`,t),r(n.matches),()=>n.removeEventListener(`change`,t)},[e]),n}function w(){let e=a(!0);return e.current?(e.current=!1,!0):e.current}function T(e,n){let r=w();t(()=>{if(!r)return e()},[...n??[],e,r])}function ee(e){let t=C(`(prefers-color-scheme: dark)`),[n,r]=x(`gmana-dark-mode`,e??t??!1);return T(()=>{r(t)},[t]),{isDarkMode:n,toggle:()=>r(e=>!e),enable:()=>r(!0),disable:()=>r(!1)}}function E(e,n=500){let{delay:r=500,leading:i=!1,trailing:s=!0,maxWait:c}=typeof n==`number`?{delay:n}:n,[l,u]=o(e),[d,f]=o(!1),p=a(null),m=a(null),h=a(0),g=a(0),_=a(!0),v=a(e);v.current=e;let y=()=>{p.current&&=(clearTimeout(p.current),null),m.current&&=(clearTimeout(m.current),null)},b=()=>{u(v.current),f(!1),g.current=Date.now()};return t(()=>{let e=Date.now(),t=e-g.current;if(h.current=e,i&&_.current&&(b(),_.current=!1,!s))return y;if(y(),s){if(f(!0),c!==void 0){let e=c-t;if(e>0)m.current=setTimeout(()=>{b(),y()},e);else{b();return}}return p.current=setTimeout(()=>{b(),y()},r),y}},[e,r,i,s,c]),t(()=>y,[]),typeof n==`number`?l:{value:l,flush:()=>{y(),d&&b()},cancel:()=>{y(),f(!1),_.current=!0},isPending:d}}function D(n,r){let{delay:i,leading:s=!1,trailing:c=!0,maxWait:l}=typeof r==`number`?{delay:r}:r,u=a(n),d=a(null),f=a(null),p=a(0),m=a(0),h=a(null),g=a(!0),[_,v]=o(!1);t(()=>{u.current=n},[n]);let y=e(()=>{d.current&&=(clearTimeout(d.current),null),f.current&&=(clearTimeout(f.current),null)},[]),b=e(()=>{h.current!==null&&(u.current(...h.current),m.current=Date.now(),v(!1))},[]),x=e(()=>{y(),_&&h.current!==null&&b()},[y,b,_]),S=e(()=>{y(),h.current=null,v(!1),g.current=!0},[y]),C=e(()=>_,[_]),w=e((...e)=>{let t=Date.now(),n=t-m.current;if(p.current=t,h.current=e,!(s&&g.current&&(u.current(...e),m.current=t,g.current=!1,!c))&&(y(),c)){if(v(!0),l!==void 0){let e=l-n;if(e>0)f.current=setTimeout(()=>{b(),y()},e);else{b();return}}d.current=setTimeout(()=>{b(),y()},i)}},[i,s,c,l,y,b]);t(()=>()=>{y()},[y]);let T=w;return T.flush=x,T.cancel=S,T.isPending=C,T}function O(e){let[n,r]=o({width:0,height:0});return t(()=>{let t=e.current;function n(){return{width:t?.offsetWidth||0,height:t?.offsetHeight||0}}let i=new ResizeObserver(e=>{e[0]&&r(n())});return t&&(i.observe(t),r(n())),()=>{t&&i.unobserve(t),i.disconnect()}},[e]),n}function k(e){t(e,[])}function A(){let[t,n]=o(null),[r,i]=o({width:0,height:0}),a=e(()=>{i({width:t?.offsetWidth||0,height:t?.offsetHeight||0})},[t?.offsetHeight,t?.offsetWidth]);return b(`resize`,a),y(()=>{a()},[t?.offsetHeight,t?.offsetWidth]),[n,r]}function j(){let[e,n]=o(0);return t(()=>{(async()=>{if(!(typeof navigator>`u`||!navigator.storage?.estimate))try{let e=await navigator.storage.estimate(),t=e?.usage??0;n(((e?.quota??0)-t)/1024/1024||0)}catch(e){console.warn(`Failed to estimate storage:`,e),n(0)}})()},[]),e}function M(e,n){let o=a({}),s=a(!1),c=r(()=>({error:void 0,data:void 0,isLoading:!1}),[]),[l,u]=i((e,t)=>{switch(t.type){case`loading`:return{...e,isLoading:!0,error:void 0};case`fetched`:return{...c,data:t.payload,isLoading:!1};case`error`:return{...c,error:t.payload,isLoading:!1};default:return e}},c);return t(()=>e?((async()=>{if(u({type:`loading`}),o.current[e]){u({type:`fetched`,payload:o.current[e]});return}try{let t=await fetch(e,n);if(!t.ok)throw Error(t.statusText);let r=await t.json();if(o.current[e]=r,s.current)return;u({type:`fetched`,payload:r})}catch(e){if(s.current)return;u({type:`error`,payload:e})}})(),()=>{s.current=!0}):void 0,[e,n]),l}function N(e=!0){let n=a(null);return t(()=>{if(typeof window>`u`||typeof document>`u`||!e||!n.current)return;let t=n.current,r=t.querySelectorAll(`a[href], button, textarea, input[type="text"], input[type="radio"], input[type="checkbox"], select, [tabindex]:not([tabindex="-1"])`),i=r[0],a=r[r.length-1];function o(e){e.key===`Tab`&&(e.shiftKey?document.activeElement===i&&(a?.focus(),e.preventDefault()):document.activeElement===a&&(i?.focus(),e.preventDefault()))}return t.addEventListener(`keydown`,o),i?.focus(),()=>{t.removeEventListener(`keydown`,o)}},[e]),n}function P(e){let[t,n]=o(!1);return b(`mouseenter`,()=>n(!0),e),b(`mouseleave`,()=>n(!1),e),t}function F(){let[e,n]=o(!1);return t(()=>{n(!0)},[]),e}function I(){let[e,t]=o(!1);return{handleImageOnLoad:()=>{t(!0)},css:{thumbnail:{visibility:e?`hidden`:`visible`,filter:`blur(8px)`,transition:`visibility 0ms ease-out 500ms`},fullSize:{opacity:e?1:0,transition:`opacity 500ms ease-in 0ms`}}}}const L=(e,n)=>{let[r,i]=o(!1);return t(()=>{if(!e.current)return;let t=e.current,r=new IntersectionObserver(([e])=>{i(e.isIntersecting)},{rootMargin:n});return r.observe(t),()=>r.unobserve(t)},[e,n]),r};function R(n,{threshold:r=0,root:i=null,rootMargin:a=`0%`,freezeOnceVisible:s=!1}){let[c,l]=o(),u=c?.isIntersecting&&s,d=e(([e])=>{l(e)},[]);return t(()=>{if(typeof window>`u`)return;let e=n?.current;if(!window.IntersectionObserver||u||!e)return;let t={threshold:r,root:i,rootMargin:a},o=new IntersectionObserver(d,t);return o.observe(e),()=>o.disconnect()},[n,r,i,a,u,d]),c}function z(e,n){let r=a(e);y(()=>{r.current=e},[e]),t(()=>{if(!n&&n!==0)return;let e=setInterval(()=>r.current(),n);return()=>clearInterval(e)},[n])}function B(){let[e,n]=o(!1);return t(()=>{n(!0)},[]),e}function V(){let n=a(!1);return t(()=>(n.current=!0,()=>{n.current=!1}),[]),e(()=>n.current,[])}function te(e=!1){let[n,r]=o(e);return y(()=>{if(typeof window>`u`||typeof document>`u`||!n)return;let e=document.body.style.overflow,t=document.body.style.paddingRight;document.body.style.overflow=`hidden`;let r=document.getElementById(`___gatsby`)||document.getElementById(`__next`)||document.body,i=r?r.offsetWidth-r.scrollWidth:0;return i&&(document.body.style.paddingRight=`${i}px`),()=>{document.body.style.overflow=e,i&&(document.body.style.paddingRight=t)}},[n]),t(()=>{n!==e&&r(e)},[e,n]),[n,r]}function H(t=new Map){let[n,r]=o(new Map(t));return[n,{set:e((e,t)=>{r(n=>{let r=new Map(n);return r.set(e,t),r})},[]),setAll:e(e=>{r(()=>new Map(e))},[]),remove:e(e=>{r(t=>{let n=new Map(t);return n.delete(e),n})},[]),reset:e(()=>{r(()=>new Map)},[])}]}function U(){let[e,n]=o(()=>typeof window>`u`?!1:window.innerWidth<768);return t(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 767px)`),t=()=>{n(window.innerWidth<768)};return e.addEventListener(`change`,t),n(window.innerWidth<768),()=>e.removeEventListener(`change`,t)},[]),e}const W=()=>{let[e,n]=o(null);return t(()=>{if(typeof window>`u`||typeof navigator>`u`)return;let e=()=>{let e=navigator.connection;e&&n({isOnline:navigator.onLine,effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt})};return e(),window.addEventListener(`load`,e),window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`load`,e),window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]),e},G=()=>{let[n,r]=o(()=>typeof navigator>`u`?!1:!navigator.onLine),i=e(()=>{typeof navigator<`u`&&r(!navigator.onLine)},[]);return t(()=>{if(typeof window>`u`||typeof navigator>`u`)return;r(!navigator.onLine);let e=K(i,300);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[i]),n},K=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}};function q(e,t,n=`mousedown`){b(n,n=>{let r=e?.current;!r||r.contains(n.target)||t(n)})}function J(e){let n=a(void 0);return t(()=>{n.current=e},[e]),n.current}function Y(n){let r=e(()=>{if(typeof window>`u`)return null;try{let e=window.localStorage.getItem(n);return e?JSON.parse(e):null}catch(e){return console.warn(`Error reading localStorage key “${n}”:`,e),null}},[n]),[i,a]=o(r);t(()=>{a(r())},[r]);let s=e(()=>{a(r())},[r]);return b(`storage`,s),b(`local-storage`,s),i}function X(){let e=()=>{if(window?.screen)return window.screen},[t,n]=o(e());function r(){n(e())}return b(`resize`,r),y(()=>{r()},[]),t}function Z(e){let[n,r]=o(()=>typeof window>`u`?`idle`:e?`loading`:`idle`);return t(()=>{if(typeof window>`u`||typeof document>`u`)return;if(!e){r(`idle`);return}let t=document.querySelector(`script[src="${e}"]`);if(t)r(t.getAttribute(`data-status`));else{t=document.createElement(`script`),t.src=e,t.async=!0,t.setAttribute(`data-status`,`loading`),document.body.appendChild(t);let n=e=>{t?.setAttribute(`data-status`,e.type===`load`?`ready`:`error`)};t.addEventListener(`load`,n),t.addEventListener(`error`,n)}let n=e=>{r(e.type===`load`?`ready`:`error`)};return t.addEventListener(`load`,n),t.addEventListener(`error`,n),()=>{t&&(t.removeEventListener(`load`,n),t.removeEventListener(`error`,n))}},[e]),n}function Q(e=20){let[n,r]=o(!1);return t(()=>{if(typeof window>`u`)return;function t(){r(window.scrollY>e)}return window.addEventListener(`scroll`,t),t(),()=>window.removeEventListener(`scroll`,t)},[e]),n}function ne(){let[e,t]=o(`open`);return{open:e===`open`,onOpenChange:e=>t(e?`open`:`closed`)}}function re(){let e=typeof window<`u`&&!!window?.document?.documentElement;return{isBrowser:e,isServer:!e,isHydrated:e}}function ie(t){let[n,i]=o(1),a=r(()=>n+1<=t,[n,t]),s=r(()=>n-1>=1,[n]),c=e(e=>{let r=e instanceof Function?e(n):e;if(r>=1&&r<=t){i(r);return}throw Error(`Step not valid`)},[t,n]);return[n,{goToNextStep:e(()=>{a&&i(e=>e+1)},[a]),goToPrevStep:e(()=>{s&&i(e=>e-1)},[s]),canGoToNextStep:a,canGoToPrevStep:s,setStep:c,reset:e(()=>{i(1)},[])}]}function ae(){let e=C(`(prefers-color-scheme: dark)`),[n,r]=x(`gmana-ternary-dark-mode`,`system`),[i,a]=o(e);T(()=>{n===`system`&&a(e)},[e]),t(()=>{switch(n){case`light`:a(!1);break;case`system`:a(e);break;case`dark`:a(!0);break}},[n,e]);function s(){let e={light:`system`,system:`dark`,dark:`light`};r(t=>e[t])}return{isDarkMode:i,ternaryDarkMode:n,setTernaryDarkMode:r,toggleTernaryDarkMode:s}}function oe(t,n,r){let i=a(0),o=a(null);return e(((...e)=>{let r=Date.now();r-i.current>=n?(i.current=r,t(...e)):(o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{i.current=Date.now(),t(...e)},n-(r-i.current)))}),[...r??[],t,n])}function $(n,r){let i=a(n),o=a(null);t(()=>{i.current=n},[n]);let s=e(()=>{o.current=setTimeout(()=>i.current(),r)},[r]),c=e(()=>{o.current&&clearTimeout(o.current)},[]);return t(()=>(o.current=setTimeout(()=>i.current(),r),()=>{o.current&&clearTimeout(o.current)}),[r]),{reset:e(()=>{c(),s()},[c,s]),clear:c}}function se(e){let[t,n]=o(e);function r(e){n(t=>typeof e==`boolean`?e:!t)}return[t,r]}function ce(e=!0){t(()=>{if(typeof window>`u`||!e)return;let t=e=>{e.preventDefault()};return window.addEventListener(`beforeunload`,t),()=>window.removeEventListener(`beforeunload`,t)},[e])}function le(){let[e,t]=o(()=>typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}),n=()=>{typeof window<`u`&&t({width:window.innerWidth,height:window.innerHeight})};return b(`resize`,n),y(()=>{n()},[]),e}export{m as getCookie,h as removeCookie,p as setCookie,s as useArray,c as useAsyncEffect,l as useBoolean,u as useClipboard,g as useCopyToClipboard,_ as useCountdown,v as useCounter,ee as useDarkMode,E as useDebounce,D as useDebouncedCallback,O as useDimensions,k as useEffectOnce,A as useElementSize,j as useEstimateStorage,b as useEventListener,M as useFetch,N as useFocusTrap,P as useHover,F as useHydrated,I as useImageOnLoad,L as useIntersection,R as useIntersectionObserver,z as useInterval,B as useIsClient,w as useIsFirstRender,U as useIsMobile,V as useIsMounted,y as useIsomorphicLayoutEffect,x as useLocalStorage,te as useLockedBody,H as useMap,C as useMediaQuery,W as useNetworkInformation,G as useOfflineDetector,q as useOnClickOutside,J as usePrevious,Y as useReadLocalStorage,X as useScreen,Z as useScript,Q as useScroll,ne as useSidebar,re as useSsr,ie as useStep,ae as useTernaryDarkMode,oe as useThrottle,$ as useTimeout,se as useToggle,ce as useUnloadWarning,T as useUpdateEffect,le as useWindowSize};