@chaomingd/store 2.0.7

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,22 @@
1
+ import { EventEmitter2 } from '@chaomingd/utils';
2
+ export interface AsyncManagerOptions {
3
+ retryCount?: number;
4
+ retryInterval?: number;
5
+ }
6
+ export declare class AsyncManager<T, Fn extends (aborts: {
7
+ lastAbortController: AbortController | null;
8
+ abortController: AbortController;
9
+ }, tryCount: number) => Promise<T>> extends EventEmitter2<{
10
+ loading: (() => void)[];
11
+ success: ((result: any) => void)[];
12
+ error: ((error: Error) => void)[];
13
+ finish: ((error: Error | null, result: any) => void)[];
14
+ }> {
15
+ execId: number;
16
+ options: AsyncManagerOptions;
17
+ abortSignalMap: Record<number, AbortController>;
18
+ constructor(options?: AsyncManagerOptions);
19
+ getCurrentExecId(): number;
20
+ getAbortController(execId: number): AbortController;
21
+ exec(fn: Fn): Promise<T>;
22
+ }
@@ -0,0 +1,89 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
4
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
5
+ function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
6
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
7
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
8
+ function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
9
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
10
+ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
11
+ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
12
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
14
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
15
+ import { EventEmitter2 } from '@chaomingd/utils';
16
+ var DEFAULT_TIMEOUT = 300;
17
+ export var AsyncManager = /*#__PURE__*/function (_EventEmitter) {
18
+ _inherits(AsyncManager, _EventEmitter);
19
+ var _super = _createSuper(AsyncManager);
20
+ function AsyncManager(options) {
21
+ var _this;
22
+ _classCallCheck(this, AsyncManager);
23
+ _this = _super.call(this);
24
+ _defineProperty(_assertThisInitialized(_this), "execId", 0);
25
+ _defineProperty(_assertThisInitialized(_this), "options", {});
26
+ _defineProperty(_assertThisInitialized(_this), "abortSignalMap", {});
27
+ if (options) {
28
+ _this.options = options;
29
+ }
30
+ return _this;
31
+ }
32
+ _createClass(AsyncManager, [{
33
+ key: "getCurrentExecId",
34
+ value: function getCurrentExecId() {
35
+ return this.execId;
36
+ }
37
+ }, {
38
+ key: "getAbortController",
39
+ value: function getAbortController(execId) {
40
+ return this.abortSignalMap[execId];
41
+ }
42
+ }, {
43
+ key: "exec",
44
+ value: function exec(fn) {
45
+ var _this2 = this;
46
+ var tryCount = 0;
47
+ var execId = ++this.execId;
48
+ this.emit('loading');
49
+ return new Promise(function (resolve, reject) {
50
+ var _exec = function _exec() {
51
+ var lastAbortController = _this2.abortSignalMap[execId - 1] || null;
52
+ var abortController = _this2.abortSignalMap[execId] = new AbortController();
53
+ fn({
54
+ lastAbortController: lastAbortController,
55
+ abortController: abortController
56
+ }, tryCount).then(function (res) {
57
+ if (execId === _this2.execId) {
58
+ _this2.emit('success', res);
59
+ }
60
+ resolve(res);
61
+ delete _this2.abortSignalMap[execId];
62
+ _this2.emit('finish', null, res);
63
+ return res;
64
+ }).catch(function (e) {
65
+ if (execId === _this2.execId) {
66
+ if (tryCount < (_this2.options.retryCount || 0)) {
67
+ setTimeout(function () {
68
+ _exec();
69
+ }, _this2.options.retryInterval || DEFAULT_TIMEOUT);
70
+ } else {
71
+ _this2.emit('error', e);
72
+ reject(e);
73
+ delete _this2.abortSignalMap[execId];
74
+ _this2.emit('finish', e, null);
75
+ }
76
+ } else {
77
+ delete _this2.abortSignalMap[execId];
78
+ _this2.emit('finish', e, null);
79
+ reject(e);
80
+ }
81
+ tryCount++;
82
+ });
83
+ };
84
+ _exec();
85
+ });
86
+ }
87
+ }]);
88
+ return AsyncManager;
89
+ }(EventEmitter2);
@@ -0,0 +1,85 @@
1
+ import { ReactNode } from 'react';
2
+ import type { AsyncManagerOptions } from './Manager/AsyncManager';
3
+ import { AsyncManager } from './Manager/AsyncManager';
4
+ import type { IDispatchOptions, TComputed, TEqualityFn, TWatch } from './type';
5
+ type TSubscribeFunc<TState extends Record<string, any> = Record<string, any>, TEffects extends Record<string, any> = Record<string, any>, UserData extends Record<string, any> = Record<string, any>> = (state: Model<TState, TEffects, UserData>, silent: boolean) => any;
6
+ type IEffects<M extends Model<any, any>> = Record<string, ((this: M, ...args: any[]) => any) | any>;
7
+ export interface IModelConfig<TState extends Record<string, any> = Record<string, any>, TEffects extends IEffects<Model<TState, TEffects>> = IEffects<Model>, UserData extends Record<string, any> = Record<string, any>> {
8
+ autoInit?: boolean;
9
+ state: TState;
10
+ effects?: Partial<TEffects>;
11
+ onStateChange?: (prevState: TState, currentState: TState) => any;
12
+ modifyState?: (prevState: TState, nextState: TState) => Partial<TState> | null;
13
+ watch?: TWatch<TState>;
14
+ computed?: TComputed<TState>;
15
+ userData?: UserData;
16
+ name?: string;
17
+ }
18
+ export declare class Model<TState extends Record<string, any> = Record<string, any>, TEffects extends IEffects<Model<TState, TEffects>> = IEffects<Model<TState, any, any>>, UserData extends Record<string, any> = Record<string, any>> {
19
+ config: IModelConfig<TState, TEffects, UserData>;
20
+ isUnMount: boolean;
21
+ name?: string;
22
+ state: TState;
23
+ _userData: UserData;
24
+ _effects: TEffects;
25
+ _preState: TState;
26
+ _dispatchSignal: string;
27
+ _subscribes: Record<string, TSubscribeFunc<TState, TEffects, UserData>[]>;
28
+ asyncManagerMap: Record<string, AsyncManager<Partial<TState>, (aborts: {
29
+ lastAbortController: AbortController | null;
30
+ abortController: AbortController;
31
+ }, tryCount: number) => Promise<Partial<TState>>>>;
32
+ _isInited: boolean;
33
+ constructor(config: IModelConfig<TState, TEffects, UserData>);
34
+ init(): void;
35
+ asyncManager(name: string, options?: {
36
+ loadingKey?: string;
37
+ errorKey?: string;
38
+ config?: AsyncManagerOptions;
39
+ showLoading?: boolean;
40
+ }): AsyncManager<Partial<TState>, (aborts: {
41
+ lastAbortController: AbortController | null;
42
+ abortController: AbortController;
43
+ }, tryCount: number) => Promise<Partial<TState>>>;
44
+ subscribe(func: TSubscribeFunc<TState, TEffects, UserData>, name?: string): () => void;
45
+ getSubscribeName(name?: string): string;
46
+ unsubscribe(func: TSubscribeFunc<TState, TEffects, UserData>, name?: string): void;
47
+ getUserData(): UserData;
48
+ setUserData(userData: Partial<UserData>): void;
49
+ setState(state: Partial<TState> | ((state: TState) => Partial<TState>), options?: IDispatchOptions): void;
50
+ getActualState(prevState: TState, payload: Partial<TState>): TState & Partial<TState>;
51
+ getState: () => TState;
52
+ dispatch(options?: IDispatchOptions): void;
53
+ setEffect<M extends TEffects[keyof TEffects]>(name: keyof TEffects, effect: M): void;
54
+ setEffects(effects: Partial<TEffects>): void;
55
+ getEffect<Name extends keyof TEffects>(name: Name): (...args: Parameters<TEffects[Name]>) => ReturnType<TEffects[Name]>;
56
+ dispose(): void;
57
+ useSelector: (equalityFn?: TEqualityFn<TState>, name?: string) => TState;
58
+ useGetState: <Key extends keyof TState>(keys?: Key[], equalityFn?: TEqualityFn<TState>, name?: string) => TState;
59
+ useUpdate: <Key extends keyof TState>(keys?: Key[], equalityFn?: TEqualityFn<TState>) => void;
60
+ subscribeWithKeys<Key extends keyof TState>(func: TSubscribeFunc<TState, TEffects>, options: {
61
+ keys?: Key[];
62
+ equalityFn?: TEqualityFn<TState>;
63
+ name?: string;
64
+ }): () => void;
65
+ useSubscribe: <Key extends keyof TState>(func: TSubscribeFunc<TState, TEffects>, options?: {
66
+ keys?: Key[];
67
+ equalityFn?: TEqualityFn<TState>;
68
+ name?: string;
69
+ forceUpdate?: boolean;
70
+ }) => void;
71
+ UI: <Key extends keyof TState>({ children, keys, equalityFn, name, }: {
72
+ children: (state: TState) => ReactNode | ReactNode[];
73
+ keys?: Key[] | undefined;
74
+ equalityFn?: TEqualityFn<TState> | undefined;
75
+ name?: string | undefined;
76
+ }) => ReactNode | ReactNode[];
77
+ }
78
+ export declare function useModel<TState extends Record<string, any>, TEffects extends IEffects<Model<TState, TEffects>> = IEffects<Model<TState>>, UserData extends Record<string, any> = Record<string, any>>(modelConfig: IModelConfig<TState, TEffects, UserData>): Model<TState, TEffects, UserData>;
79
+ export declare function createAsyncEffect<EffectHandler extends (options?: {
80
+ showLoading?: boolean;
81
+ }, ...args: any[]) => Promise<any>>(effectHandler: EffectHandler, config: {
82
+ loadingKey: string;
83
+ }): EffectHandler;
84
+ export declare function createEqualityFn(keys?: string[]): (prevState: Record<string, any>, nextState: Record<string, any>) => boolean;
85
+ export * from './type';
@@ -0,0 +1,394 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
5
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
6
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
7
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
8
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
9
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
10
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
11
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
12
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
13
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
14
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
15
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
16
+ import { arrayToMap, shallowEqualKeys, uuid } from '@chaomingd/utils';
17
+ import { useCreation, useLatest, useMemoizedFn } from 'ahooks';
18
+ import { useEffect, useRef, useState } from 'react';
19
+ import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector';
20
+ import { AsyncManager } from "./Manager/AsyncManager";
21
+ import { calcComputedState, execWatchHandler } from "./utils";
22
+ var useSyncExternalStoreWithSelector = useSyncExternalStoreExports.useSyncExternalStoreWithSelector;
23
+ var DEFAULT_SUBSCRIBE_NAME = 'reactStoreSubscribe';
24
+ export var Model = /*#__PURE__*/function () {
25
+ function Model(config) {
26
+ var _this = this;
27
+ _classCallCheck(this, Model);
28
+ _defineProperty(this, "isUnMount", false);
29
+ _defineProperty(this, "name", void 0);
30
+ _defineProperty(this, "state", {});
31
+ _defineProperty(this, "_userData", {});
32
+ _defineProperty(this, "_effects", {});
33
+ _defineProperty(this, "_preState", {});
34
+ _defineProperty(this, "_dispatchSignal", '');
35
+ _defineProperty(this, "_subscribes", {});
36
+ _defineProperty(this, "asyncManagerMap", {});
37
+ _defineProperty(this, "_isInited", false);
38
+ _defineProperty(this, "getState", function () {
39
+ return _this.state;
40
+ });
41
+ _defineProperty(this, "useSelector", function (equalityFn, name) {
42
+ // eslint-disable-next-line
43
+ var subscribe = useMemoizedFn(function (listener) {
44
+ return _this.subscribe(function (_, silent) {
45
+ if (!silent) {
46
+ listener();
47
+ }
48
+ }, name);
49
+ });
50
+ var selector = useMemoizedFn(function (state) {
51
+ return state;
52
+ });
53
+ var isEqual = useMemoizedFn(function (prevState, nextState) {
54
+ if (equalityFn) {
55
+ return equalityFn(prevState, nextState);
56
+ }
57
+ return Object.is(prevState, nextState);
58
+ });
59
+ var state = useSyncExternalStoreWithSelector(subscribe, _this.getState, _this.getState, selector, isEqual);
60
+ return state;
61
+ });
62
+ _defineProperty(this, "useGetState", function (keys, equalityFn, name) {
63
+ var state = _this.useSelector(function (prevState, nextState) {
64
+ if (keys && shallowEqualKeys(prevState, nextState, keys)) {
65
+ return true;
66
+ }
67
+ if (equalityFn && equalityFn(prevState, nextState)) {
68
+ return true;
69
+ }
70
+ return false;
71
+ }, name);
72
+ return state;
73
+ });
74
+ _defineProperty(this, "useUpdate", function (keys, equalityFn) {
75
+ _this.useGetState(keys, equalityFn);
76
+ });
77
+ _defineProperty(this, "useSubscribe", function (func, options) {
78
+ var unmountRef = useRef(false);
79
+ var funcRef = useLatest(func);
80
+ // eslint-disable-next-line
81
+ var _useState = useState({}),
82
+ _useState2 = _slicedToArray(_useState, 2),
83
+ _ = _useState2[0],
84
+ forceUpdate = _useState2[1];
85
+ var optionsRef = useLatest(options);
86
+ var needDispatchRef = useRef(false);
87
+ useEffect(function () {
88
+ var _funcRef$current;
89
+ unmountRef.current = false;
90
+ (_funcRef$current = funcRef.current) === null || _funcRef$current === void 0 || _funcRef$current.call(funcRef, _this, false);
91
+ var unsubscribe = _this.subscribeWithKeys(function (__, silent) {
92
+ if (!unmountRef.current) {
93
+ var _optionsRef$current;
94
+ needDispatchRef.current = true;
95
+ if (((_optionsRef$current = optionsRef.current) === null || _optionsRef$current === void 0 ? void 0 : _optionsRef$current.forceUpdate) !== false && silent !== true) {
96
+ forceUpdate({});
97
+ }
98
+ }
99
+ }, options || {});
100
+ return function () {
101
+ unmountRef.current = true;
102
+ unsubscribe();
103
+ };
104
+ // eslint-disable-next-line
105
+ }, []);
106
+ useEffect(function () {
107
+ if (needDispatchRef.current) {
108
+ var _funcRef$current2;
109
+ (_funcRef$current2 = funcRef.current) === null || _funcRef$current2 === void 0 || _funcRef$current2.call(funcRef, _this, false);
110
+ needDispatchRef.current = false;
111
+ }
112
+ }, [_this._dispatchSignal, funcRef]);
113
+ });
114
+ _defineProperty(this, "UI", function (_ref) {
115
+ var children = _ref.children,
116
+ keys = _ref.keys,
117
+ equalityFn = _ref.equalityFn,
118
+ name = _ref.name;
119
+ var state = _this.useGetState(keys, equalityFn, name);
120
+ return children(state);
121
+ });
122
+ this.config = config;
123
+ if (config.autoInit !== false) {
124
+ this.init();
125
+ }
126
+ }
127
+ _createClass(Model, [{
128
+ key: "init",
129
+ value: function init() {
130
+ if (!this._isInited) {
131
+ this._isInited = true;
132
+ var _config = this.config;
133
+ this.state = this.getActualState({}, _config.state || {});
134
+ this._preState = _objectSpread({}, this.state);
135
+ this._userData = (_config === null || _config === void 0 ? void 0 : _config.userData) || {};
136
+ if (_config.effects) {
137
+ this.setEffects(_config.effects);
138
+ }
139
+ if (_config.name) {
140
+ this.name = _config.name;
141
+ }
142
+ }
143
+ }
144
+ }, {
145
+ key: "asyncManager",
146
+ value: function asyncManager(name, options) {
147
+ var _this2 = this;
148
+ var _ref2 = options || {},
149
+ _ref2$loadingKey = _ref2.loadingKey,
150
+ loadingKey = _ref2$loadingKey === void 0 ? 'loading' : _ref2$loadingKey,
151
+ _ref2$errorKey = _ref2.errorKey,
152
+ errorKey = _ref2$errorKey === void 0 ? 'error' : _ref2$errorKey,
153
+ _ref2$showLoading = _ref2.showLoading,
154
+ showLoading = _ref2$showLoading === void 0 ? true : _ref2$showLoading,
155
+ config = _ref2.config;
156
+ if (!this.asyncManagerMap[name]) {
157
+ this.asyncManagerMap[name] = new AsyncManager(config);
158
+ }
159
+ var asyncManager = this.asyncManagerMap[name];
160
+ asyncManager.offAllListeners();
161
+ asyncManager.on('loading', function () {
162
+ if (showLoading) {
163
+ _this2.setState(_defineProperty({}, loadingKey, true));
164
+ }
165
+ });
166
+ asyncManager.on('success', function (result) {
167
+ if (_typeof(result) === 'object' && result !== null) {
168
+ _this2.setState(_objectSpread(_defineProperty({}, loadingKey, false), result));
169
+ }
170
+ });
171
+ asyncManager.on('error', function (error) {
172
+ _this2.setState(_defineProperty(_defineProperty({}, loadingKey, false), errorKey, error));
173
+ });
174
+ return this.asyncManagerMap[name];
175
+ }
176
+ }, {
177
+ key: "subscribe",
178
+ value: function subscribe(func, name) {
179
+ var _this3 = this;
180
+ var subscribeName = this.getSubscribeName(name);
181
+ if (!this._subscribes[subscribeName]) {
182
+ this._subscribes[subscribeName] = [];
183
+ }
184
+ this._subscribes[subscribeName].push(func);
185
+ return function () {
186
+ _this3.unsubscribe(func, name);
187
+ };
188
+ }
189
+ }, {
190
+ key: "getSubscribeName",
191
+ value: function getSubscribeName(name) {
192
+ return name || DEFAULT_SUBSCRIBE_NAME;
193
+ }
194
+ }, {
195
+ key: "unsubscribe",
196
+ value: function unsubscribe(func, name) {
197
+ var subscribeName = this.getSubscribeName(name);
198
+ if (this._subscribes[subscribeName] && this._subscribes[subscribeName].length) {
199
+ this._subscribes[subscribeName] = this._subscribes[subscribeName].filter(function (fn) {
200
+ return fn !== func;
201
+ });
202
+ }
203
+ }
204
+ }, {
205
+ key: "getUserData",
206
+ value: function getUserData() {
207
+ return _objectSpread({}, this._userData);
208
+ }
209
+ }, {
210
+ key: "setUserData",
211
+ value: function setUserData(userData) {
212
+ Object.assign(this._userData, userData);
213
+ }
214
+ }, {
215
+ key: "setState",
216
+ value: function setState(state, options) {
217
+ if (state) {
218
+ if (typeof state === 'function') {
219
+ this.state = this.getActualState(this._preState, state(this.state));
220
+ } else {
221
+ this.state = this.getActualState(this._preState, state);
222
+ }
223
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
224
+ this.config.onStateChange && this.config.onStateChange(this._preState, this.getState());
225
+ this.dispatch(options);
226
+ this._preState = _objectSpread({}, this.state);
227
+ }
228
+ }
229
+ }, {
230
+ key: "getActualState",
231
+ value: function getActualState(prevState, payload) {
232
+ var nextState = _objectSpread(_objectSpread({}, prevState), payload);
233
+ var _ref3 = this.config || {},
234
+ modifyState = _ref3.modifyState,
235
+ watch = _ref3.watch,
236
+ computed = _ref3.computed;
237
+ var partialState;
238
+ if (modifyState) {
239
+ partialState = modifyState(prevState, nextState);
240
+ if (partialState && _typeof(partialState) === 'object') {
241
+ Object.assign(nextState, partialState);
242
+ }
243
+ }
244
+ // 处理计算属性
245
+ nextState = calcComputedState({
246
+ prevState: prevState,
247
+ nextState: nextState,
248
+ computed: computed
249
+ });
250
+ // 执行 watch
251
+ execWatchHandler({
252
+ prevState: prevState,
253
+ nextState: nextState,
254
+ watch: watch
255
+ });
256
+ return nextState;
257
+ }
258
+ }, {
259
+ key: "dispatch",
260
+ value: function dispatch(options) {
261
+ var _this4 = this;
262
+ if (this.isUnMount) return;
263
+ var subscribeNames = Object.keys(this._subscribes);
264
+ if (options) {
265
+ if (options.include) {
266
+ var includeNameMap = arrayToMap(options.include);
267
+ subscribeNames = subscribeNames.filter(function (name) {
268
+ return includeNameMap[name];
269
+ });
270
+ }
271
+ if (options.exclude) {
272
+ var excludeNameMap = arrayToMap(options.exclude);
273
+ subscribeNames = subscribeNames.filter(function (name) {
274
+ return !excludeNameMap[name];
275
+ });
276
+ }
277
+ }
278
+ this._dispatchSignal = uuid();
279
+ subscribeNames.forEach(function (subscribeName) {
280
+ if (_this4._subscribes[subscribeName]) {
281
+ _this4._subscribes[subscribeName].forEach(function (func) {
282
+ return func(_this4, (options === null || options === void 0 ? void 0 : options.silent) || false);
283
+ });
284
+ }
285
+ });
286
+ }
287
+ }, {
288
+ key: "setEffect",
289
+ value: function setEffect(name, effect) {
290
+ if (this._effects[name] !== effect) {
291
+ this._effects[name] = typeof effect === 'function' ? effect.bind(this) : effect;
292
+ }
293
+ }
294
+ }, {
295
+ key: "setEffects",
296
+ value: function setEffects(effects) {
297
+ var _this5 = this;
298
+ Object.keys(effects).forEach(function (name) {
299
+ _this5.setEffect(name, effects[name]);
300
+ });
301
+ }
302
+ }, {
303
+ key: "getEffect",
304
+ value: function getEffect(name) {
305
+ var _this6 = this;
306
+ return function () {
307
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
308
+ args[_key] = arguments[_key];
309
+ }
310
+ return _this6._effects[name].apply(_this6, args);
311
+ };
312
+ }
313
+ }, {
314
+ key: "dispose",
315
+ value: function dispose() {
316
+ this._effects = {};
317
+ this.state = {};
318
+ }
319
+ }, {
320
+ key: "subscribeWithKeys",
321
+ value: function subscribeWithKeys(func, options) {
322
+ var _this7 = this;
323
+ var keys = options.keys,
324
+ equalityFn = options.equalityFn,
325
+ name = options.name;
326
+ return this.subscribe(function (_, silent) {
327
+ var nextState = _this7.getState();
328
+ if (keys && shallowEqualKeys(_this7._preState, nextState, keys)) {
329
+ return;
330
+ }
331
+ if (equalityFn && equalityFn(_this7._preState, nextState)) {
332
+ return;
333
+ }
334
+ func(_this7, silent);
335
+ }, name);
336
+ }
337
+ }]);
338
+ return Model;
339
+ }();
340
+ export function useModel(modelConfig) {
341
+ var model = useCreation(function () {
342
+ return new Model(modelConfig);
343
+ }, []);
344
+ model.config = modelConfig;
345
+ if (modelConfig.effects) {
346
+ model.setEffects(modelConfig.effects);
347
+ }
348
+ useEffect(function () {
349
+ model.isUnMount = false;
350
+ return function () {
351
+ model.isUnMount = true;
352
+ };
353
+ }, [model]);
354
+ return model;
355
+ }
356
+ export function createAsyncEffect(effectHandler, config) {
357
+ return function () {
358
+ var options = arguments.length <= 0 ? undefined : arguments[0];
359
+ var loadingKey = (config === null || config === void 0 ? void 0 : config.loadingKey) || 'loading';
360
+ var showLoading = options === null || options === void 0 ? void 0 : options.showLoading;
361
+ var model = this;
362
+ if (showLoading !== false) {
363
+ model.setState(_defineProperty({}, loadingKey, true));
364
+ }
365
+ var fetchCountKey = "".concat(loadingKey, "-count");
366
+ if (model[fetchCountKey] === undefined) {
367
+ model[fetchCountKey] = -1;
368
+ }
369
+ var fetchCount = ++model[fetchCountKey];
370
+ return effectHandler.apply(void 0, arguments).then(function (data) {
371
+ if (fetchCount !== model[fetchCountKey]) return data;
372
+ var nextState = {};
373
+ if (showLoading !== false) {
374
+ nextState[loadingKey] = false;
375
+ }
376
+ if (data && _typeof(data) === 'object') {
377
+ Object.assign(nextState, data);
378
+ }
379
+ model.setState(nextState);
380
+ return data;
381
+ }).catch(function (e) {
382
+ if (showLoading !== false) {
383
+ model.setState(_defineProperty({}, loadingKey, false));
384
+ }
385
+ throw e;
386
+ });
387
+ };
388
+ }
389
+ export function createEqualityFn(keys) {
390
+ return function (prevState, nextState) {
391
+ return shallowEqualKeys(prevState, nextState, keys);
392
+ };
393
+ }
394
+ export * from "./type";
@@ -0,0 +1,17 @@
1
+ export type TEqualityFn<TState extends Record<string, any>> = (prevState: TState, nextState: TState) => boolean;
2
+ export type TPromiseValue<T> = T | Promise<T>;
3
+ export type TComputedHandler<TState, R = any> = (state: TState, keyMap: Record<keyof TState & string, boolean>, prevState: TState) => R;
4
+ export type TWatch<TState extends Record<string, any>> = {
5
+ keys: (keyof TState)[];
6
+ hander: TComputedHandler<TState, any>;
7
+ }[];
8
+ export type TComputed<TState extends Record<string, any>> = ({
9
+ keys: (keyof TState)[];
10
+ hander: TComputedHandler<TState, Partial<TState>>;
11
+ } | ((state: TState, prevState: TState) => Partial<TState>))[];
12
+ export interface IDispatchOptions {
13
+ include?: string[];
14
+ exclude?: string[];
15
+ silent?: boolean;
16
+ }
17
+ export type TSelectorFn<TState> = (state: TState) => Partial<TState>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import type { TComputed, TWatch } from '../type';
2
+ interface IComputedConfig<TState extends Record<string, any>> {
3
+ prevState: TState;
4
+ nextState: TState;
5
+ computed?: TComputed<TState>;
6
+ }
7
+ export declare function calcDiffKeys(obj1: object, obj2: object, keys: (string | number | symbol)[]): {
8
+ diffKeysMap: Record<string | number | symbol, boolean>;
9
+ diff: boolean;
10
+ };
11
+ export declare function calcComputedState<TState extends Record<string, any>>({ prevState, nextState, computed, }: IComputedConfig<TState>): TState;
12
+ interface IWatchConfig<TState extends Record<string, any>> {
13
+ prevState: TState;
14
+ nextState: TState;
15
+ watch?: TWatch<TState>;
16
+ }
17
+ export declare function execWatchHandler<TState extends Record<string, any>>({ prevState, nextState, watch, }: IWatchConfig<TState>): void;
18
+ export {};