@webkrafters/react-observable-context 4.0.0-alpha.2 → 4.0.0-alpha.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.
@@ -1 +1 @@
1
- /** @type {"@@STATE"} */
1
+ export const FULL_STATE_SELECTOR: "@@STATE";
package/dist/constants.js CHANGED
@@ -3,9 +3,7 @@ Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
5
  exports.NULL_STATE_SELECTOR = exports.FULL_STATE_SELECTOR = void 0;
6
- /** @type {"@@STATE"} */
7
6
  var FULL_STATE_SELECTOR = '@@STATE';
8
7
  exports.FULL_STATE_SELECTOR = FULL_STATE_SELECTOR;
9
- /** @type {""} */
10
8
  var NULL_STATE_SELECTOR = '';
11
9
  exports.NULL_STATE_SELECTOR = NULL_STATE_SELECTOR;
@@ -1 +1 @@
1
- export default usePrehooksRef;
2
1
  * @param {Prehooks<T>} prehooks
3
2
  * @template {State} T
4
3
  */
4
+ export default usePrehooksRef;
@@ -4,7 +4,6 @@ Object.defineProperty(exports, "__esModule", {
4
4
  });
5
5
  exports["default"] = void 0;
6
6
  var _react = require("react");
7
- /**
8
7
  * @param {Prehooks<T>} prehooks
9
8
  * @template {State} T
10
9
  */
11
10
  var usePrehooksRef = function usePrehooksRef(prehooks) {
12
11
  var prehooksRef = (0, _react.useRef)(prehooks);
13
12
  (0, _react.useEffect)(function () {
@@ -1 +1 @@
1
- export default useRenderKeyProvider;
2
1
  [selectorKey: string]: string | keyof T;
3
2
  * @type {Provider<T>}
4
3
  * @template {State} T
5
4
  */
5
+ export default useRenderKeyProvider;
6
6
  [selectorKey: string]: string | keyof T;
@@ -4,31 +4,19 @@ Object.defineProperty(exports, "__esModule", {
4
4
  });
5
5
  exports["default"] = void 0;
6
6
  var _react = require("react");
7
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
- 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."); }
9
- 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); }
10
- 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; }
11
- function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) { ; } } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
12
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
13
- /**
14
7
  * @type {Provider<T>}
15
8
  * @template {State} T
16
9
  */
17
10
  var getCurrKeys = function getCurrKeys(selectorMap) {
18
11
  var currKeys = Object.values(selectorMap);
19
12
  return currKeys.length ? Array.from(new Set(currKeys)) : [];
20
13
  };
21
- /**
22
14
  * @type {Provider<T>}
23
15
  * @template {State} T
24
16
  */
25
17
  var useRenderKeyProvider = function useRenderKeyProvider(selectorMap) {
26
- var _useState = (0, _react.useState)(function () {
27
- return getCurrKeys(selectorMap);
28
- }),
29
- _useState2 = _slicedToArray(_useState, 2),
30
- renderKeys = _useState2[0],
31
- setRenderKeys = _useState2[1];
18
+ var renderKeys = (0, _react.useRef)([]);
32
19
  var currKeys = getCurrKeys(selectorMap);
33
- (renderKeys.length !== currKeys.length || renderKeys.some(function (k, i) {
20
+ if (renderKeys.current.length !== currKeys.length || renderKeys.current.some(function (k, i) {
34
21
  return k !== currKeys[i];
35
- })) && setRenderKeys(currKeys);
36
- return renderKeys;
22
+ })) {
23
+ renderKeys.current = currKeys;
24
+ }
25
+ return renderKeys.current;
37
26
  };
38
27
  var _default = useRenderKeyProvider;
39
- /**
40
28
  * @callback Provider
41
29
  * @param {{[selectorKey: string]: string|keyof T}} selectorMap Key:value pairs where `key` => arbitrary key given to Store.data property holding the state slices and `value` => property paths to state slices used by this component. May use `{..., state: '@@STATE'}` to indicate a desire to obtain the entire state object and assign to a `state` property of Store.data. A change in any of the referenced properties results in this component render. When using `['@@STATE']`, any change in the state object results in this component render.
42
30
  * @returns {[string|keyof T]} Property paths
43
31
  * @template {State} T
44
32
  */
