UNPKG

@frauschert/yas

Version:

Yet Another State - A lightweight and type-safe state management solution for React

2 lines (1 loc) 1.79 kB
(function(s,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],i):(s=typeof globalThis<"u"?globalThis:s||self,i(s.yas={},s.React))})(this,function(s,i){"use strict";function S(e,r){if(e===r)return!0;if(typeof e!="object"||e===null||typeof r!="object"||r===null)return!1;const n=Object.keys(e),t=Object.keys(r);if(n.length!==t.length)return!1;for(const u of n)if(!t.includes(u)||!S(e[u],r[u]))return!1;return!0}function p(e,r,...n){let t=e,u=e;const c=new Set,o=r||S;function m(){return t}function v(){return e}function O(){return u}let d=f=>{const a=f(t);u=t,t=a,c.forEach(l=>l(t,u))};const g={getState:m,getInitialState:v,getPreviousState:O,setState:d,subscribe:f=>(c.add(f),()=>{c.delete(f)})};if(n.length>0){const f=n.slice().reverse().reduce((a,l)=>l(g)(a),a=>d(()=>a));d=a=>{const l=a(t);o(t,l)||f(l)}}return{...g,setState:d}}function h(e){return r=>i.useSyncExternalStore(e.subscribe,i.useCallback(()=>r(e.getState()),[e,r]))}function y(e){return r=>Object.fromEntries(Object.entries(r).map(([n,t])=>[n,(...u)=>e.setState(c=>t(c,...u))]))}function b({initialState:e,actions:r,equalityFn:n,middleware:t=[]}){const u=p(e,n,...t),c=h(u),o=y(u)(r);return{useStore:c,actions:o,api:u}}function k(e,r=50){const n=[],t=[];return{...e,setState:c=>{const o=e.getState();e.setState(c),n.push(o),n.length>r&&n.shift(),t.length=0},undo:()=>{if(!n.length)return;const c=e.getState(),o=n.pop();t.push(c),e.setState(()=>o)},redo:()=>{if(!t.length)return;const c=e.getState(),o=t.pop();n.push(c),e.setState(()=>o)},canUndo:()=>n.length>0,canRedo:()=>t.length>0,clearHistory:()=>{n.length=0,t.length=0}}}s.create=b,s.createStore=p,s.makeUndoable=k,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});