use-typed-reducer 4.2.3 → 4.2.4

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.
package/dist/hooks.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MutableRefObject } from 'react';
2
- export declare const useMutable: <T extends {}>(state: T) => MutableRefObject<T>;
1
+ import { RefObject } from "react";
2
+ export declare const useMutable: <T extends {}>(state: T) => RefObject<T>;
3
3
  export declare const usePrevious: <V>(value: V) => V;
4
4
  //# sourceMappingURL=hooks.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAqB,MAAM,OAAO,CAAC;AAE5D,eAAO,MAAM,UAAU,GAAI,CAAC,SAAS,EAAE,SAAS,CAAC,KAAG,gBAAgB,CAAC,CAAC,CAIrE,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,CAAC,KAAG,CAMzC,CAAC"}
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAqB,MAAM,OAAO,CAAC;AAErD,eAAO,MAAM,UAAU,GAAI,CAAC,SAAS,EAAE,SAAS,CAAC,KAAG,SAAS,CAAC,CAAC,CAI9D,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,CAAC,KAAG,CAMzC,CAAC"}
package/dist/index.cjs CHANGED
@@ -1,38 +1,386 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react");var A={exports:{}},D={},j={exports:{}},P={};/**
2
- * @license React
3
- * use-sync-external-store-shim.production.js
4
- *
5
- * Copyright (c) Meta Platforms, Inc. and affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var H;function x(){if(H)return P;H=1;var e=y;function r(i,s){return i===s&&(i!==0||1/i===1/s)||i!==i&&s!==s}var n=typeof Object.is=="function"?Object.is:r,c=e.useState,a=e.useEffect,l=e.useLayoutEffect,v=e.useDebugValue;function p(i,s){var t=s(),o=c({inst:{value:t,getSnapshot:s}}),u=o[0].inst,S=o[1];return l(function(){u.value=t,u.getSnapshot=s,O(u)&&S({inst:u})},[i,t,s]),a(function(){return O(u)&&S({inst:u}),i(function(){O(u)&&S({inst:u})})},[i]),v(t),t}function O(i){var s=i.getSnapshot;i=i.value;try{var t=s();return!n(i,t)}catch{return!0}}function f(i,s){return s()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:p;return P.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,P}var M={};/**
10
- * @license React
11
- * use-sync-external-store-shim.development.js
12
- *
13
- * Copyright (c) Meta Platforms, Inc. and affiliates.
14
- *
15
- * This source code is licensed under the MIT license found in the
16
- * LICENSE file in the root directory of this source tree.
17
- */var K;function F(){return K||(K=1,process.env.NODE_ENV!=="production"&&function(){function e(t,o){return t===o&&(t!==0||1/t===1/o)||t!==t&&o!==o}function r(t,o){d||a.startTransition===void 0||(d=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var u=o();if(!i){var S=o();l(u,S)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),i=!0)}S=v({inst:{value:u,getSnapshot:o}});var _=S[0].inst,E=S[1];return O(function(){_.value=u,_.getSnapshot=o,n(_)&&E({inst:_})},[t,u,o]),p(function(){return n(_)&&E({inst:_}),t(function(){n(_)&&E({inst:_})})},[t]),f(u),u}function n(t){var o=t.getSnapshot;t=t.value;try{var u=o();return!l(t,u)}catch{return!0}}function c(t,o){return o()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var a=y,l=typeof Object.is=="function"?Object.is:e,v=a.useState,p=a.useEffect,O=a.useLayoutEffect,f=a.useDebugValue,d=!1,i=!1,s=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:r;M.useSyncExternalStore=a.useSyncExternalStore!==void 0?a.useSyncExternalStore:s,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),M}var W;function z(){return W||(W=1,process.env.NODE_ENV==="production"?j.exports=x():j.exports=F()),j.exports}/**
18
- * @license React
19
- * use-sync-external-store-shim/with-selector.production.js
20
- *
21
- * Copyright (c) Meta Platforms, Inc. and affiliates.
22
- *
23
- * This source code is licensed under the MIT license found in the
24
- * LICENSE file in the root directory of this source tree.
25
- */var N;function J(){if(N)return D;N=1;var e=y,r=z();function n(f,d){return f===d&&(f!==0||1/f===1/d)||f!==f&&d!==d}var c=typeof Object.is=="function"?Object.is:n,a=r.useSyncExternalStore,l=e.useRef,v=e.useEffect,p=e.useMemo,O=e.useDebugValue;return D.useSyncExternalStoreWithSelector=function(f,d,i,s,t){var o=l(null);if(o.current===null){var u={hasValue:!1,value:null};o.current=u}else u=o.current;o=p(function(){function _(m){if(!E){if(E=!0,h=m,m=s(m),t!==void 0&&u.hasValue){var b=u.value;if(t(b,m))return L=b}return L=m}if(b=L,c(h,m))return b;var w=s(m);return t!==void 0&&t(b,w)?(h=m,b):(h=m,L=w)}var E=!1,h,L,R=i===void 0?null:i;return[function(){return _(d())},R===null?void 0:function(){return _(R())}]},[d,i,s,t]);var S=a(f,o[0],o[1]);return v(function(){u.hasValue=!0,u.value=S},[S]),O(S),S},D}var C={};/**
26
- * @license React
27
- * use-sync-external-store-shim/with-selector.development.js
28
- *
29
- * Copyright (c) Meta Platforms, Inc. and affiliates.
30
- *
31
- * This source code is licensed under the MIT license found in the
32
- * LICENSE file in the root directory of this source tree.
33
- */var U;function Y(){return U||(U=1,process.env.NODE_ENV!=="production"&&function(){function e(f,d){return f===d&&(f!==0||1/f===1/d)||f!==f&&d!==d}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=y,n=z(),c=typeof Object.is=="function"?Object.is:e,a=n.useSyncExternalStore,l=r.useRef,v=r.useEffect,p=r.useMemo,O=r.useDebugValue;C.useSyncExternalStoreWithSelector=function(f,d,i,s,t){var o=l(null);if(o.current===null){var u={hasValue:!1,value:null};o.current=u}else u=o.current;o=p(function(){function _(m){if(!E){if(E=!0,h=m,m=s(m),t!==void 0&&u.hasValue){var b=u.value;if(t(b,m))return L=b}return L=m}if(b=L,c(h,m))return b;var w=s(m);return t!==void 0&&t(b,w)?(h=m,b):(h=m,L=w)}var E=!1,h,L,R=i===void 0?null:i;return[function(){return _(d())},R===null?void 0:function(){return _(R())}]},[d,i,s,t]);var S=a(f,o[0],o[1]);return v(function(){u.hasValue=!0,u.value=S},[S]),O(S),S},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),C}var $;function Q(){return $||($=1,process.env.NODE_ENV==="production"?A.exports=J():A.exports=Y()),A.exports}var X=Q();const g=e=>{const r=y.useRef(e??{});return y.useEffect(()=>void(r.current=e),[e]),r},I=e=>{const r=y.useRef(void 0);return y.useEffect(()=>{r.current=e},[e]),r.current},Z=e=>e&&typeof e=="object",ee=Object.keys,T=e=>Object.entries(e),V=e=>e instanceof Promise,G=e=>{const r=typeof e;return r==="string"||r==="number"||r==="bigint"||r==="boolean"||r==="undefined"||r===null},q=(e,r)=>{if(e===r||Object.is(e,r))return!0;if(Array.isArray(e)&&Array.isArray(r)&&e.length!==r.length)return!1;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();const n=Object.keys(e);if(length=n.length,length!==Object.keys(r).length)return!1;let c=length;for(;c--!==0;)if(!Object.prototype.hasOwnProperty.call(r,n[c]))return!1;c=length;for(let a=length;a--!==0;){const l=n[a];if(!(G(e[l])&&G(r[l])&&r[l]===e[l]))return!1}return!0}return e!==e&&r!==r},re=e=>Object.assign(Object.create(Object.getPrototypeOf(e)),e),te=(e,r)=>typeof r=="function"?r(e):r,ne=(e,r,n)=>{const[c,a]=y.useState(e),l=g(n??{}),v=y.useCallback(()=>l.current,[l]),p=y.useMemo(()=>T(r).reduce((O,[f,d])=>({...O,[f]:async(...i)=>{const s=await d(...i);return a(t=>s(t,v()))}}),r),[r,v]);return[c,p]},k=(e,r,n,c)=>r===e?n.reduce((a,l)=>l(a,r,c),e):e.constructor.name===Object.name?n.reduce((a,l)=>l(a,r,c),{...r,...e}):n.reduce((a,l)=>l(a,r,c),e),ue=(e,r,n,c,a,l)=>(...v)=>{const p=performance.now(),O=r(...v),f=(d,i)=>n(s=>k(d,s,l,i));return V(O)?O.then(d=>{a.current={method:e,props:c(),time:performance.now()-p},f(d,a.current)}):(a.current={method:e,props:c(),time:performance.now()-p},void f(O,a.current))},oe=(e,r,n,c,a,l)=>(...v)=>{a.current={method:e,time:0,props:c()};const p=r(...v),O=f=>n(d=>k(f,d,l,a.current));return V(p)?p.then(f=>O(f)):O(p)},ce=(e,r,n)=>{const[c,a]=y.useState(()=>e),l=g(c),v=g((n==null?void 0:n.props)??{}),p=g(r),O=g((n==null?void 0:n.postMiddleware)??[]),f=g((n==null?void 0:n.interceptor)??[]),d=y.useRef(e),i=I(c),s=g(i),t=y.useRef(null);y.useEffect(()=>{if(t.current===null)return;const u=t.current;O.current.forEach(S=>{S(c,i,u)})},[c,O,i]);const[o]=y.useState(()=>{const u=()=>v.current,S=p.current({props:u,state:()=>l.current,initialState:d.current,previousState:()=>s.current});return T(S).reduce((_,[E,h])=>({..._,[E]:n!=null&&n.debug?ue(E,h,a,u,t,f.current):oe(E,h,a,u,t,f.current)}),{})});return[c,o,v.current]},se=(e,r,n)=>{let c=e;const a=(n==null?void 0:n.interceptor)??[],l=()=>c,v=new Set,p=s=>(v.add(s),()=>v.delete(s)),O=s=>{const t={...c},o=s(c);c=o,v.forEach(u=>u(o,t))},f={initialState:e,props:{},state:l,previousState:l},d=s=>s,i=T(r(f)).reduce((s,[t,o])=>({...s,[t]:(...u)=>{const S=o(...u),_=E=>O(h=>k(E,h,a,{method:t,props:{},selector:d,time:0}));return V(S)?S.then(_):_(S)}}),{});return Object.assign(function(t,o=q,u){const S=g((u==null?void 0:u.postMiddleware)??[]),_=X.useSyncExternalStoreWithSelector(p,l,l,t||d,o),E=I(_);return y.useEffect(()=>{Array.isArray(S.current)&&S.current.forEach(h=>{h(_,E,{method:"@globalState@",time:-1,props:{},selector:t})})},[_,E,S]),[_,i,{}]},{dispatchers:i,getState:()=>c})},B=e=>r=>(n,c)=>(e().set(r,JSON.stringify(n)),n),ae=B(()=>({set:(e,r)=>localStorage.setItem(e,r)})),ie=B(()=>({set:(e,r)=>sessionStorage.setItem(e,r)})),le=e=>(r,n,c)=>(console.group(e),console.info(`%cAction %c- "${c.method}" ${c.time}ms
34
- `,"color: gold","color: white",n),console.info(`%cPrevious state
35
- `,"color: silver",n),console.info(`%cCurrent state
36
- `,"color: green",r),console.info(`Props
37
- `,c.props),console.groupEnd(),r);exports.clone=re;exports.createGlobalReducer=se;exports.createLocalStoragePlugin=ae;exports.createLoggerPlugin=le;exports.createSessionStoragePlugin=ie;exports.createStoragePlugin=B;exports.dispatchCallback=te;exports.entries=T;exports.isObject=Z;exports.isPrimitive=G;exports.isPromise=V;exports.keys=ee;exports.shallowCompare=q;exports.useLegacyReducer=ne;exports.useMutable=g;exports.usePrevious=I;exports.useReducer=ce;
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var withSelector = require('use-sync-external-store/shim/with-selector');
5
+
6
+ /******************************************************************************
7
+ Copyright (c) Microsoft Corporation.
8
+
9
+ Permission to use, copy, modify, and/or distribute this software for any
10
+ purpose with or without fee is hereby granted.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
+ PERFORMANCE OF THIS SOFTWARE.
19
+ ***************************************************************************** */
20
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
21
+
22
+
23
+ var __assign = function() {
24
+ __assign = Object.assign || function __assign(t) {
25
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
26
+ s = arguments[i];
27
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
28
+ }
29
+ return t;
30
+ };
31
+ return __assign.apply(this, arguments);
32
+ };
33
+
34
+ function __awaiter(thisArg, _arguments, P, generator) {
35
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
36
+ return new (P || (P = Promise))(function (resolve, reject) {
37
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
38
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
39
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
40
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
41
+ });
42
+ }
43
+
44
+ function __generator(thisArg, body) {
45
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
46
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
+ function verb(n) { return function (v) { return step([n, v]); }; }
48
+ function step(op) {
49
+ if (f) throw new TypeError("Generator is already executing.");
50
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
51
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
52
+ if (y = 0, t) op = [op[0] & 2, t.value];
53
+ switch (op[0]) {
54
+ case 0: case 1: t = op; break;
55
+ case 4: _.label++; return { value: op[1], done: false };
56
+ case 5: _.label++; y = op[1]; op = [0]; continue;
57
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
+ default:
59
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
+ if (t[2]) _.ops.pop();
64
+ _.trys.pop(); continue;
65
+ }
66
+ op = body.call(thisArg, _);
67
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : undefined, done: true };
69
+ }
70
+ }
71
+
72
+ function __read(o, n) {
73
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
74
+ if (!m) return o;
75
+ var i = m.call(o), r, ar = [], e;
76
+ try {
77
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
78
+ }
79
+ catch (error) { e = { error: error }; }
80
+ finally {
81
+ try {
82
+ if (r && !r.done && (m = i["return"])) m.call(i);
83
+ }
84
+ finally { if (e) throw e.error; }
85
+ }
86
+ return ar;
87
+ }
88
+
89
+ function __spreadArray(to, from, pack) {
90
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
91
+ if (ar || !(i in from)) {
92
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
93
+ ar[i] = from[i];
94
+ }
95
+ }
96
+ return to.concat(ar || Array.prototype.slice.call(from));
97
+ }
98
+
99
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
100
+ var e = new Error(message);
101
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
102
+ };
103
+
104
+ var useMutable = function (state) {
105
+ var mutable = react.useRef(state !== null && state !== undefined ? state : {});
106
+ react.useEffect(function () { return void (mutable.current = state); }, [state]);
107
+ return mutable;
108
+ };
109
+ var usePrevious = function (value) {
110
+ var ref = react.useRef(undefined);
111
+ react.useEffect(function () {
112
+ ref.current = value;
113
+ }, [value]);
114
+ return ref.current;
115
+ };
116
+
117
+ var isObject = function (obj) { return obj && typeof obj === "object"; };
118
+ var keys = Object.keys;
119
+ var entries = function (t) { return Object.entries(t); };
120
+ var isPromise = function (promise) { return promise instanceof Promise; };
121
+ var isPrimitive = function (a) {
122
+ var type = typeof a;
123
+ return (type === "string" ||
124
+ type === "number" ||
125
+ type === "bigint" ||
126
+ type === "boolean" ||
127
+ type === "undefined" ||
128
+ type === null);
129
+ };
130
+ var shallowCompare = function (left, right) {
131
+ if (left === right || Object.is(left, right))
132
+ return true;
133
+ if (Array.isArray(left) && Array.isArray(right)) {
134
+ if (left.length !== right.length)
135
+ return false;
136
+ }
137
+ if (left && right && typeof left === "object" && typeof right === "object") {
138
+ if (left.constructor !== right.constructor)
139
+ return false;
140
+ if (left.valueOf !== Object.prototype.valueOf)
141
+ return left.valueOf() === right.valueOf();
142
+ var keys_1 = Object.keys(left);
143
+ length = keys_1.length;
144
+ if (length !== Object.keys(right).length) {
145
+ return false;
146
+ }
147
+ var i = length;
148
+ for (; i-- !== 0;) {
149
+ if (!Object.prototype.hasOwnProperty.call(right, keys_1[i])) {
150
+ return false;
151
+ }
152
+ }
153
+ i = length;
154
+ for (var i_1 = length; i_1-- !== 0;) {
155
+ var key = keys_1[i_1];
156
+ if (!(isPrimitive(left[key]) && isPrimitive(right[key]) && right[key] === left[key]))
157
+ return false;
158
+ }
159
+ return true;
160
+ }
161
+ return left !== left && right !== right;
162
+ };
163
+ var clone = function (instance) { return Object.assign(Object.create(Object.getPrototypeOf(instance)), instance); };
164
+ var dispatchCallback = function (prev, setter) {
165
+ return typeof setter === "function" ? setter(prev) : setter;
166
+ };
167
+
168
+ var useLegacyReducer = function (initialState, reducers, props) {
169
+ var _a;
170
+ var _b = __read(react.useState(initialState), 2), state = _b[0], setState = _b[1];
171
+ var refProps = useMutable((_a = props) !== null && _a !== undefined ? _a : {});
172
+ var getProps = react.useCallback(function () { return refProps.current; }, [refProps]);
173
+ var dispatches = react.useMemo(function () {
174
+ return entries(reducers).reduce(function (acc, _a) {
175
+ var _b;
176
+ var _c = __read(_a, 2), name = _c[0], dispatch = _c[1];
177
+ return (__assign(__assign({}, acc), (_b = {}, _b[name] = function () {
178
+ var params = [];
179
+ for (var _i = 0; _i < arguments.length; _i++) {
180
+ params[_i] = arguments[_i];
181
+ }
182
+ return __awaiter(undefined, undefined, undefined, function () {
183
+ var dispatcher;
184
+ return __generator(this, function (_a) {
185
+ switch (_a.label) {
186
+ case 0: return [4 /*yield*/, dispatch.apply(undefined, __spreadArray([], __read(params), false))];
187
+ case 1:
188
+ dispatcher = _a.sent();
189
+ return [2 /*return*/, setState(function (previousState) { return dispatcher(previousState, getProps()); })];
190
+ }
191
+ });
192
+ });
193
+ }, _b)));
194
+ }, reducers);
195
+ }, [reducers, getProps]);
196
+ return [state, dispatches];
197
+ };
198
+ var reduce = function (state, prev, mutations, debug) {
199
+ if (prev === state)
200
+ return mutations.reduce(function (acc, el) { return el(acc, prev, debug); }, state);
201
+ return state.constructor.name === Object.name
202
+ ? mutations.reduce(function (acc, el) { return el(acc, prev, debug); }, __assign(__assign({}, prev), state))
203
+ : mutations.reduce(function (acc, el) { return el(acc, prev, debug); }, state);
204
+ };
205
+ var debugFunc = function (name, dispatch, setState, getProps, debug, mutations) {
206
+ return function () {
207
+ var params = [];
208
+ for (var _i = 0; _i < arguments.length; _i++) {
209
+ params[_i] = arguments[_i];
210
+ }
211
+ var now = performance.now();
212
+ var result = dispatch.apply(undefined, __spreadArray([], __read(params), false));
213
+ var set = function (newState, debug) {
214
+ return setState(function (prev) { return reduce(newState, prev, mutations, debug); });
215
+ };
216
+ if (isPromise(result)) {
217
+ return result.then(function (resolved) {
218
+ debug.current = {
219
+ method: name,
220
+ props: getProps(),
221
+ time: performance.now() - now
222
+ };
223
+ set(resolved, debug.current);
224
+ });
225
+ }
226
+ debug.current = {
227
+ method: name,
228
+ props: getProps(),
229
+ time: performance.now() - now
230
+ };
231
+ return void set(result, debug.current);
232
+ };
233
+ };
234
+ var optimizedFunc = function (name, dispatch, setState, getProps, debug, mutations) {
235
+ return function () {
236
+ var params = [];
237
+ for (var _i = 0; _i < arguments.length; _i++) {
238
+ params[_i] = arguments[_i];
239
+ }
240
+ debug.current = { method: name, time: 0, props: getProps() };
241
+ var result = dispatch.apply(undefined, __spreadArray([], __read(params), false));
242
+ var set = function (newState) { return setState(function (prev) { return reduce(newState, prev, mutations, debug.current); }); };
243
+ if (isPromise(result)) {
244
+ return result.then(function (resolved) { return set(resolved); });
245
+ }
246
+ return set(result);
247
+ };
248
+ };
249
+ var useReducer = function (initialState, reducer, options) {
250
+ var _a, _b, _c;
251
+ var _d = __read(react.useState(function () { return initialState; }), 2), state = _d[0], setState = _d[1];
252
+ var mutableState = useMutable(state);
253
+ var mutableProps = useMutable((_a = options === null || options === undefined ? undefined : options.props) !== null && _a !== undefined ? _a : {});
254
+ var mutableReducer = useMutable(reducer);
255
+ var middleware = useMutable((_b = options === null || options === undefined ? undefined : options.postMiddleware) !== null && _b !== undefined ? _b : []);
256
+ var mutations = useMutable((_c = options === null || options === undefined ? undefined : options.interceptor) !== null && _c !== undefined ? _c : []);
257
+ var savedInitialState = react.useRef(initialState);
258
+ var previous = usePrevious(state);
259
+ var previousRef = useMutable(previous);
260
+ var debug = react.useRef(null);
261
+ react.useEffect(function () {
262
+ if (debug.current === null)
263
+ return;
264
+ var d = debug.current;
265
+ middleware.current.forEach(function (middle) {
266
+ middle(state, previous, d);
267
+ });
268
+ }, [state, middleware, previous]);
269
+ var _e = __read(react.useState(function () {
270
+ var getProps = function () { return mutableProps.current; };
271
+ var reducers = mutableReducer.current({
272
+ props: getProps,
273
+ state: function () { return mutableState.current; },
274
+ initialState: savedInitialState.current,
275
+ previousState: function () { return previousRef.current; }
276
+ });
277
+ return entries(reducers).reduce(function (acc, _a) {
278
+ var _b;
279
+ var _c = __read(_a, 2), name = _c[0], dispatch = _c[1];
280
+ return (__assign(__assign({}, acc), (_b = {}, _b[name] = (options === null || options === undefined ? undefined : options.debug)
281
+ ? debugFunc(name, dispatch, setState, getProps, debug, mutations.current)
282
+ : optimizedFunc(name, dispatch, setState, getProps, debug, mutations.current), _b)));
283
+ }, {});
284
+ }), 1), dispatchers = _e[0];
285
+ return [state, dispatchers, mutableProps.current];
286
+ };
287
+ var createGlobalReducer = function (initialState, reducer, rootOptions) {
288
+ var _a;
289
+ var state = initialState;
290
+ var rootMutations = (_a = rootOptions === null || rootOptions === undefined ? undefined : rootOptions.interceptor) !== null && _a !== undefined ? _a : [];
291
+ var getSnapshot = function () { return state; };
292
+ var listeners = new Set();
293
+ var addListener = function (listener) {
294
+ listeners.add(listener);
295
+ return function () { return listeners.delete(listener); };
296
+ };
297
+ var setState = function (callback) {
298
+ var previousState = __assign({}, state);
299
+ var newState = callback(state);
300
+ state = newState;
301
+ listeners.forEach(function (exec) { return exec(newState, previousState); });
302
+ };
303
+ var debugOptions = { initialState: initialState, props: {}, state: getSnapshot, previousState: getSnapshot };
304
+ var defaultSelector = function (state) { return state; };
305
+ var dispatchers = entries(reducer(debugOptions)).reduce(function (acc, _a) {
306
+ var _b;
307
+ var _c = __read(_a, 2), method = _c[0], fn = _c[1];
308
+ return (__assign(__assign({}, acc), (_b = {}, _b[method] = function () {
309
+ var args = [];
310
+ for (var _i = 0; _i < arguments.length; _i++) {
311
+ args[_i] = arguments[_i];
312
+ }
313
+ var result = fn.apply(undefined, __spreadArray([], __read(args), false));
314
+ var set = function (newState) {
315
+ return setState(function (prev) {
316
+ return reduce(newState, prev, rootMutations, {
317
+ method: method,
318
+ props: {},
319
+ selector: defaultSelector,
320
+ time: 0
321
+ });
322
+ });
323
+ };
324
+ return isPromise(result) ? result.then(set) : set(result);
325
+ }, _b)));
326
+ }, {});
327
+ return Object.assign(function useStore(selector, comparator, options) {
328
+ var _a;
329
+ if (comparator === undefined) { comparator = shallowCompare; }
330
+ var middleware = useMutable((_a = options === null || options === undefined ? undefined : options.postMiddleware) !== null && _a !== undefined ? _a : []);
331
+ var state = withSelector.useSyncExternalStoreWithSelector(addListener, getSnapshot, getSnapshot, selector || defaultSelector, comparator);
332
+ var previous = usePrevious(state);
333
+ react.useEffect(function () {
334
+ if (Array.isArray(middleware.current))
335
+ middleware.current.forEach(function (middle) {
336
+ middle(state, previous, { method: "@globalState@", time: -1, props: {}, selector: selector });
337
+ });
338
+ }, [state, previous, middleware]);
339
+ return [state, dispatchers, {}];
340
+ }, { dispatchers: dispatchers, getState: function () { return state; } });
341
+ };
342
+
343
+ var createStoragePlugin = function (storage) {
344
+ return function (key) {
345
+ return function (state, _) {
346
+ storage().set(key, JSON.stringify(state));
347
+ return state;
348
+ };
349
+ };
350
+ };
351
+ var createLocalStoragePlugin = createStoragePlugin(function () { return ({
352
+ set: function (k, v) { return localStorage.setItem(k, v); }
353
+ }); });
354
+ var createSessionStoragePlugin = createStoragePlugin(function () { return ({
355
+ set: function (k, v) { return sessionStorage.setItem(k, v); }
356
+ }); });
357
+ var createLoggerPlugin = function (groupName) {
358
+ return function (state, prev, debug) {
359
+ console.group(groupName);
360
+ console.info("%cAction %c- \"".concat(debug.method, "\" ").concat(debug.time, "ms\n"), "color: gold", "color: white", prev);
361
+ console.info("%cPrevious state\n", "color: silver", prev);
362
+ console.info("%cCurrent state\n", "color: green", state);
363
+ console.info("Props\n", debug.props);
364
+ console.groupEnd();
365
+ return state;
366
+ };
367
+ };
368
+
369
+ exports.clone = clone;
370
+ exports.createGlobalReducer = createGlobalReducer;
371
+ exports.createLocalStoragePlugin = createLocalStoragePlugin;
372
+ exports.createLoggerPlugin = createLoggerPlugin;
373
+ exports.createSessionStoragePlugin = createSessionStoragePlugin;
374
+ exports.createStoragePlugin = createStoragePlugin;
375
+ exports.dispatchCallback = dispatchCallback;
376
+ exports.entries = entries;
377
+ exports.isObject = isObject;
378
+ exports.isPrimitive = isPrimitive;
379
+ exports.isPromise = isPromise;
380
+ exports.keys = keys;
381
+ exports.shallowCompare = shallowCompare;
382
+ exports.useLegacyReducer = useLegacyReducer;
383
+ exports.useMutable = useMutable;
384
+ exports.usePrevious = usePrevious;
385
+ exports.useReducer = useReducer;
38
386
  //# sourceMappingURL=index.cjs.map