@rokku-x/react-hook-loading-spinner 0.1.12 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,9 @@
1
- export { default } from '../mainLogic';
2
- export * from '../mainLogic';
1
+ export default function ssrLoading(): {
2
+ overrideLoading: (state: boolean | null) => void;
3
+ startLoading: () => void;
4
+ stopLoading: () => void;
5
+ readonly isLocalLoading: boolean;
6
+ asyncUseLoading: <R, _ extends any[]>(asyncFunction: Promise<R>) => Promise<R>;
7
+ readonly isLoading: boolean;
8
+ };
9
+ export * from '../store/loadingStore';
@@ -1,2 +1,9 @@
1
- export { default } from '../mainLogic';
2
- export * from '../mainLogic';
1
+ export default function useLoading(): {
2
+ overrideLoading: (state: boolean | null) => void;
3
+ startLoading: () => void;
4
+ stopLoading: () => void;
5
+ readonly isLocalLoading: boolean;
6
+ asyncUseLoading: <R, _ extends any[]>(asyncFunction: Promise<R>) => Promise<R>;
7
+ readonly isLoading: boolean;
8
+ };
9
+ export * from '../store/loadingStore';
package/dist/index.cjs.js CHANGED
@@ -1,10 +1,5 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("react/jsx-runtime"),m=require("react"),N=require("react-dom"),I=n=>{let t;const e=new Set,i=(f,r)=>{const d=typeof f=="function"?f(t):f;if(!Object.is(d,t)){const g=t;t=r??(typeof d!="object"||d===null)?d:Object.assign({},t,d),e.forEach(u=>u(t,g))}},o=()=>t,s={setState:i,getState:o,getInitialState:()=>p,subscribe:f=>(e.add(f),()=>e.delete(f))},p=t=n(i,o,s);return s},D=(n=>n?I(n):I),F=n=>n;function M(n,t=F){const e=m.useSyncExternalStore(n.subscribe,m.useCallback(()=>t(n.getState()),[n,t]),m.useCallback(()=>t(n.getInitialState()),[n,t]));return m.useDebugValue(e),e}const j=n=>{const t=D(n),e=i=>M(t,i);return Object.assign(e,t),e},P=(n=>n?j(n):j),T={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},C=new Map,x=n=>{const t=C.get(n);return t?Object.fromEntries(Object.entries(t.stores).map(([e,i])=>[e,i.getState()])):{}},$=(n,t,e)=>{if(n===void 0)return{type:"untracked",connection:t.connect(e)};const i=C.get(e.name);if(i)return{type:"tracked",store:n,...i};const o={connection:t.connect(e),stores:{}};return C.set(e.name,o),{type:"tracked",store:n,...o}},J=(n,t)=>{if(t===void 0)return;const e=C.get(n);e&&(delete e.stores[t],Object.keys(e.stores).length===0&&C.delete(n))},U=n=>{var t,e;if(!n)return;const i=n.split(`
2
- `),o=i.findIndex(v=>v.includes("api.setState"));if(o<0)return;const l=((t=i[o+1])==null?void 0:t.trim())||"";return(e=/.+ (.+) .+/.exec(l))==null?void 0:e[1]},z=(n,t={})=>(e,i,o)=>{const{enabled:l,anonymousActionType:v,store:s,...p}=t;let f;try{f=(l??(T?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!f)return n(e,i,o);const{connection:r,...d}=$(s,f,p);let g=!0;o.setState=((c,L,a)=>{const S=e(c,L);if(!g)return S;const _=a===void 0?{type:v||U(new Error().stack)||"anonymous"}:typeof a=="string"?{type:a}:a;return s===void 0?(r?.send(_,i()),S):(r?.send({..._,type:`${s}/${_.type}`},{...x(p.name),[s]:o.getState()}),S)}),o.devtools={cleanup:()=>{r&&typeof r.unsubscribe=="function"&&r.unsubscribe(),J(p.name,s)}};const u=(...c)=>{const L=g;g=!1,e(...c),g=L},E=n(o.setState,i,o);if(d.type==="untracked"?r?.init(E):(d.stores[d.store]=o,r?.init(Object.fromEntries(Object.entries(d.stores).map(([c,L])=>[c,c===d.store?E:L.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let c=!1;const L=o.dispatch;o.dispatch=(...a)=>{(T?"production":void 0)!=="production"&&a[0].type==="__setState"&&!c&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),c=!0),L(...a)}}return r.subscribe(c=>{var L;switch(c.type){case"ACTION":if(typeof c.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return w(c.payload,a=>{if(a.type==="__setState"){if(s===void 0){u(a.state);return}Object.keys(a.state).length!==1&&console.error(`
3
- [zustand devtools middleware] Unsupported __setState action format.
4
- When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
5
- and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
6
- `);const S=a.state[s];if(S==null)return;JSON.stringify(o.getState())!==JSON.stringify(S)&&u(S);return}o.dispatchFromDevtools&&typeof o.dispatch=="function"&&o.dispatch(a)});case"DISPATCH":switch(c.payload.type){case"RESET":return u(E),s===void 0?r?.init(o.getState()):r?.init(x(p.name));case"COMMIT":if(s===void 0){r?.init(o.getState());return}return r?.init(x(p.name));case"ROLLBACK":return w(c.state,a=>{if(s===void 0){u(a),r?.init(o.getState());return}u(a[s]),r?.init(x(p.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return w(c.state,a=>{if(s===void 0){u(a);return}JSON.stringify(o.getState())!==JSON.stringify(a[s])&&u(a[s])});case"IMPORT_STATE":{const{nextLiftedState:a}=c.payload,S=(L=a.computedStates.slice(-1)[0])==null?void 0:L.state;if(!S)return;u(s===void 0?S:S[s]),r?.send(null,a);return}case"PAUSE_RECORDING":return g=!g}return}}),E},W=z,w=(n,t)=>{let e;try{e=JSON.parse(n)}catch(i){console.error("[zustand devtools middleware] Could not parse the received json",i)}e!==void 0&&t(e)};class R extends EventTarget{constructor(){super(...arguments),this.controller=new AbortController}on(t,e){return this.addEventListener(t,i=>e(i.detail),{signal:this.controller.signal}),this}once(t,e){return this.addEventListener(t,i=>e(i.detail),{signal:this.controller.signal,once:!0}),this}emit(t,e){return this.dispatchEvent(new CustomEvent(t,{detail:e}))}removeAllListeners(){this.controller.abort(),this.controller=new AbortController}}const b=new R,V=P()(W((n,t)=>({loadingCount:0,overrideState:null,localCounters:{},isLoading(){return t().overrideState??t().loadingCount>0},actions:{isGlobalLoading(){return t().isLoading()},startLoading:e=>{const i=t().isLoading();n(l=>({loadingCount:l.loadingCount+1})),e&&n(l=>({localCounters:{...l.localCounters,[e]:(l.localCounters[e]??0)+1}}));const o=t().isLoading();o&&!i&&b.emit("start",null),b.emit("change",{isLoading:o,isOverrideState:t().overrideState!==null})},stopLoading:e=>{const i=t().isLoading(),o=e?t().localCounters[e]??0:0;e&&o>0&&n(v=>({loadingCount:Math.max(0,v.loadingCount-1),localCounters:{...v.localCounters,[e]:Math.max(0,v.localCounters[e]-1)}}));const l=t().isLoading();!l&&i&&b.emit("stop",null),b.emit("change",{isLoading:l,isOverrideState:t().overrideState!==null})},overrideLoading:e=>{const i=t().isLoading();n({overrideState:e});const o=t().isLoading();o&&!i?b.emit("start",null):!o&&i&&b.emit("stop",null),b.emit("change",{isLoading:o,isOverrideState:e!==null})},getLocalCounter:e=>t().localCounters[e]??0,isLocalLoading:e=>(t().localCounters[e]??0)>0}})));function O(){const n=m.useId(),{actions:t}=V(l=>l),e=()=>{t.startLoading(n)},i=()=>{t.isLocalLoading(n)&&t.stopLoading(n)},o=async l=>{e();try{return await l}finally{i()}};return{overrideLoading:t.overrideLoading,startLoading:e,stopLoading:i,get isLocalLoading(){return t.isLocalLoading(n)},asyncUseLoading:o,get isLoading(){return t.isGlobalLoading()}}}const y={Spin:"spin",FadeInOut:"fadeInOut",None:"none"},q=({scale:n=1,animationType:t=y.Spin,animationDuration:e,children:i,style:o,className:l,id:v,prefix:s})=>{const p=t,f=t===y.Spin?1:t===y.FadeInOut?2:0,r=e||f,d=t===y.Spin?"linear":t===y.FadeInOut?"ease-in-out":"linear",g=t===y.None?"none":`${s}-${p} ${r}s ${d} infinite`;return h.jsx("div",{style:{animation:g,...n!==1?{zoom:n}:{},...o},className:l,id:v,children:i})},A=n=>h.jsx("div",{id:"loading-circle",style:{width:"90px",height:"90px",border:"15px solid #f3f3f3",borderTop:"15px solid #009b4bff",borderRadius:"50%",boxSizing:"border-box"},...n}),k=n=>h.jsx("div",{style:{padding:"20px",fontSize:"25px",color:"#333",fontFamily:"system-ui, sans-serif"},...n,children:"Please wait..."});function B({loadingComponent:n,loadingComponentScale:t=1,animationType:e=y.Spin,animationDuration:i,wrapperStyle:o,wrapperClassName:l,wrapperId:v,animationWrapperStyle:s,animationWrapperClassName:p,animationWrapperId:f}){n=n||(e===y.Spin?A:k);const r=m.useRef(Math.random().toString(36).substring(2,6).replace(/[0-9]/g,"")),{isLoading:d}=O(),g=m.useRef(null);m.useEffect(()=>{d?(g.current?.showModal(),document.body.setAttribute("inert","")):(g.current?.close(),document.body.removeAttribute("inert"))},[d]);const u=v||"loading-wrapper-"+r.current;return d?N.createPortal(h.jsxs(h.Fragment,{children:[h.jsx("style",{children:`
7
- dialog#${u}[open] {
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react"),O=require("crypto"),L=require("react/jsx-runtime"),A=require("react-dom"),y=n=>{let t;const e=new Set,o=(s,l)=>{const d=typeof s=="function"?s(t):s;if(!Object.is(d,t)){const p=t;t=l??(typeof d!="object"||d===null)?d:Object.assign({},t,d),e.forEach(m=>m(t,p))}},r=()=>t,f={setState:o,getState:r,getInitialState:()=>b,subscribe:s=>(e.add(s),()=>e.delete(s))},b=t=n(o,r,f);return f},R=(n=>n?y(n):y),$=n=>n;function F(n,t=$){const e=a.useSyncExternalStore(n.subscribe,a.useCallback(()=>t(n.getState()),[n,t]),a.useCallback(()=>t(n.getInitialState()),[n,t]));return a.useDebugValue(e),e}const x=n=>{const t=R(n),e=o=>F(t,o);return Object.assign(e,t),e},k=(n=>n?x(n):x);class C extends EventTarget{constructor(){super(...arguments),this.controller=new AbortController}on(t,e){return this.addEventListener(t,o=>e(o.detail),{signal:this.controller.signal}),this}once(t,e){return this.addEventListener(t,o=>e(o.detail),{signal:this.controller.signal,once:!0}),this}emit(t,e){return this.dispatchEvent(new CustomEvent(t,{detail:e}))}removeAllListeners(){this.controller.abort(),this.controller=new AbortController}}const g=new C,v=k()((n,t)=>({loadingCount:0,overrideState:null,localCounters:{},isLoading(){return t().overrideState??t().loadingCount>0},actions:{isGlobalLoading(){return t().isLoading()},startLoading:e=>{const o=t().isLoading();n(i=>({loadingCount:i.loadingCount+1})),e&&n(i=>({localCounters:{...i.localCounters,[e]:(i.localCounters[e]??0)+1}}));const r=t().isLoading();r&&!o&&g.emit("start",null),g.emit("change",{isLoading:r,isOverrideState:t().overrideState!==null})},stopLoading:e=>{const o=t().isLoading(),r=e?t().localCounters[e]??0:0;e&&r>0&&n(u=>({loadingCount:Math.max(0,u.loadingCount-1),localCounters:{...u.localCounters,[e]:Math.max(0,u.localCounters[e]-1)}}));const i=t().isLoading();!i&&o&&g.emit("stop",null),g.emit("change",{isLoading:i,isOverrideState:t().overrideState!==null})},overrideLoading:e=>{const o=t().isLoading();n({overrideState:e});const r=t().isLoading();r&&!o?g.emit("start",null):!r&&o&&g.emit("stop",null),g.emit("change",{isLoading:r,isOverrideState:e!==null})},getLocalCounter:e=>t().localCounters[e]??0,isLocalLoading:e=>(t().localCounters[e]??0)>0}}));function w(){const n=a.useId(),{actions:t}=v(i=>i),e=()=>{t.startLoading(n)},o=()=>{t.isLocalLoading(n)&&t.stopLoading(n)},r=async i=>{e();try{return await i}finally{o()}};return{overrideLoading:t.overrideLoading,startLoading:e,stopLoading:o,get isLocalLoading(){return t.isLocalLoading(n)},asyncUseLoading:r,get isLoading(){return t.isGlobalLoading()}}}function M(){const n=O.randomUUID(),{actions:t}=v(i=>i),e=()=>{t.startLoading(n)},o=()=>{t.isLocalLoading(n)&&t.stopLoading(n)},r=async i=>{e();try{return await i}finally{o()}};return{overrideLoading:t.overrideLoading,startLoading:e,stopLoading:o,get isLocalLoading(){return t.isLocalLoading(n)},asyncUseLoading:r,get isLoading(){return t.isGlobalLoading()}}}const c={Spin:"spin",FadeInOut:"fadeInOut",None:"none"},N=({scale:n=1,animationType:t=c.Spin,animationDuration:e,children:o,style:r,className:i,id:u,prefix:f})=>{const b=t,s=t===c.Spin?1:t===c.FadeInOut?2:0,l=e||s,d=t===c.Spin?"linear":t===c.FadeInOut?"ease-in-out":"linear",p=t===c.None?"none":`${f}-${b} ${l}s ${d} infinite`;return L.jsx("div",{style:{animation:p,...n!==1?{zoom:n}:{},...r},className:i,id:u,children:o})},E=n=>L.jsx("div",{id:"loading-circle",style:{width:"90px",height:"90px",border:"15px solid #f3f3f3",borderTop:"15px solid #009b4bff",borderRadius:"50%",boxSizing:"border-box"},...n}),I=n=>L.jsx("div",{style:{padding:"20px",fontSize:"25px",color:"#333",fontFamily:"system-ui, sans-serif"},...n,children:"Please wait..."});function P({loadingComponent:n,loadingComponentScale:t=1,animationType:e=c.Spin,animationDuration:o,wrapperStyle:r,wrapperClassName:i,wrapperId:u,animationWrapperStyle:f,animationWrapperClassName:b,animationWrapperId:s}){n=n||(e===c.Spin?E:I);const l=a.useRef(Math.random().toString(36).substring(2,6).replace(/[0-9]/g,"")),{loadingCount:d,overrideState:p}=v(j=>j),m=p??d>0,S=a.useRef(null);a.useEffect(()=>{m?(S.current?.showModal(),document.body.setAttribute("inert","")):(S.current?.close(),document.body.removeAttribute("inert"))},[m]);const h=u||"loading-wrapper-"+l.current;return m?A.createPortal(L.jsxs(L.Fragment,{children:[L.jsx("style",{children:`
2
+ dialog#${h}[open] {
8
3
  display: flex !important;
9
4
  justify-content: center;
10
5
  align-items: center;
@@ -13,18 +8,18 @@
13
8
  max-width: 100%;
14
9
  max-height: 100%;
15
10
  }
16
- @keyframes ${r.current}-spin {
11
+ @keyframes ${l.current}-spin {
17
12
  0% { transform: rotate(0deg); }
18
13
  100% { transform: rotate(360deg); }
19
14
  }
20
- @keyframes ${r.current}-fadeInOut {
15
+ @keyframes ${l.current}-fadeInOut {
21
16
  0%, 100% { opacity: 0.2; }
22
17
  50% { opacity: 1; }
23
18
  }
24
- body:has(dialog#${u}[open]) {
19
+ body:has(dialog#${h}[open]) {
25
20
  overflow: hidden;
26
21
  }
27
22
  body {
28
23
  scrollbar-gutter: stable;
29
24
  }
30
- `}),h.jsx("dialog",{ref:g,style:{border:"none",padding:0,backgroundColor:"rgba(0, 0, 0, 0.5)",backdropFilter:"blur(2px)",...o},className:l,id:u,children:h.jsx(q,{scale:t,animationType:e,animationDuration:i,style:s,className:p,id:f,prefix:r.current,children:m.isValidElement(n)?n:m.createElement(n)})})]}),document.body):null}function G({isLoading:n=!1}){const{startLoading:t,stopLoading:e}=O();return m.useEffect(()=>(n?t():e(),()=>{n&&e()}),[n]),null}exports.AnimationType=y;exports.EventEmitter=R;exports.Loading=G;exports.LoadingCircle=A;exports.LoadingPleaseWait=k;exports.LoadingRenderer=B;exports.loadingEventTarget=b;exports.ssrLoading=O;exports.useLoading=O;
25
+ `}),L.jsx("dialog",{ref:S,style:{border:"none",padding:0,backgroundColor:"rgba(0, 0, 0, 0.5)",backdropFilter:"blur(2px)",...r},className:i,id:h,children:L.jsx(N,{scale:t,animationType:e,animationDuration:o,style:f,className:b,id:s,prefix:l.current,children:a.isValidElement(n)?n:a.createElement(n)})})]}),document.body):null}function q({isLoading:n=!1}){const{startLoading:t,stopLoading:e}=w();return a.useEffect(()=>(n?t():e(),()=>{n&&e()}),[n]),null}exports.AnimationType=c;exports.EventEmitter=C;exports.Loading=q;exports.LoadingCircle=E;exports.LoadingPleaseWait=I;exports.LoadingRenderer=P;exports.loadingEventTarget=g;exports.ssrLoading=M;exports.useLoading=w;
package/dist/index.d.ts CHANGED
@@ -5,4 +5,4 @@ export type { AnimationType as AnimationTypeType } from './components/LoadingRen
5
5
  export { default as Loading } from './components/Loading';
6
6
  export { default as LoadingRenderer } from './components/LoadingRenderer';
7
7
  export { default as EventEmitter } from './utils/EventEmitter';
8
- export { loadingEventTarget } from './mainLogic';
8
+ export { loadingEventTarget } from './store/loadingStore';
package/dist/index.esm.js CHANGED
@@ -1,232 +1,60 @@
1
1
  "use client";
2
- import { jsx as L, jsxs as N, Fragment as j } from "react/jsx-runtime";
3
- import y, { useId as D, useRef as x, useEffect as k } from "react";
4
- import { createPortal as F } from "react-dom";
5
- const I = (n) => {
2
+ import L, { useId as E, useRef as y, useEffect as w } from "react";
3
+ import { randomUUID as O } from "crypto";
4
+ import { jsx as f, jsxs as $, Fragment as j } from "react/jsx-runtime";
5
+ import { createPortal as A } from "react-dom";
6
+ const x = (n) => {
6
7
  let t;
7
- const e = /* @__PURE__ */ new Set(), r = (f, i) => {
8
- const d = typeof f == "function" ? f(t) : f;
9
- if (!Object.is(d, t)) {
10
- const g = t;
11
- t = i ?? (typeof d != "object" || d === null) ? d : Object.assign({}, t, d), e.forEach((u) => u(t, g));
8
+ const o = /* @__PURE__ */ new Set(), e = (a, s) => {
9
+ const l = typeof a == "function" ? a(t) : a;
10
+ if (!Object.is(l, t)) {
11
+ const p = t;
12
+ t = s ?? (typeof l != "object" || l === null) ? l : Object.assign({}, t, l), o.forEach((b) => b(t, p));
12
13
  }
13
- }, o = () => t, s = { setState: r, getState: o, getInitialState: () => p, subscribe: (f) => (e.add(f), () => e.delete(f)) }, p = t = n(r, o, s);
14
- return s;
15
- }, M = ((n) => n ? I(n) : I), $ = (n) => n;
16
- function P(n, t = $) {
17
- const e = y.useSyncExternalStore(
14
+ }, r = () => t, g = { setState: e, getState: r, getInitialState: () => m, subscribe: (a) => (o.add(a), () => o.delete(a)) }, m = t = n(e, r, g);
15
+ return g;
16
+ }, F = ((n) => n ? x(n) : x), k = (n) => n;
17
+ function N(n, t = k) {
18
+ const o = L.useSyncExternalStore(
18
19
  n.subscribe,
19
- y.useCallback(() => t(n.getState()), [n, t]),
20
- y.useCallback(() => t(n.getInitialState()), [n, t])
20
+ L.useCallback(() => t(n.getState()), [n, t]),
21
+ L.useCallback(() => t(n.getInitialState()), [n, t])
21
22
  );
22
- return y.useDebugValue(e), e;
23
+ return L.useDebugValue(o), o;
23
24
  }
24
- const T = (n) => {
25
- const t = M(n), e = (r) => P(t, r);
26
- return Object.assign(e, t), e;
27
- }, J = ((n) => n ? T(n) : T), R = { BASE_URL: "/", DEV: !1, MODE: "production", PROD: !0, SSR: !1 }, C = /* @__PURE__ */ new Map(), w = (n) => {
28
- const t = C.get(n);
29
- return t ? Object.fromEntries(
30
- Object.entries(t.stores).map(([e, r]) => [e, r.getState()])
31
- ) : {};
32
- }, U = (n, t, e) => {
33
- if (n === void 0)
34
- return {
35
- type: "untracked",
36
- connection: t.connect(e)
37
- };
38
- const r = C.get(e.name);
39
- if (r)
40
- return { type: "tracked", store: n, ...r };
41
- const o = {
42
- connection: t.connect(e),
43
- stores: {}
44
- };
45
- return C.set(e.name, o), { type: "tracked", store: n, ...o };
46
- }, z = (n, t) => {
47
- if (t === void 0) return;
48
- const e = C.get(n);
49
- e && (delete e.stores[t], Object.keys(e.stores).length === 0 && C.delete(n));
50
- }, V = (n) => {
51
- var t, e;
52
- if (!n) return;
53
- const r = n.split(`
54
- `), o = r.findIndex(
55
- (v) => v.includes("api.setState")
56
- );
57
- if (o < 0) return;
58
- const l = ((t = r[o + 1]) == null ? void 0 : t.trim()) || "";
59
- return (e = /.+ (.+) .+/.exec(l)) == null ? void 0 : e[1];
60
- }, W = (n, t = {}) => (e, r, o) => {
61
- const { enabled: l, anonymousActionType: v, store: s, ...p } = t;
62
- let f;
63
- try {
64
- f = (l ?? (R ? "production" : void 0) !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
65
- } catch {
66
- }
67
- if (!f)
68
- return n(e, r, o);
69
- const { connection: i, ...d } = U(s, f, p);
70
- let g = !0;
71
- o.setState = ((c, m, a) => {
72
- const S = e(c, m);
73
- if (!g) return S;
74
- const O = a === void 0 ? {
75
- type: v || V(new Error().stack) || "anonymous"
76
- } : typeof a == "string" ? { type: a } : a;
77
- return s === void 0 ? (i?.send(O, r()), S) : (i?.send(
78
- {
79
- ...O,
80
- type: `${s}/${O.type}`
81
- },
82
- {
83
- ...w(p.name),
84
- [s]: o.getState()
85
- }
86
- ), S);
87
- }), o.devtools = {
88
- cleanup: () => {
89
- i && typeof i.unsubscribe == "function" && i.unsubscribe(), z(p.name, s);
90
- }
91
- };
92
- const u = (...c) => {
93
- const m = g;
94
- g = !1, e(...c), g = m;
95
- }, _ = n(o.setState, r, o);
96
- if (d.type === "untracked" ? i?.init(_) : (d.stores[d.store] = o, i?.init(
97
- Object.fromEntries(
98
- Object.entries(d.stores).map(([c, m]) => [
99
- c,
100
- c === d.store ? _ : m.getState()
101
- ])
102
- )
103
- )), o.dispatchFromDevtools && typeof o.dispatch == "function") {
104
- let c = !1;
105
- const m = o.dispatch;
106
- o.dispatch = (...a) => {
107
- (R ? "production" : void 0) !== "production" && a[0].type === "__setState" && !c && (console.warn(
108
- '[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'
109
- ), c = !0), m(...a);
110
- };
111
- }
112
- return i.subscribe((c) => {
113
- var m;
114
- switch (c.type) {
115
- case "ACTION":
116
- if (typeof c.payload != "string") {
117
- console.error(
118
- "[zustand devtools middleware] Unsupported action format"
119
- );
120
- return;
121
- }
122
- return E(
123
- c.payload,
124
- (a) => {
125
- if (a.type === "__setState") {
126
- if (s === void 0) {
127
- u(a.state);
128
- return;
129
- }
130
- Object.keys(a.state).length !== 1 && console.error(
131
- `
132
- [zustand devtools middleware] Unsupported __setState action format.
133
- When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
134
- and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
135
- `
136
- );
137
- const S = a.state[s];
138
- if (S == null)
139
- return;
140
- JSON.stringify(o.getState()) !== JSON.stringify(S) && u(S);
141
- return;
142
- }
143
- o.dispatchFromDevtools && typeof o.dispatch == "function" && o.dispatch(a);
144
- }
145
- );
146
- case "DISPATCH":
147
- switch (c.payload.type) {
148
- case "RESET":
149
- return u(_), s === void 0 ? i?.init(o.getState()) : i?.init(w(p.name));
150
- case "COMMIT":
151
- if (s === void 0) {
152
- i?.init(o.getState());
153
- return;
154
- }
155
- return i?.init(w(p.name));
156
- case "ROLLBACK":
157
- return E(c.state, (a) => {
158
- if (s === void 0) {
159
- u(a), i?.init(o.getState());
160
- return;
161
- }
162
- u(a[s]), i?.init(w(p.name));
163
- });
164
- case "JUMP_TO_STATE":
165
- case "JUMP_TO_ACTION":
166
- return E(c.state, (a) => {
167
- if (s === void 0) {
168
- u(a);
169
- return;
170
- }
171
- JSON.stringify(o.getState()) !== JSON.stringify(a[s]) && u(a[s]);
172
- });
173
- case "IMPORT_STATE": {
174
- const { nextLiftedState: a } = c.payload, S = (m = a.computedStates.slice(-1)[0]) == null ? void 0 : m.state;
175
- if (!S) return;
176
- u(s === void 0 ? S : S[s]), i?.send(
177
- null,
178
- // FIXME no-any
179
- a
180
- );
181
- return;
182
- }
183
- case "PAUSE_RECORDING":
184
- return g = !g;
185
- }
186
- return;
187
- }
188
- }), _;
189
- }, B = W, E = (n, t) => {
190
- let e;
191
- try {
192
- e = JSON.parse(n);
193
- } catch (r) {
194
- console.error(
195
- "[zustand devtools middleware] Could not parse the received json",
196
- r
197
- );
198
- }
199
- e !== void 0 && t(e);
200
- };
201
- class G extends EventTarget {
25
+ const C = (n) => {
26
+ const t = F(n), o = (e) => N(t, e);
27
+ return Object.assign(o, t), o;
28
+ }, R = ((n) => n ? C(n) : C);
29
+ class M extends EventTarget {
202
30
  constructor() {
203
31
  super(...arguments), this.controller = new AbortController();
204
32
  }
205
- on(t, e) {
33
+ on(t, o) {
206
34
  return this.addEventListener(
207
35
  t,
208
- (r) => e(r.detail),
36
+ (e) => o(e.detail),
209
37
  { signal: this.controller.signal }
210
38
  ), this;
211
39
  }
212
- once(t, e) {
40
+ once(t, o) {
213
41
  return this.addEventListener(
214
42
  t,
215
- (r) => e(r.detail),
43
+ (e) => o(e.detail),
216
44
  {
217
45
  signal: this.controller.signal,
218
46
  once: !0
219
47
  }
220
48
  ), this;
221
49
  }
222
- emit(t, e) {
223
- return this.dispatchEvent(new CustomEvent(t, { detail: e }));
50
+ emit(t, o) {
51
+ return this.dispatchEvent(new CustomEvent(t, { detail: o }));
224
52
  }
225
53
  removeAllListeners() {
226
54
  this.controller.abort(), this.controller = new AbortController();
227
55
  }
228
56
  }
229
- const b = new G(), X = J()(B((n, t) => ({
57
+ const u = new M(), v = R()((n, t) => ({
230
58
  loadingCount: 0,
231
59
  overrideState: null,
232
60
  localCounters: {},
@@ -237,95 +65,121 @@ const b = new G(), X = J()(B((n, t) => ({
237
65
  isGlobalLoading() {
238
66
  return t().isLoading();
239
67
  },
240
- startLoading: (e) => {
241
- const r = t().isLoading();
242
- n((l) => ({ loadingCount: l.loadingCount + 1 })), e && n((l) => ({
68
+ startLoading: (o) => {
69
+ const e = t().isLoading();
70
+ n((i) => ({ loadingCount: i.loadingCount + 1 })), o && n((i) => ({
243
71
  localCounters: {
244
- ...l.localCounters,
245
- [e]: (l.localCounters[e] ?? 0) + 1
72
+ ...i.localCounters,
73
+ [o]: (i.localCounters[o] ?? 0) + 1
246
74
  }
247
75
  }));
248
- const o = t().isLoading();
249
- o && !r && b.emit("start", null), b.emit("change", { isLoading: o, isOverrideState: t().overrideState !== null });
76
+ const r = t().isLoading();
77
+ r && !e && u.emit("start", null), u.emit("change", { isLoading: r, isOverrideState: t().overrideState !== null });
250
78
  },
251
- stopLoading: (e) => {
252
- const r = t().isLoading(), o = e ? t().localCounters[e] ?? 0 : 0;
253
- e && o > 0 && n((v) => ({
254
- loadingCount: Math.max(0, v.loadingCount - 1),
79
+ stopLoading: (o) => {
80
+ const e = t().isLoading(), r = o ? t().localCounters[o] ?? 0 : 0;
81
+ o && r > 0 && n((d) => ({
82
+ loadingCount: Math.max(0, d.loadingCount - 1),
255
83
  localCounters: {
256
- ...v.localCounters,
257
- [e]: Math.max(0, v.localCounters[e] - 1)
84
+ ...d.localCounters,
85
+ [o]: Math.max(0, d.localCounters[o] - 1)
258
86
  }
259
87
  }));
260
- const l = t().isLoading();
261
- !l && r && b.emit("stop", null), b.emit("change", { isLoading: l, isOverrideState: t().overrideState !== null });
88
+ const i = t().isLoading();
89
+ !i && e && u.emit("stop", null), u.emit("change", { isLoading: i, isOverrideState: t().overrideState !== null });
262
90
  },
263
- overrideLoading: (e) => {
91
+ overrideLoading: (o) => {
92
+ const e = t().isLoading();
93
+ n({ overrideState: o });
264
94
  const r = t().isLoading();
265
- n({ overrideState: e });
266
- const o = t().isLoading();
267
- o && !r ? b.emit("start", null) : !o && r && b.emit("stop", null), b.emit("change", { isLoading: o, isOverrideState: e !== null });
95
+ r && !e ? u.emit("start", null) : !r && e && u.emit("stop", null), u.emit("change", { isLoading: r, isOverrideState: o !== null });
268
96
  },
269
- getLocalCounter: (e) => t().localCounters[e] ?? 0,
270
- isLocalLoading: (e) => (t().localCounters[e] ?? 0) > 0
97
+ getLocalCounter: (o) => t().localCounters[o] ?? 0,
98
+ isLocalLoading: (o) => (t().localCounters[o] ?? 0) > 0
271
99
  }
272
- })));
273
- function A() {
274
- const n = D(), { actions: t } = X((l) => l), e = () => {
100
+ }));
101
+ function U() {
102
+ const n = E(), { actions: t } = v((i) => i), o = () => {
103
+ t.startLoading(n);
104
+ }, e = () => {
105
+ t.isLocalLoading(n) && t.stopLoading(n);
106
+ }, r = async (i) => {
107
+ o();
108
+ try {
109
+ return await i;
110
+ } finally {
111
+ e();
112
+ }
113
+ };
114
+ return {
115
+ overrideLoading: t.overrideLoading,
116
+ startLoading: o,
117
+ stopLoading: e,
118
+ get isLocalLoading() {
119
+ return t.isLocalLoading(n);
120
+ },
121
+ asyncUseLoading: r,
122
+ get isLoading() {
123
+ return t.isGlobalLoading();
124
+ }
125
+ };
126
+ }
127
+ function q() {
128
+ const n = O(), { actions: t } = v((i) => i), o = () => {
275
129
  t.startLoading(n);
276
- }, r = () => {
130
+ }, e = () => {
277
131
  t.isLocalLoading(n) && t.stopLoading(n);
278
- }, o = async (l) => {
279
- e();
132
+ }, r = async (i) => {
133
+ o();
280
134
  try {
281
- return await l;
135
+ return await i;
282
136
  } finally {
283
- r();
137
+ e();
284
138
  }
285
139
  };
286
140
  return {
287
141
  overrideLoading: t.overrideLoading,
288
- startLoading: e,
289
- stopLoading: r,
142
+ startLoading: o,
143
+ stopLoading: e,
290
144
  get isLocalLoading() {
291
145
  return t.isLocalLoading(n);
292
146
  },
293
- asyncUseLoading: o,
147
+ asyncUseLoading: r,
294
148
  get isLoading() {
295
149
  return t.isGlobalLoading();
296
150
  }
297
151
  };
298
152
  }
299
- const h = {
153
+ const c = {
300
154
  Spin: "spin",
301
155
  FadeInOut: "fadeInOut",
302
156
  None: "none"
303
- }, H = ({ scale: n = 1, animationType: t = h.Spin, animationDuration: e, children: r, style: o, className: l, id: v, prefix: s }) => {
304
- const p = t, f = t === h.Spin ? 1 : t === h.FadeInOut ? 2 : 0, i = e || f, d = t === h.Spin ? "linear" : t === h.FadeInOut ? "ease-in-out" : "linear", g = t === h.None ? "none" : `${s}-${p} ${i}s ${d} infinite`;
305
- return /* @__PURE__ */ L("div", { style: { animation: g, ...n !== 1 ? { zoom: n } : {}, ...o }, className: l, id: v, children: r });
306
- }, K = (n) => /* @__PURE__ */ L("div", { id: "loading-circle", style: { width: "90px", height: "90px", border: "15px solid #f3f3f3", borderTop: "15px solid #009b4bff", borderRadius: "50%", boxSizing: "border-box" }, ...n }), q = (n) => /* @__PURE__ */ L("div", { style: { padding: "20px", fontSize: "25px", color: "#333", fontFamily: "system-ui, sans-serif" }, ...n, children: "Please wait..." });
307
- function tt({
157
+ }, z = ({ scale: n = 1, animationType: t = c.Spin, animationDuration: o, children: e, style: r, className: i, id: d, prefix: g }) => {
158
+ const m = t, a = t === c.Spin ? 1 : t === c.FadeInOut ? 2 : 0, s = o || a, l = t === c.Spin ? "linear" : t === c.FadeInOut ? "ease-in-out" : "linear", p = t === c.None ? "none" : `${g}-${m} ${s}s ${l} infinite`;
159
+ return /* @__PURE__ */ f("div", { style: { animation: p, ...n !== 1 ? { zoom: n } : {}, ...r }, className: i, id: d, children: e });
160
+ }, D = (n) => /* @__PURE__ */ f("div", { id: "loading-circle", style: { width: "90px", height: "90px", border: "15px solid #f3f3f3", borderTop: "15px solid #009b4bff", borderRadius: "50%", boxSizing: "border-box" }, ...n }), G = (n) => /* @__PURE__ */ f("div", { style: { padding: "20px", fontSize: "25px", color: "#333", fontFamily: "system-ui, sans-serif" }, ...n, children: "Please wait..." });
161
+ function H({
308
162
  loadingComponent: n,
309
163
  loadingComponentScale: t = 1,
310
- animationType: e = h.Spin,
311
- animationDuration: r,
312
- wrapperStyle: o,
313
- wrapperClassName: l,
314
- wrapperId: v,
315
- animationWrapperStyle: s,
316
- animationWrapperClassName: p,
317
- animationWrapperId: f
164
+ animationType: o = c.Spin,
165
+ animationDuration: e,
166
+ wrapperStyle: r,
167
+ wrapperClassName: i,
168
+ wrapperId: d,
169
+ animationWrapperStyle: g,
170
+ animationWrapperClassName: m,
171
+ animationWrapperId: a
318
172
  }) {
319
- n = n || (e === h.Spin ? K : q);
320
- const i = x(Math.random().toString(36).substring(2, 6).replace(/[0-9]/g, "")), { isLoading: d } = A(), g = x(null);
321
- k(() => {
322
- d ? (g.current?.showModal(), document.body.setAttribute("inert", "")) : (g.current?.close(), document.body.removeAttribute("inert"));
323
- }, [d]);
324
- const u = v || "loading-wrapper-" + i.current;
325
- return d ? F(
326
- /* @__PURE__ */ N(j, { children: [
327
- /* @__PURE__ */ L("style", { children: `
328
- dialog#${u}[open] {
173
+ n = n || (o === c.Spin ? D : G);
174
+ const s = y(Math.random().toString(36).substring(2, 6).replace(/[0-9]/g, "")), { loadingCount: l, overrideState: p } = v((I) => I), b = p ?? l > 0, S = y(null);
175
+ w(() => {
176
+ b ? (S.current?.showModal(), document.body.setAttribute("inert", "")) : (S.current?.close(), document.body.removeAttribute("inert"));
177
+ }, [b]);
178
+ const h = d || "loading-wrapper-" + s.current;
179
+ return b ? A(
180
+ /* @__PURE__ */ $(j, { children: [
181
+ /* @__PURE__ */ f("style", { children: `
182
+ dialog#${h}[open] {
329
183
  display: flex !important;
330
184
  justify-content: center;
331
185
  align-items: center;
@@ -334,55 +188,55 @@ function tt({
334
188
  max-width: 100%;
335
189
  max-height: 100%;
336
190
  }
337
- @keyframes ${i.current}-spin {
191
+ @keyframes ${s.current}-spin {
338
192
  0% { transform: rotate(0deg); }
339
193
  100% { transform: rotate(360deg); }
340
194
  }
341
- @keyframes ${i.current}-fadeInOut {
195
+ @keyframes ${s.current}-fadeInOut {
342
196
  0%, 100% { opacity: 0.2; }
343
197
  50% { opacity: 1; }
344
198
  }
345
- body:has(dialog#${u}[open]) {
199
+ body:has(dialog#${h}[open]) {
346
200
  overflow: hidden;
347
201
  }
348
202
  body {
349
203
  scrollbar-gutter: stable;
350
204
  }
351
205
  ` }),
352
- /* @__PURE__ */ L(
206
+ /* @__PURE__ */ f(
353
207
  "dialog",
354
208
  {
355
- ref: g,
209
+ ref: S,
356
210
  style: {
357
211
  border: "none",
358
212
  padding: 0,
359
213
  backgroundColor: "rgba(0, 0, 0, 0.5)",
360
214
  backdropFilter: "blur(2px)",
361
- ...o
215
+ ...r
362
216
  },
363
- className: l,
364
- id: u,
365
- children: /* @__PURE__ */ L(H, { scale: t, animationType: e, animationDuration: r, style: s, className: p, id: f, prefix: i.current, children: y.isValidElement(n) ? n : y.createElement(n) })
217
+ className: i,
218
+ id: h,
219
+ children: /* @__PURE__ */ f(z, { scale: t, animationType: o, animationDuration: e, style: g, className: m, id: a, prefix: s.current, children: L.isValidElement(n) ? n : L.createElement(n) })
366
220
  }
367
221
  )
368
222
  ] }),
369
223
  document.body
370
224
  ) : null;
371
225
  }
372
- function et({ isLoading: n = !1 }) {
373
- const { startLoading: t, stopLoading: e } = A();
374
- return k(() => (n ? t() : e(), () => {
375
- n && e();
226
+ function J({ isLoading: n = !1 }) {
227
+ const { startLoading: t, stopLoading: o } = U();
228
+ return w(() => (n ? t() : o(), () => {
229
+ n && o();
376
230
  }), [n]), null;
377
231
  }
378
232
  export {
379
- h as AnimationType,
380
- G as EventEmitter,
381
- et as Loading,
382
- K as LoadingCircle,
383
- q as LoadingPleaseWait,
384
- tt as LoadingRenderer,
385
- b as loadingEventTarget,
386
- A as ssrLoading,
387
- A as useLoading
233
+ c as AnimationType,
234
+ M as EventEmitter,
235
+ J as Loading,
236
+ D as LoadingCircle,
237
+ G as LoadingPleaseWait,
238
+ H as LoadingRenderer,
239
+ u as loadingEventTarget,
240
+ q as ssrLoading,
241
+ U as useLoading
388
242
  };
@@ -0,0 +1,26 @@
1
+ import { default as EventEmitter } from '../utils/EventEmitter';
2
+ type LoadingEvents = {
3
+ change: {
4
+ isLoading: boolean;
5
+ isOverrideState: boolean;
6
+ } | null;
7
+ start: null;
8
+ stop: null;
9
+ };
10
+ export declare const loadingEventTarget: EventEmitter<LoadingEvents>;
11
+ interface Store {
12
+ loadingCount: number;
13
+ overrideState: boolean | null;
14
+ localCounters: Record<string, number>;
15
+ isLoading: () => boolean;
16
+ actions: {
17
+ isGlobalLoading: () => boolean;
18
+ startLoading: (instanceId?: string) => void;
19
+ stopLoading: (instanceId?: string) => void;
20
+ overrideLoading: (state: boolean | null) => void;
21
+ getLocalCounter: (instanceId: string) => number;
22
+ isLocalLoading: (instanceId: string) => boolean;
23
+ };
24
+ }
25
+ export declare const loadingStore: import('zustand').UseBoundStore<import('zustand').StoreApi<Store>>;
26
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rokku-x/react-hook-loading-spinner",
3
- "version": "0.1.12",
3
+ "version": "0.2.1",
4
4
  "description": "A lightweight and flexible React loading state hook library with built-in spinner components, global state management, and zero dependencies (except React and Zustand).",
5
5
  "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.esm.js",
@@ -1,19 +0,0 @@
1
- import { default as EventEmitter } from './utils/EventEmitter';
2
- type LoadingEvents = {
3
- change: {
4
- isLoading: boolean;
5
- isOverrideState: boolean;
6
- } | null;
7
- start: null;
8
- stop: null;
9
- };
10
- export declare const loadingEventTarget: EventEmitter<LoadingEvents>;
11
- export default function (): {
12
- overrideLoading: (state: boolean | null) => void;
13
- startLoading: () => void;
14
- stopLoading: () => void;
15
- readonly isLocalLoading: boolean;
16
- asyncUseLoading: <R, _ extends any[]>(asyncFunction: Promise<R>) => Promise<R>;
17
- readonly isLoading: boolean;
18
- };
19
- export {};