45
33
  exports["default"] = _default;
@@ -1 +1 @@
1
- export default useStateManager;
2
1
  * @param {T} initStateValue
3
2
  * @template {State} T
4
3
  */
5
4
  select: (clientId: string, ...propertyPaths?: string[]) => {
6
5
  [propertyPaths: string]: Readonly<any>;
7
6
  };
8
7
  state: T;
9
8
  stateWatch: Listener<T>;
10
9
  unlink: (clientId: string) => void;
10
+ export default useStateManager;
11
11
  select: (clientId: string, ...propertyPaths?: string[]) => {
12
12
  [propertyPaths: string]: Readonly<any>;
13
13
  };
14
14
  state: T;
15
15
  stateWatch: Listener<T>;
16
16
  unlink: (clientId: string) => void;
@@ -13,25 +13,19 @@ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o =
13
13
  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; }
14
14
  function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) { ; } } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
15
15
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
16
- /**
17
16
  * @param {T} initStateValue
18
17
  * @template {State} T
19
18
  */
20
19
  var useStateManager = function useStateManager(initStateValue) {
21
- /** @type {[T, Function]} */
22
20
  var _useState = (0, _react.useState)(function () {
23
21
  return (0, _lodash["default"])(initStateValue);
24
22
  }),
25
23
  _useState2 = _slicedToArray(_useState, 1),
26
24
  state = _useState2[0];
27
- /** @type {[AccessorCache<T>, Function]} */
28
25
  var _useState3 = (0, _react.useState)(function () {
29
26
  return new _accessorCache["default"](state);
30
27
  }),
31
28
  _useState4 = _slicedToArray(_useState3, 1),
32
29
  cache = _useState4[0];
33
- /** @type {StoreInternal<T>["getState"]} */
34
30
  var select = (0, _react.useCallback)(cache.get.bind(cache), []);
35
- /** @type {Listener<T>} */
36
31
  var stateWatch = (0, _react.useCallback)(cache.watchSource.bind(cache), []);
37
- /** @type {StoreInternal<T>["unlinkCache"]} */
38
32
  var unlink = (0, _react.useCallback)(function (clientId) {
39
33
  return cache.unlinkClient(clientId);
40
34
  }, []);
@@ -1 +1 @@
1
- export namespace deps {
2
1
  export { _setState as setState };
3
2
  export { v4 as uuid };
4
3
  * @param {Prehooks<T>} prehooks
5
4
  * @param {T} value
6
5
  * @param {IStorage<T>} [storage] Closed to modification post-initialization
7
6
  * @template {State} T
8
7
  */
9
8
  getState: (clientId: string, ...propertyPaths?: string[]) => {
10
9
  [propertyPaths: string]: Readonly<any>;
11
10
  };
12
11
  resetState: VoidFunction;
13
12
  setState: (changes: import("../../../types").PartialState<T>) => void;
14
13
  subscribe: (listener: import("../../../types").Listener<T>) => VoidFunction;
15
14
  unlinkCache: (clientId: string) => void;
15
+ export namespace deps {
16
16
  export { _setState as setState };
17
17
  export { v4 as uuid };
18
18
  getState: (clientId: string, ...propertyPaths?: string[]) => {
19
19
  [propertyPaths: string]: Readonly<any>;
20
20
  };
21
21
  resetState: (propertyPaths?: string[]) => void;
22
22
  setState: (changes: import("../../../types").PartialState<T>) => void;
23
23
  subscribe: (listener: import("../../../types").Listener<T>) => VoidFunction;
24
24
  unlinkCache: (clientId: string) => void;
@@ -6,6 +6,8 @@ exports.deps = exports["default"] = void 0;
6
6
  var _react = require("react");
7
7
  var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
8
8
  var _uuid = require("uuid");
9
+ var _constants = require("../../../constants");
10
+ var _utils = require("../../../utils");
9
11
  var _storage2 = _interopRequireDefault(require("../../../model/storage"));
10
12
  var _usePrehooksRef = _interopRequireDefault(require("../use-prehooks-ref"));
11
13
  var _useStateManager2 = _interopRequireDefault(require("../use-state-manager"));
@@ -22,24 +24,20 @@ var deps = {
22
24
  uuid: _uuid.v4
23
25
  };
24
26
  exports.deps = deps;
25
- /**
26
27
  * @param {Prehooks<T>} prehooks
27
28
  * @param {T} value
28
29
  * @param {IStorage<T>} [storage] Closed to modification post-initialization
29
30
  * @template {State} T
30
31
  */
31
32
  var useStore = function useStore(prehooks, value, storage) {
32
33
  var mounted = (0, _react.useRef)(false);
33
34
  var prehooksRef = (0, _usePrehooksRef["default"])(prehooks);
34
- /** @type {MutableRefObject<string>} */
35
35
  var storageKey = (0, _react.useRef)();
36
36
  var _useStateManager = (0, _useStateManager2["default"])(value),
37
37
  select = _useStateManager.select,
38
38
  state = _useStateManager.state,
39
39
  stateWatch = _useStateManager.stateWatch,
40
40
  unlink = _useStateManager.unlink;
41
- /** @type {[Set<Listener<T>>, Function]} */
42
41
  var _useState = (0, _react.useState)(function () {
43
42
  return new Set();
44
43
  }),
45
44
  _useState2 = _slicedToArray(_useState, 1),
46
45
  listeners = _useState2[0];
47
- /** @type {[IStorage<T>, Function]} */
48
46
  var _useState3 = (0, _react.useState)(function () {
49
47
  var isKeyRequired = true;
50
48
  var _storage = storage;
@@ -52,26 +50,24 @@ var useStore = function useStore(prehooks, value, storage) {
52
50
  }),
53
51
  _useState4 = _slicedToArray(_useState3, 1),
54
52
  _storage = _useState4[0];
55
- /** @type {Listener<T>} */
56
53
  var onChange = function onChange(changes) {
57
54
  return listeners.forEach(function (listener) {
58
55
  return listener(changes);
59
56
  });
60
57
  };
61
- /** @type {StoreInternal<T>["resetState"]} */
62
58
  var resetState = (0, _react.useCallback)(function () {
63
- var original = _storage.getItem(storageKey.current);
64
- (!('resetState' in prehooksRef.current) || prehooksRef.current.resetState({
59
+ var propertyPaths = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
60
+ var original = _storage.clone(_storage.getItem(storageKey.current));
61
+ var resetData = !propertyPaths.length ? {} : propertyPaths.includes(_constants.FULL_STATE_SELECTOR) ? original : (0, _utils.mapPathsToObject)(original, propertyPaths);
62
+ (!('resetState' in prehooksRef.current) || prehooksRef.current.resetState(resetData, {
65
63
  current: (0, _lodash["default"])(state),
66
64
  original: original
67
- })) && deps.setState(state, original, onChange);
65
+ })) && deps.setState(state, resetData, onChange);
68
66
  }, []);
69
- /** @type {StoreInternal<T>["setState"]} */
70
67
  var setState = (0, _react.useCallback)(function (changes) {
71
68
  changes = (0, _lodash["default"])(changes);
72
69
  (!('setState' in prehooksRef.current) || prehooksRef.current.setState(changes)) && deps.setState(state, changes, onChange);
73
70
  }, []);
74
- /** @type {StoreInternal<T>["subscribe"]} */
75
71
  var subscribe = (0, _react.useCallback)(function (listener) {
76
72
  listeners.add(listener);
77
73
  return function () {
@@ -80,7 +76,7 @@ var useStore = function useStore(prehooks, value, storage) {
80
76
  }, []);
81
77
  (0, _react.useEffect)(function () {
82
78
  var sKey = storageKey.current;
83
- _storage.setItem(sKey, value);
79
+ _storage.setItem(sKey, _storage.clone(value));
84
80
  return function () {
85
81
  return _storage.removeItem(sKey);
86
82
  };
@@ -1 +1,41 @@
1
- export class UsageError extends Error {
2
1
  [selectorKey: string]: string | keyof T_1;
3
2
  Provider: ObservableProvider<S>;
4
3
  children?: ReactNode;
5
4
  prehooks?: Prehooks<T>;
6
5
  storage?: IStorage<T>;
7
6
  value: PartialState<T>;
7
+ export class UsageError extends Error {
8
+ /**
9
+ * @param {ObservableContext<T>} context Refers to the PublicObservableContext<T> type of the ObservableContext<T>
10
+ * @param {{[selectorKey: string]: string|keyof T}} [selectorMap] Key:value pairs where `key` => arbitrary key given to Store.data property holding the state slices and `value` => property paths to state slices used by this component: see examples below. May use `{..., state: '@@STATE'}` to indicate a desire to obtain the entire state object and assign to a `state` property of Store.data. A change in any of the referenced properties results in this component render. When using `['@@STATE']`, any change in the state object results in this component render.
11
+ * @returns {(WrappedComponent: C) => MemoExoticComponent<P>}
12
+ * @template {State} T
13
+ * @template {PartialStore<T> & {[x:string]:*}} [P=PartialStore<T>]
14
+ * @template {ComponentType<P>|ExoticComponent<P>} C
15
+ * @see {ObservableContext<T>}
16
+ * @see {useContext} for selectorMap sample
17
+ */
18
+ export function connect<T extends import("../types").State, P extends PartialStore<T> & {
8
19
  [x: string]: any;
9
20
  [selectorKey: string]: string | keyof T;
21
+ /**
22
+ * @returns {ObservableContext<T>} Refers to the IObservableContext<T> type of the ObservableContext<T>
23
+ * @template {State} T
24
+ * @see {ObservableContext<T>}
25
+ */
26
+ export function createContext<T extends import("../types").State>(): ObservableContext<T>;
27
+ /**
28
+ * Actively monitors the store and triggers component re-render if any of the watched keys in the state objects changes
29
+ *
30
+ * @param {ObservableContext<T>} context Refers to the PublicObservableContext<T> type of the ObservableContext<T>
31
+ * @param {{[selectorKey: string]: string|keyof T}} [selectorMap = {}] Key:value pairs where `key` => arbitrary key given to Store.data property holding the state slices and `value` => property paths to state slices used by this component: see examples below. May use `{..., state: '@@STATE'}` to indicate a desire to obtain the entire state object and assign to a `state` property of Store.data. A change in any of the referenced properties results in this component render. When using `['@@STATE']`, any change in the state object results in this component render.
32
+ * @returns {Store<T>}
33
+ * @template {State} T
34
+ * @see {ObservableContext<T>}
35
+ * @example
36
+ * a valid propertyPath follows the `lodash` object property path convention.
37
+ * for a state = { a: 1, b: 2, c: 3, d: { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] } }
38
+ * Any of the following is an applicable selector map.
39
+ * {count: 'a', myData: 'd'} => {count: 1, myData: { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] }}
40
+ * {count: 'a'} => {count: 1} // same applies to {count: 'b'} = {count: 2}; {count: 'c'} = {count: 3}
41
+ * {myData: 'd'} => {mydata: { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] }}
42
+ * {xyz: 'd.e'} => {xyz: 5}
43
+ * {def: 'd.e.f'} => {def: [6, { x: 7, y: 8, z: 9 } ]}
44
+ * {f1: 'd.e.f[0]'} or {f1: 'd.e.f.0'} => {f1: 6}
45
+ * {secondFElement: 'd.e.f[1]'} or {secondFElement: 'd.e.f.1'} => {secondFElement: { x: 7, y: 8, z: 9 }}
46
+ * {myX: 'd.e.f[1].x'} or {myX: 'd.e.f.1.x'} => {myX: 7} // same applies to {myY: 'd.e.f[1].y'} = {myY: 8}; {myZ: 'd.e.f[1].z'} = {myZ: 9}
47
+ * {myData: '@@STATE'} => {myData: state}
48
+ */
49
+ export function useContext<T extends Stat>(context: ObservableContext<T>, selectorMap?: {
10
50
  [selectorKey: string]: string | keyof T;
11
51
  Provider: ObservableProvider<S>;
12
52
  children?: ReactNode;
13
53
  prehooks?: Prehooks<T>;
14
54
  storage?: IStorage<T>;
15
55
  value: PartialState<T>;
16
56
  data?: import("../types").Data;
17
57
  resetState?: (propertyPaths?: string[]) => void;
18
58
  setState?: (changes: import("../types").PartialState<T>) => void;
19
59
  [x: string]: any;
20
60
  [x: string]: any;
@@ -2,15 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
- exports.useContext = exports.createContext = exports.UsageError = void 0;
5
+ exports.useContext = exports.createContext = exports.connect = exports.UsageError = void 0;
6
6
  var _react = _interopRequireWildcard(require("react"));
7
7
  var _lodash = _interopRequireDefault(require("lodash.isempty"));
8
8
  var _lodash2 = _interopRequireDefault(require("lodash.isequal"));
9
- var _lodash3 = _interopRequireDefault(require("lodash.omit"));
9
+ var _lodash3 = _interopRequireDefault(require("lodash.isplainobject"));
10
+ var _lodash4 = _interopRequireDefault(require("lodash.omit"));
10
11
  var _uuid = require("uuid");
11
12
  var _useRenderKeyProvider = _interopRequireDefault(require("./hooks/use-render-key-provider"));
12
13
  var _useStore = _interopRequireDefault(require("./hooks/use-store"));
13
- var _excluded = ["getState", "subscribe", "unlinkCache"];
14
+ var _excluded = ["getState", "resetState", "subscribe", "unlinkCache"];
14
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
15
16
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
16
17
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
@@ -30,6 +31,7 @@ function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefine
30
31
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
31
32
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
32
33
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
34
+ function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
33
35
  function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
34
36
  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); } }
35
37
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
@@ -56,17 +58,14 @@ var UsageError = function (_Error) {
56
58
  return _createClass(UsageError);
57
59
  }( _wrapNativeSuper(Error));
58
60
  exports.UsageError = UsageError;
59
- /**
60
61
  * @readonly
61
62
  * @type {Prehooks<T>}
62
63
  * @template {State} T
63
64
  */
64
65
  var defaultPrehooks = Object.freeze({});
65
- /** @type {NonReactUsageReport} */
66
66
  var reportNonReactUsage = function reportNonReactUsage() {
67
67
  throw new UsageError('Detected usage outside of this context\'s Provider component tree. Please apply the exported Provider component');
68
68
  };
69
- /** @type {FC<{child: ReactNode}>} */
70
69
  var ChildMemo = function () {
71
70
  var useNodeMemo = function useNodeMemo(node) {
72
71
  var nodeRef = (0, _react.useRef)(node);
73
- if (!(0, _lodash2["default"])((0, _lodash3["default"])(nodeRef.current, '_owner'), (0, _lodash3["default"])(node, '_owner'))) {
72
+ if (!(0, _lodash2["default"])((0, _lodash4["default"])(nodeRef.current, '_owner'), (0, _lodash4["default"])(node, '_owner'))) {
74
73
  nodeRef.current = node;
75
74
  }
76
75
  return nodeRef.current;
@@ -85,7 +84,6 @@ var ChildMemo = function () {
85
84
  Guardian.displayName = 'ObservableContext.Provider.Internal.Guardian';
86
85
  return Guardian;
87
86
  }();
88
- /** @type {(children: ReactNode) => ReactNode} */
89
87
  var memoizeImmediateChildTree = function memoizeImmediateChildTree(children) {
90
88
  return _react.Children.map(children, function (child) {
91
89
  var _child$props;
@@ -93,16 +91,14 @@ var memoizeImmediateChildTree = function memoizeImmediateChildTree(children) {
93
91
  return child;
94
92
  }
95
93
  if ((_child$props = child.props) !== null && _child$props !== void 0 && _child$props.children) {
96
- child = (0, _react.cloneElement)(child, (0, _lodash3["default"])(child.props, 'children'), memoizeImmediateChildTree(child.props.children));
94
+ child = (0, _react.cloneElement)(child, (0, _lodash4["default"])(child.props, 'children'), memoizeImmediateChildTree(child.props.children));
97
95
  }
98
96
  return _react["default"].createElement(ChildMemo, {
99
97
  child: child
100
98
  });
101
99
  });
102
100
  };
103
- /** @param {Provider<IStore>} Provider */
104
101
  var makeObservable = function makeObservable(Provider) {
105
- /**
106
102
  * @type {ObservableProvider<T>}
107
103
  * @template {State} T
108
104
  */
109
105
  var Observable = function Observable(_ref3) {
110
106
  var _ref3$children = _ref3.children,
111
107
  children = _ref3$children === void 0 ? null : _ref3$children,
@@ -118,7 +114,20 @@ var makeObservable = function makeObservable(Provider) {
118
114
  Observable.displayName = 'ObservableContext.Provider';
119
115
  return Observable;
120
116
  };
121
- /**
122
117
  * @returns {ObservableContext<T>} Refers to the IObservableContext<T> type of the ObservableContext<T>
123
118
  * @template {State} T
124
119
  * @see {ObservableContext<T>}
125
120
  */
121
+ var connect = function connect(context, selectorMap) {
122
+ return function (WrappedComponent) {
123
+ if (!(0, _lodash3["default"])(WrappedComponent) || !('compare' in WrappedComponent)) {
124
+ WrappedComponent = (0, _react.memo)(WrappedComponent);
125
+ }
126
+ var ConnectedComponent = (0, _react.memo)(function (ownProps) {
127
+ var store = useContext(context, selectorMap);
128
+ return _react["default"].createElement(WrappedComponent, _extends({}, store, ownProps));
129
+ });
130
+ ConnectedComponent.displayName = 'ObservableContext.Connected';
131
+ return ConnectedComponent;
132
+ };
133
+ };
134
+ exports.connect = connect;
126
135
  var createContext = function createContext() {
127
136
  var Context = (0, _react.createContext)({
128
137
  getState: reportNonReactUsage,
@@ -131,20 +140,18 @@ var createContext = function createContext() {
131
140
  return Context;
132
141
  };
133
142
  exports.createContext = createContext;
134
- /**
135
143
  * Actively monitors the store and triggers component re-render if any of the watched keys in the state objects changes
136
144
  *
137
145
  * @param {ObservableContext<T>} context Refers to the PublicObservableContext<T> type of the ObservableContext<T>
138
146
  * @param {{[selectorKey: string]: string|keyof T}} [selectorMap = {}] Key:value pairs where `key` => arbitrary key given to Store.data property holding the state slices and `value` => property paths to state slices used by this component: see examples below. May use `{..., state: '@@STATE'}` to indicate a desire to obtain the entire state object and assign to a `state` property of Store.data. A change in any of the referenced properties results in this component render. When using `['@@STATE']`, any change in the state object results in this component render.
139
147
  * @returns {Store<T>}
140
148
  * @template {State} T
141
149
  * @see {ObservableContext<T>}
142
150
  * @example
143
151
  * a valid propertyPath follows the `lodash` object property path convention.
144
152
  * for a state = { a: 1, b: 2, c: 3, d: { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] } }
145
153
  * Any of the following is an applicable selector map.
146
154
  * {count: 'a', myData: 'd'} => {count: 1, myData: { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] }}
147
155
  * {count: 'a'} => {count: 1}
148
156
  * {myData: 'd'} => {mydata: { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] }}
149
157
  * {xyz: 'd.e'} => {xyz: 5}
150
158
  * {def: 'd.e.f'} => {def: [6, { x: 7, y: 8, z: 9 } ]}
151
159
  * {f1: 'd.e.f[0]'} or {f1: 'd.e.f.0'} => {f1: 6}
152
160
  * {secondFElement: 'd.e.f[1]'} or {secondFElement: 'd.e.f.1'} => {secondFElement: { x: 7, y: 8, z: 9 }}
153
161
  * {myX: 'd.e.f[1].x'} or {myX: 'd.e.f.1.x'} => {myX: 7}
154
162
  * {myData: '@@STATE'} => {myData: state}
155
163
  */
156
164
  var useContext = function useContext(context) {
157
165
  var selectorMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
158
- /** @type {StoreInternal<T>} */
159
- var _useContext2 = (0, _react.useContext)(context),
160
- _getState = _useContext2.getState,
161
- subscribe = _useContext2.subscribe,
162
- unlinkCache = _useContext2.unlinkCache,
163
- store = _objectWithoutProperties(_useContext2, _excluded);
164
- var _useState = (0, _react.useState)(_uuid.v4),
165
- _useState2 = _slicedToArray(_useState, 1),
166
- clientId = _useState2[0];
166
+ var _React$useContext = _react["default"].useContext(context),
167
+ _getState = _React$useContext.getState,
168
+ _resetState = _React$useContext.resetState,
169
+ subscribe = _React$useContext.subscribe,
170
+ unlinkCache = _React$useContext.unlinkCache,
171
+ store = _objectWithoutProperties(_React$useContext, _excluded);
172
+ var _React$useState = _react["default"].useState(_uuid.v4),
173
+ _React$useState2 = _slicedToArray(_React$useState, 1),
174
+ clientId = _React$useState2[0];
167
175
  var _renderKeys = (0, _useRenderKeyProvider["default"])(selectorMap);
168
- /** @type {{[propertyPath: string]: string}} Reversed selectorMap i.e. {selectorKey: propertyPath} => {propertyPath: selectorKey} */
169
176
  var path2SelectorMap = (0, _react.useMemo)(function () {
170
177
  var map = {};
171
178
  if ((0, _lodash["default"])(_renderKeys)) {
@@ -156,8 +163,7 @@ var useContext = function useContext(context) {
156
163
  }
157
164
  return map;
158
165
  }, [_renderKeys]);
159
- /** @type {[Data, Function]} */
160
- var _useState3 = (0, _react.useState)(function () {
166
+ var _React$useState3 = _react["default"].useState(function () {
161
167
  var data = {};
162
168
  if ((0, _lodash["default"])(_renderKeys)) {
163
169
  return data;
@@ -177,9 +183,9 @@ var useContext = function useContext(context) {
177
183
  }
178
184
  return data;
179
185
  }),
180
- _useState4 = _slicedToArray(_useState3, 2),
181
- data = _useState4[0],
182
- setData = _useState4[1];
186
+ _React$useState4 = _slicedToArray(_React$useState3, 2),
187
+ data = _React$useState4[0],
188
+ setData = _React$useState4[1];
183
189
  var updateData = function updateData() {
184
190
  var hasChanges = false;
185
191
  var state = _getState.apply(void 0, [clientId].concat(_toConsumableArray(_renderKeys)));
@@ -200,7 +206,11 @@ var useContext = function useContext(context) {
200
206
  }
201
207
  hasChanges && setData(_objectSpread({}, data));
202
208
  };
203
- (0, _react.useEffect)(function () {
209
+ var resetState = (0, _react.useCallback)(function () {
210
+ var propertyPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _renderKeys;
211
+ return _resetState(propertyPath);
212
+ }, [_renderKeys]);
213
+ _react["default"].useEffect(function () {
204
214
  if ((0, _lodash["default"])(_renderKeys)) {
205
215
  !(0, _lodash2["default"])({}, data) && setData({});
206
216
  return;
@@ -219,7 +229,8 @@ var useContext = function useContext(context) {
219
229
  }, [_renderKeys]);
220
230
  return (0, _react.useMemo)(function () {
221
231
  return _objectSpread({
222
- data: data
232
+ data: data,
233
+ resetState: resetState
223
234
  }, store);
224
235
  }, [data]);
225
236
  };
@@ -1 +1 @@
1
- export default setState;
2
1
  [rootKey: number]: {
3
2
  [x: string]: any;
4
3
  };
5
4
  [x: string]: any;
6
5
  [rootKey: string]: {
7
6
  [x: string]: any;
8
7
  };
9
8
  [rootKey: symbol]: {
10
9
  [x: string]: any;
11
10
  };
12
11
  [rootKey: number]: T;
13
12
  [rootKey: string]: T;
14
13
  [rootKey: symbol]: T;
15
14
  hasChanges: boolean;
16
15
  * @param {T} state
17
16
  * @param {PartialState<T>} newState
18
17
  * @param {Listener<T>} [onStateChange]
19
18
  * @template {State} T
20
19
  */
20
+ export default setState;
21
21
  [rootKey: number]: {
22
22
  [x: string]: any;
23
23
  };
24
24
  [x: string]: any;
25
25
  [rootKey: string]: {
26
26
  [x: string]: any;
27
27
  };
28
28
  [rootKey: symbol]: {
29
29
  [x: string]: any;
30
30
  };
31
31
  [rootKey: number]: T;
32
32
  [rootKey: string]: T;
33
33
  [rootKey: symbol]: T;
34
34
  hasChanges: boolean;
@@ -14,14 +14,12 @@ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o =
14
14
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
15
15
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
16
16
  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; }
17
- /** @param {{[x:string]: any}} obj */
18
17
  var isIndexBasedObj = function isIndexBasedObj(obj) {
19
18
  return Object.keys(obj).every(function (k) {
20
19
  var i = +k;
21
20
  return Number.isInteger(i) && i > -1;
22
21
  });
23
22
  };
24
- /**
25
23
  * Mutates its arguments
26
24
  *
27
25
  * @param {HasArrayRoot<K>|HasObjectRoot<K>} state
28
26
  * @param {HasArrayRoot<K>|HasObjectRoot<K>} newState
29
27
  * @param {K} stateKey
30
28
  * @param {Stats} stats
31
29
  * @template {KeyTypes} K
32
30
  */
33
31
  function setAtomic(state, newState, stateKey, stats) {
34
32
  if ((0, _lodash2["default"])(state[stateKey], newState[stateKey])) {
35
33
  return;
@@ -43,7 +41,6 @@ function setAtomic(state, newState, stateKey, stats) {
43
41
  state[stateKey] = isArrayNewState || isPlainObjectNewState ? (0, _lodash["default"])(newState[stateKey]) : newState[stateKey];
44
42
  }
45
43
  ;
46
- /**
47
44
  * Mutates its arguments
48
45
  *
49
46
  * @param {HasArrayRoot<K>} state
50
47
  * @param {HasArrayRoot<K>} newState
51
48
  * @param {K} rootKey
52
49
  * @param {Stats} stats
53
50
  * @template {KeyTypes} K
54
51
  */
55
52
  function setArray(state, newState, rootKey, stats) {
56
53
  var nsLength = newState[rootKey].length;
57
54
  if (state[rootKey].length !== nsLength) {
@@ -55,7 +52,6 @@ function setArray(state, newState, rootKey, stats) {
55
52
  }
56
53
  }
57
54
  ;
58
- /**
59
55
  * Mutates its arguments
60
56
  *
61
57
  * @param {HasArrayRoot<K>} state
62
58
  * @param {HasObjectRoot<K>} newState
63
59
  * @param {K} rootKey
64
60
  * @param {Stats} stats
65
61
  * @template {KeyTypes} K
66
62
  */
67
63
  function setArrayIndex(state, newState, rootKey, stats) {
68
64
  var incomingIndexes = Object.keys(newState[rootKey]).map(function (i) {
69
65
  return +i;
@@ -79,19 +75,16 @@ function setArrayIndex(state, newState, rootKey, stats) {
79
75
  }
80
76
  }
81
77
  ;
82
- /**
83
78
  * Mutates its arguments
84
79
  *
85
80
  * @param {HasObjectRoot<K>} state
86
81
  * @param {HasObjectRoot<K>} newState
87
82
  * @param {K} rootKey
88
83
  * @param {Stats} stats
89
84
  * @template {KeyTypes} K
90
85
  */
91
86
  function setPlainObject(state, newState, rootKey, stats) {
92
87
  set(state[rootKey], newState[rootKey], stats);
93
88
  }
94
89
  ;
95
- /**
96
90
  * Mutates its arguments
97
91
  *
98
92
  * @param {HasObjectRoot} state
99
93
  * @param {HasObjectRoot} newState
100
94
  * @param {Stats} stats
101
95
  */
102
96
  function set(state, newState, stats) {
103
97
  for (var k in newState) {
104
98
  setAtomic(state, newState, k, stats);
105
99
  }
106
100
  }
107
101
  ;
108
- /**
109
102
  * @param {T} state
110
103
  * @param {PartialState<T>} newState
111
104
  * @param {Listener<T>} [onStateChange]
112
105
  * @template {State} T
113
106
  */
114
107
  function setState(state, newState, onStateChange) {
115
108
  var stats = {
116
109
  hasChanges: false