atomaric
Version:
Manage your project state
2 lines (1 loc) • 2.07 kB
JavaScript
(function(s,n){typeof exports=="object"&&typeof module<"u"?n(exports):typeof define=="function"&&define.amd?define(["exports"],n):(s=typeof globalThis<"u"?globalThis:s||self,n(s.atomaric={}))})(this,function(s){"use strict";const n={};window.addEventListener("storage",e=>{e.key===null||n[e.key]===void 0||n[e.key](e)});class c{constructor(i,o){if(this._defaultValue=i,this.subscribers=new Set,this.save=()=>{},this.invokeSubscriber=t=>t(this.value),this.get=()=>this.value,this.toggle=()=>this.set(!this.value),this.inkrement=t=>this.set(this.value+t),this.subscribe=t=>(this.subscribers.add(t),()=>{this.subscribers.delete(t)}),this.set=(t,b)=>{const u=typeof t=="function"?t(this.value):t;u===this.value||u===void 0||typeof u=="number"&&isNaN(u)||(this.value=u,this.subscribers.forEach(this.invokeSubscriber,this),b!==!0&&this.save(u))},this.value=i,typeof i!="boolean"&&(this.toggle=()=>{}),typeof i!="number"&&(this.inkrement=()=>{}),this.reset=()=>{this.set(i,!0),this.subscribers.forEach(this.invokeSubscriber,this)},o==null)return;let l=null,g=!0,m=!0;if(typeof o=="string"?l=o:o.storeKey!==void 0&&(g=o.warnOnDuplicateStoreKey??!0,m=o.listenStorageChanges??!0,l=o.storeKey),l===null)return;const r=`atom/${l}`;this.value=r in localStorage?JSON.parse(localStorage[r]):i,this.save=t=>{if(t===i){this.reset();return}localStorage[r]=JSON.stringify(t)},this.reset=()=>{delete localStorage[r],this.set(i,!0)},g&&n[r]!==void 0&&console.warn("Duplicate Atom key",o),m&&(n[r]=t=>{if(t.newValue===null){this.reset();return}try{this.set(JSON.parse(t.newValue))}catch{console.warn("Invalid json value",t.newValue)}})}get defaultValue(){return this._defaultValue}}let a=()=>{throw"call configureAtomaric() before all!"};const S=e=>a=e.useSyncExternalStore,h=e=>a(e.subscribe,e.get),f=e=>e.set,d=e=>e.get,A=e=>e.toggle,v=e=>e.inkrement,y=e=>[h(e),f(e)],k=(e,i)=>new c(e,i);s.Atom=c,s.atom=k,s.configureAtomaric=S,s.useAtom=y,s.useAtomGet=d,s.useAtomInkrement=v,s.useAtomSet=f,s.useAtomToggle=A,s.useAtomValue=h,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});