UNPKG

cozyevent

Version:

World's fastest, Lightweight Async/Sync Event Emitter, also for React

3 lines (2 loc) 1.56 kB
import{jsx as e}from"react/jsx-runtime";import{createContext as t,useEffect as n,useMemo as o,useContext as s,useCallback as i}from"react";class r{_events={};on(e,t){(this._events[e]??=[]).push(t)}once(e,t){const n=o=>{t(o),this.off(e,n)};this.on(e,n)}off(e,t){this._events[e]&&(this._events[e]=this._events[e].filter((e=>e!==t)),0===this._events[e].length&&delete this._events[e])}emit(e,t){this._events[e]?.forEach((e=>e(t)))}emitAsync(e,t){this._events[e]&&queueMicrotask((()=>{this._events[e].forEach((e=>e(t)))}))}removeAllListeners(e){e?delete this._events[e]:this._events={}}}const v=t(null),c={},f=(e,t)=>{c[e]=t},h=e=>c[e],a=new r,d=({instance:t=a,children:s,id:i="default"})=>{if(!(t instanceof r))throw new Error("Invalid CozyEvent instance provided to CozyEventProvider");n((()=>(f(i,t),()=>{(e=>{delete c[e]})(i)})),[i,t]);const h=o((()=>t),[t]);return e(v.Provider,{value:h,children:s})},l=(e,t,r)=>{const{namespace:c,id:f}=r||{},d=f?h(f):s(v)||a;if(!d)throw new Error(`No CozyEvent instance found for id: ${f}`);if("string"!=typeof e||""===e.trim())throw new Error("Invalid eventName provided to useCozyEvent. It must be a non-empty string.");if("function"!=typeof t)throw new Error("Invalid callback provided to useCozyEvent. It must be a function.");const l=o((()=>c?`${c}:${e}`:e),[c,e]),u=i(t,[t]);return n((()=>(d.on(l,u),()=>{d.off(l,u)})),[d,l,u]),d};export{r as CozyEvent,v as CozyEventContext,d as CozyEventProvider,h as getCozyEventInstanceById,f as registerCozyEventInstance,l as useCozyEvent}; //# sourceMappingURL=index.esm.js.map