@webkrafters/react-observable-context 3.0.0-rc.1 → 4.0.0-alpha.0

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.
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports["default"] = exports.NULL_STATE_SELECTOR = exports.FULL_STATE_SELECTOR = void 0;
6
+ var _react = require("react");
7
+ var _lodash = _interopRequireDefault(require("lodash.isempty"));
8
+ var _lodash2 = _interopRequireDefault(require("lodash.isequal"));
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
10
+ var FULL_STATE_SELECTOR = '@@STATE';
11
+ exports.FULL_STATE_SELECTOR = FULL_STATE_SELECTOR;
12
+ var NULL_STATE_SELECTOR = '';
13
+ exports.NULL_STATE_SELECTOR = NULL_STATE_SELECTOR;
14
+ /**
15
  * @param {string[]} renderKeys
1
16
  * @returns {string[]}
2
17
  */
18
+ var useRenderKeysManager = function useRenderKeysManager(renderKeys) {
19
+ var curKeys = (0, _react.useRef)([]);
20
+ var managedKeys = (0, _react.useMemo)(function () {
21
+ if (!(0, _lodash2["default"])(curKeys.current, renderKeys)) {
22
+ curKeys.current = renderKeys;
23
+ }
24
+ return curKeys.current;
25
+ }, [renderKeys]);
26
+ return (0, _react.useMemo)(function () {
27
+ var selectors = Array.isArray(managedKeys) ? Array.from(new Set(managedKeys)) : [];
28
+ if ((0, _lodash["default"])(selectors)) {
29
+ selectors[0] = NULL_STATE_SELECTOR;
30
+ } else if (managedKeys.includes(FULL_STATE_SELECTOR)) {
31
+ selectors.length = 0;
32
+ }
33
+ return selectors;
34
+ }, [managedKeys]);
35
+ };
36
+ var _default = useRenderKeysManager;
37
+ exports["default"] = _default;
@@ -0,0 +1 @@
1
+ export default useStateManager;
2
  * @param {T} initStateValue
1
3
  * @template {State} T
2
4
  */
3
5
  select: (clientId: string, ...propertyPaths?: string[]) => Readonly<import("../../../types").PartialState<T>>;
4
6
  state: T;
5
7
  stateWatch: Listener<T>;
6
8
  unlink: (clientId: string) => void;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports["default"] = void 0;
6
+ var _react = require("react");
7
+ var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
8
+ var _accessorCache = _interopRequireDefault(require("../../../model/accessor-cache"));
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
10
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
11
+ 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."); }
12
+ 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); }
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
+ 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
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
16
+ /**
17
  * @param {T} initStateValue
1
18
  * @template {State} T
2
19
  */
20
+ var useStateManager = function useStateManager(initStateValue) {
21
+ /** @type {[T, Function]} */
22
+ var _useState = (0, _react.useState)(function () {
23
+ return (0, _lodash["default"])(initStateValue);
24
+ }),
25
+ _useState2 = _slicedToArray(_useState, 1),
26
+ state = _useState2[0];
27
+ /** @type {[AccessorCache<T>, Function]} */
28
+ var _useState3 = (0, _react.useState)(function () {
29
+ return new _accessorCache["default"](state);
30
+ }),
31
+ _useState4 = _slicedToArray(_useState3, 1),
32
+ cache = _useState4[0];
33
+ /** @type {StoreInternal<T>["getState"]} */
34
+ var select = (0, _react.useCallback)(cache.get.bind(cache), []);
35
+ /** @type {Listener<T>} */
36
+ var stateWatch = (0, _react.useCallback)(cache.watchSource.bind(cache), []);
37
+ /** @type {StoreInternal<T>["unlinkCache"]} */
38
+ var unlink = (0, _react.useCallback)(function (clientId) {
39
+ return cache.unlinkClient(clientId);
40
+ }, []);
41
+ return (0, _react.useState)(function () {
42
+ return {
43
+ select: select,
44
+ state: state,
45
+ stateWatch: stateWatch,
46
+ unlink: unlink
47
+ };
48
+ })[0];
49
+ };
50
+ var _default = useStateManager;
51
+ exports["default"] = _default;
@@ -0,0 +1 @@
1
+ export namespace deps {
2
  export { _setState as setState };
1
3
  export { v4 as uuid };
2
4
  * @param {Prehooks<T>} prehooks
3
5
  * @param {T} value
4
6
  * @param {IStorage<T>} [storage] Closed to modification post-initialization
5
7
  * @template {State} T
6
8
  */
7
9
  getState: (clientId: string, ...propertyPaths?: string[]) => Readonly<import("../../../types").PartialState<T>>;
8
10
  resetState: VoidFunction;
9
11
  setState: (changes: import("../../../types").PartialState<T>) => void;
10
12
  subscribe: (listener: import("../../../types").Listener<T>) => VoidFunction;
11
13
  unlinkCache: (clientId: string) => void;
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports.deps = exports["default"] = void 0;
6
+ var _react = require("react");
7
+ var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
8
+ var _uuid = require("uuid");
9
+ var _storage2 = _interopRequireDefault(require("../../../model/storage"));
10
+ var _usePrehooksRef = _interopRequireDefault(require("../use-prehooks-ref"));
11
+ var _useStateManager2 = _interopRequireDefault(require("../use-state-manager"));
12
+ var _setState2 = _interopRequireDefault(require("../../set-state"));
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
14
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
15
+ 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."); }
16
+ 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); }
17
+ 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; }
18
+ 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; } }
19
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
20
+ var deps = {
21
+ setState: _setState2["default"],
22
+ uuid: _uuid.v4
23
+ };
24
+ exports.deps = deps;
25
+ /**
26
  * @param {Prehooks<T>} prehooks
1
27
  * @param {T} value
2
28
  * @param {IStorage<T>} [storage] Closed to modification post-initialization
3
29
  * @template {State} T
4
30
  */
31
+ var useStore = function useStore(prehooks, value, storage) {
32
+ var mounted = (0, _react.useRef)(false);
33
+ var prehooksRef = (0, _usePrehooksRef["default"])(prehooks);
34
+ /** @type {MutableRefObject<string>} */
35
+ var storageKey = (0, _react.useRef)();
36
+ var _useStateManager = (0, _useStateManager2["default"])(value),
37
+ select = _useStateManager.select,
38
+ state = _useStateManager.state,
39
+ stateWatch = _useStateManager.stateWatch,
40
+ unlink = _useStateManager.unlink;
41
+ /** @type {[Set<Listener<T>>, Function]} */
42
+ var _useState = (0, _react.useState)(function () {
43
+ return new Set();
44
+ }),
45
+ _useState2 = _slicedToArray(_useState, 1),
46
+ listeners = _useState2[0];
47
+ /** @type {[IStorage<T>, Function]} */
48
+ var _useState3 = (0, _react.useState)(function () {
49
+ var isKeyRequired = true;
50
+ var _storage = storage;
51
+ if (!storage) {
52
+ _storage = new _storage2["default"]();
53
+ isKeyRequired = _storage.isKeyRequired;
54
+ }
55
+ storageKey.current = isKeyRequired ? "".concat(deps.uuid(), ":").concat(Date.now(), ":").concat(Math.random()) : null;
56
+ return _storage;
57
+ }),
58
+ _useState4 = _slicedToArray(_useState3, 1),
59
+ _storage = _useState4[0];
60
+ /** @type {Listener<T>} */
61
+ var onChange = function onChange(state) {
62
+ return listeners.forEach(function (listener) {
63
+ return listener(state);
64
+ });
65
+ };
66
+ /** @type {StoreInternal<T>["resetState"]} */
67
+ var resetState = (0, _react.useCallback)(function () {
68
+ var original = _storage.getItem(storageKey.current);
69
+ (!('resetState' in prehooksRef.current) || prehooksRef.current.resetState({
70
+ current: (0, _lodash["default"])(state),
71
+ original: original
72
+ })) && deps.setState(state, original, onChange);
73
+ }, []);
74
+ /** @type {StoreInternal<T>["setState"]} */
75
+ var setState = (0, _react.useCallback)(function (changes) {
76
+ changes = (0, _lodash["default"])(changes);
77
+ (!('setState' in prehooksRef.current) || prehooksRef.current.setState(changes)) && deps.setState(state, changes, onChange);
78
+ }, []);
79
+ /** @type {StoreInternal<T>["subscribe"]} */
80
+ var subscribe = (0, _react.useCallback)(function (listener) {
81
+ listeners.add(listener);
82
+ return function () {
83
+ return listeners["delete"](listener);
84
+ };
85
+ }, []);
86
+ (0, _react.useEffect)(function () {
87
+ var sKey = storageKey.current;
88
+ _storage.setItem(sKey, value);
89
+ return function () {
90
+ return _storage.removeItem(sKey);
91
+ };
92
+ }, []);
93
+ (0, _react.useEffect)(function () {
94
+ if (!mounted.current) {
95
+ mounted.current = true;
96
+ return;
97
+ }
98
+ setState((0, _lodash["default"])(value));
99
+ }, [value]);
100
+ (0, _react.useEffect)(function () {
101
+ if (!listeners.size) {
102
+ listeners.add(stateWatch);
103
+ } else {
104
+ var newList = Array.from(listeners);
105
+ newList.unshift(stateWatch);
106
+ listeners.clear();
107
+ newList.forEach(function (l) {
108
+ listeners.add(l);
109
+ });
110
+ }
111
+ return function () {
112
+ return listeners["delete"](stateWatch);
113
+ };
114
+ }, [stateWatch]);
115
+ return (0, _react.useState)(function () {
116
+ return {
117
+ getState: select,
118
+ resetState: resetState,
119
+ setState: setState,
120
+ subscribe: subscribe,
121
+ unlinkCache: unlink
122
+ };
123
+ })[0];
124
+ };
125
+ var _default = useStore;
126
+ exports["default"] = _default;
@@ -0,0 +1 @@
1
+ export class UsageError extends Error {
2
  Provider: ObservableProvider<S>;
1
3
  children?: ReactNode;
2
4
  prehooks?: Prehooks<T>;
3
5
  storage?: IStorage<T>;
4
6
  value: PartialState<T>;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports.useContext = exports.createContext = exports.UsageError = void 0;
6
+ var _react = _interopRequireWildcard(require("react"));
7
+ var _lodash = _interopRequireDefault(require("lodash.isequal"));
8
+ var _lodash2 = _interopRequireDefault(require("lodash.omit"));
9
+ var _uuid = require("uuid");
10
+ var _useRenderKeysManager = _interopRequireDefault(require("./hooks/use-render-keys-manager"));
11
+ var _useStore = _interopRequireDefault(require("./hooks/use-store"));
12
+ var _excluded = ["getState", "subscribe", "unlinkCache"];
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
14
+ 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); }
15
+ 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; }
16
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
17
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
18
+ 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; }
19
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
20
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
21
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
22
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
23
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
24
+ 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."); }
25
+ 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); }
26
+ 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; }
27
+ 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; } }
28
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
29
+ 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; }
30
+ 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; }
31
+ 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); }
32
+ 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); } }
33
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
34
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
35
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
36
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37
+ 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); }
38
+ 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); }; }
39
+ 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); }
40
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
41
+ function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
42
+ function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
43
+ 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; } }
44
+ function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
45
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
46
+ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
47
+ var UsageError = function (_Error) {
48
+ _inherits(UsageError, _Error);
49
+ var _super = _createSuper(UsageError);
50
+ function UsageError() {
51
+ _classCallCheck(this, UsageError);
52
+ return _super.apply(this, arguments);
53
+ }
54
+ return _createClass(UsageError);
55
+ }( _wrapNativeSuper(Error));
56
+ exports.UsageError = UsageError;
57
+ /**
58
  * @readonly
1
59
  * @type {Prehooks<T>}
2
60
  * @template {State} T
3
61
  */
62
+ var defaultPrehooks = Object.freeze({});
63
+ /** @type {NonReactUsageReport} */
64
+ var reportNonReactUsage = function reportNonReactUsage() {
65
+ throw new UsageError('Detected usage outside of this context\'s Provider component tree. Please apply the exported Provider component');
66
+ };
67
+ /** @type {FC<{child: ReactNode}>} */
68
+ var ChildMemo = function () {
69
+ var useNodeMemo = function useNodeMemo(node) {
70
+ var nodeRef = (0, _react.useRef)(node);
71
+ if (!(0, _lodash["default"])((0, _lodash2["default"])(nodeRef.current, '_owner'), (0, _lodash2["default"])(node, '_owner'))) {
72
+ nodeRef.current = node;
73
+ }
74
+ return nodeRef.current;
75
+ };
76
+ var ChildMemo = (0, _react.memo)(function (_ref) {
77
+ var child = _ref.child;
78
+ return child;
79
+ });
80
+ ChildMemo.displayName = 'ObservableContext.Provider.Internal.Guardian.ChildMemo';
81
+ var Guardian = function Guardian(_ref2) {
82
+ var child = _ref2.child;
83
+ return _react["default"].createElement(ChildMemo, {
84
+ child: useNodeMemo(child)
85
+ });
86
+ };
87
+ Guardian.displayName = 'ObservableContext.Provider.Internal.Guardian';
88
+ return Guardian;
89
+ }();
90
+ /** @type {(children: ReactNode) => ReactNode} */
91
+ var memoizeImmediateChildTree = function memoizeImmediateChildTree(children) {
92
+ return _react.Children.map(children, function (child) {
93
+ var _child$props;
94
+ if (_typeof(child.type) === 'object' && 'compare' in child.type) {
95
+ return child;
96
+ }
97
+ if ((_child$props = child.props) !== null && _child$props !== void 0 && _child$props.children) {
98
+ child = (0, _react.cloneElement)(child, (0, _lodash2["default"])(child.props, 'children'), memoizeImmediateChildTree(child.props.children));
99
+ }
100
+ return _react["default"].createElement(ChildMemo, {
101
+ child: child
102
+ });
103
+ });
104
+ };
105
+ /** @param {Provider<IStore>} Provider */
106
+ var makeObservable = function makeObservable(Provider) {
107
+ /**
4
108
  * @type {ObservableProvider<T>}
5
109
  * @template {State} T
6
110
  */
111
+ var Observable = function Observable(_ref3) {
112
+ var _ref3$children = _ref3.children,
113
+ children = _ref3$children === void 0 ? null : _ref3$children,
114
+ _ref3$prehooks = _ref3.prehooks,
115
+ prehooks = _ref3$prehooks === void 0 ? defaultPrehooks : _ref3$prehooks,
116
+ _ref3$storage = _ref3.storage,
117
+ storage = _ref3$storage === void 0 ? null : _ref3$storage,
118
+ value = _ref3.value;
119
+ return _react["default"].createElement(Provider, {
120
+ value: (0, _useStore["default"])(prehooks, value, storage)
121
+ }, memoizeImmediateChildTree(children));
122
+ };
123
+ Observable.displayName = 'ObservableContext.Provider';
124
+ return Observable;
125
+ };
126
+ /**
7
127
  * @returns {ObservableContext<T>} Refers to the IObservableContext<T> type of the ObservableContext<T>
8
128
  * @template {State} T
9
129
  * @see {ObservableContext<T>}
10
130
  */
131
+ var createContext = function createContext() {
132
+ var Context = (0, _react.createContext)({
133
+ getState: reportNonReactUsage,
134
+ resetState: reportNonReactUsage,
135
+ setState: reportNonReactUsage,
136
+ subscribe: reportNonReactUsage
137
+ });
138
+ var provider = Context.Provider;
139
+ Context.Provider = makeObservable(provider);
140
+ return Context;
141
+ };
142
+ exports.createContext = createContext;
143
+ /**
11
144
  * Actively monitors the store and triggers component re-render if any of the watched keys in the state objects changes
12
145
  *
13
146
  * @param {ObservableContext<T>} context Refers to the PublicObservableContext<T> type of the ObservableContext<T>
14
147
  * @param {Array<string|keyof T>} [renderKeys = []] a list of paths to state object properties used by this component: see examples below. May use `['@@STATE']` to indicate a desire to obtain the entire state object. 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.
15
148
  * @returns {Store<T>}
16
149
  * @template {State} T
17
150
  * @see {ObservableContext<T>}
18
151
  * @example
19
152
  * a valid renderKey follows the `lodash` object property path convention.
20
153
  * for a state = { a: 1, b: 2, c: 3, d: { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] } }
21
154
  * Any of the following is a valid renderKey
22
155
  * 'a' => 1
23
156
  * 'd' => { e: 5, f: [6, { x: 7, y: 8, z: 9 } ] }
24
157
  * 'd.e' => 5
25
158
  * 'd.e.f => [6, { x: 7, y: 8, z: 9 } ]
26
159
  * 'd.e.f[0]' or 'd.e.f.0' => 6
27
160
  * 'd.e.f[1]' or 'd.e.f.1' => { x: 7, y: 8, z: 9 }
28
161
  * 'd.e.f[1].x' or 'd.e.f.1.x' => 7
29
162
  * '@@STATE' => state
30
163
  */
164
+ var useContext = function useContext(context) {
165
+ var renderKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
166
+ /** @type {StoreInternal<T>} */
167
+ var _useContext2 = (0, _react.useContext)(context),
168
+ _getState = _useContext2.getState,
169
+ subscribe = _useContext2.subscribe,
170
+ unlinkCache = _useContext2.unlinkCache,
171
+ store = _objectWithoutProperties(_useContext2, _excluded);
172
+ var _useState = (0, _react.useState)(_uuid.v4),
173
+ _useState2 = _slicedToArray(_useState, 1),
174
+ clientId = _useState2[0];
175
+ var _renderKeys = (0, _useRenderKeysManager["default"])(renderKeys);
176
+ /** @returns {Readonly<PartialState<T>>} */
177
+ var getState = function getState() {
178
+ return _getState.apply(void 0, [clientId].concat(_toConsumableArray(_renderKeys)));
179
+ };
180
+ var _useState3 = (0, _react.useState)(getState),
181
+ _useState4 = _slicedToArray(_useState3, 2),
182
+ data = _useState4[0],
183
+ setData = _useState4[1];
184
+ (0, _react.useMemo)(function () {
185
+ return setData(getState());
186
+ }, [_renderKeys]);
187
+ (0, _react.useEffect)(function () {
188
+ return subscribe(function () {
189
+ return setData(getState());
190
+ });
191
+ }, [_renderKeys]);
192
+ (0, _react.useEffect)(function () {
193
+ return function () {
194
+ return unlinkCache(clientId);
195
+ };
196
+ }, []);
197
+ return (0, _react.useMemo)(function () {
198
+ return _objectSpread({
199
+ data: data
200
+ }, store);
201
+ }, [data]);
202
+ };
203
+ exports.useContext = useContext;
@@ -0,0 +1 @@
1
+ export default setState;
2
  [rootKey: number]: {
1
3
  [x: string]: any;
2
4
  };
3
5
  [x: string]: any;
4
6
  [rootKey: string]: {
5
7
  [x: string]: any;
6
8
  };
7
9
  [rootKey: symbol]: {
8
10
  [x: string]: any;
9
11
  };
10
12
  [rootKey: number]: T;
11
13
  [rootKey: string]: T;
12
14
  [rootKey: symbol]: T;
13
15
  hasChanges: boolean;
14
16
  * @param {T} state
15
17
  * @param {PartialState<T>} newState
16
18
  * @param {Listener<T>} [onStateChange]
17
19
  * @template {State} T
18
20
  */
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports["default"] = void 0;
6
+ var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
7
+ var _lodash2 = _interopRequireDefault(require("lodash.isequal"));
8
+ var _lodash3 = _interopRequireDefault(require("lodash.isplainobject"));
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
10
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
11
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
12
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
13
+ 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); }
14
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
15
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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
+ var isIndexBasedObj = function isIndexBasedObj(obj) {
19
+ return Object.keys(obj).every(function (k) {
20
+ var i = +k;
21
+ return Number.isInteger(i) && i > -1;
22
+ });
23
+ };
24
+ /**
25
  * Mutates its arguments
1
26
  *
2
27
  * @param {HasArrayRoot<K>|HasObjectRoot<K>} state
3
28
  * @param {HasArrayRoot<K>|HasObjectRoot<K>} newState
4
29
  * @param {K} stateKey
5
30
  * @param {Stats} stats
6
31
  * @template {KeyTypes} K
7
32
  */
33
+ function setAtomic(state, newState, stateKey, stats) {
34
+ if ((0, _lodash2["default"])(state[stateKey], newState[stateKey])) {
35
+ return;
36
+ }
37
+ var isPlainObjectNewState = (0, _lodash3["default"])(newState[stateKey]);
38
+ var isArrayNewState = Array.isArray(newState[stateKey]);
39
+ if (Array.isArray(state[stateKey])) {
40
+ if (isArrayNewState) {
41
+ return setArray(state, newState, stateKey, stats);
42
+ }
43
+ if (isPlainObjectNewState && isIndexBasedObj(newState[stateKey])) {
44
+ return setArrayIndex(state, newState, stateKey, stats);
45
+ }
46
+ }
47
+ if (isPlainObjectNewState && (0, _lodash3["default"])(state[stateKey])) {
48
+ return setPlainObject(state, newState, stateKey, stats);
49
+ }
50
+ stats.hasChanges = true;
51
+ state[stateKey] = isArrayNewState || isPlainObjectNewState ? (0, _lodash["default"])(newState[stateKey]) : newState[stateKey];
52
+ }
53
+ ;
54
+ /**
8
55
  * Mutates its arguments
9
56
  *
10
57
  * @param {HasArrayRoot<K>} state
11
58
  * @param {HasArrayRoot<K>} newState
12
59
  * @param {K} rootKey
13
60
  * @param {Stats} stats
14
61
  * @template {KeyTypes} K
15
62
  */
63
+ function setArray(state, newState, rootKey, stats) {
64
+ var nsLength = newState[rootKey].length;
65
+ if (state[rootKey].length !== nsLength) {
66
+ state[rootKey].length = nsLength;
67
+ stats.hasChanges = true;
68
+ }
69
+ for (var i = 0; i < nsLength; i++) {
70
+ setAtomic(state[rootKey], newState[rootKey], i, stats);
71
+ }
72
+ }
73
+ ;
74
+ /**
16
75
  * Mutates its arguments
17
76
  *
18
77
  * @param {HasArrayRoot<K>} state
19
78
  * @param {HasObjectRoot<K>} newState
20
79
  * @param {K} rootKey
21
80
  * @param {Stats} stats
22
81
  * @template {KeyTypes} K
23
82
  */
83
+ function setArrayIndex(state, newState, rootKey, stats) {
84
+ var incomingIndexes = Object.keys(newState[rootKey]).map(function (i) {
85
+ return +i;
86
+ });
87
+ var maxIncomingIndex = Math.max.apply(Math, _toConsumableArray(incomingIndexes));
88
+ if (maxIncomingIndex >= state[rootKey].length) {
89
+ state[rootKey].length = maxIncomingIndex + 1;
90
+ stats.hasChanges = true;
91
+ }
92
+ var _iterator = _createForOfIteratorHelper(incomingIndexes),
93
+ _step;
94
+ try {
95
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
96
+ var i = _step.value;
97
+ setAtomic(state[rootKey], newState[rootKey], i, stats);
98
+ }
99
+ } catch (err) {
100
+ _iterator.e(err);
101
+ } finally {
102
+ _iterator.f();
103
+ }
104
+ }
105
+ ;
106
+ /**
24
107
  * Mutates its arguments
25
108
  *
26
109
  * @param {HasObjectRoot<K>} state
27
110
  * @param {HasObjectRoot<K>} newState
28
111
  * @param {K} rootKey
29
112
  * @param {Stats} stats
30
113
  * @template {KeyTypes} K
31
114
  */
115
+ function setPlainObject(state, newState, rootKey, stats) {
116
+ set(state[rootKey], newState[rootKey], stats);
117
+ }
118
+ ;
119
+ /**
32
120
  * Mutates its arguments
33
121
  *
34
122
  * @param {HasObjectRoot} state
35
123
  * @param {HasObjectRoot} newState
36
124
  * @param {Stats} stats
37
125
  */
126
+ function set(state, newState, stats) {
127
+ for (var k in newState) {
128
+ setAtomic(state, newState, k, stats);
129
+ }
130
+ }
131
+ ;
132
+ /**
38
133
  * @param {T} state
39
134
  * @param {PartialState<T>} newState
40
135
  * @param {Listener<T>} [onStateChange]
41
136
  * @template {State} T
42
137
  */
138
+ function setState(state, newState, onStateChange) {
139
+ var stats = {
140
+ hasChanges: false
141
+ };
142
+ set(state, newState, stats);
143
+ stats.hasChanges && (onStateChange === null || onStateChange === void 0 ? void 0 : onStateChange(state));
144
+ }
145
+ ;
146
+ var _default = setState;
147
+ exports["default"] = _default;
@@ -0,0 +1 @@
1
+ export default AccessorCache;
2
  /** @param {T} origin State object reference from which slices stored in this cache are to be curated */
1
3
  constructor(origin: T);
2
4
  /**
3
5
  * Gets state slice from the cache matching the `propertyPaths`.\
4
6
  * If not found, creates a new entry for the client from source, and returns it.
5
7
  *
6
8
  * @param {string} clientId
7
9
  * @param {...string} propertyPaths
8
10
  * @return {Readonly<PartialState<T>>}
9
11
  */
10
12
  get(clientId: string, ...propertyPaths: string[]): Readonly<PartialState<T>>;
11
13
  /**
12
14
  * Unlinks a consumer from the cache: performing synchronized state cleanup
13
15
  *
14
16
  * @param {string} clientId
15
17
  */
16
18
  unlinkClient(clientId: string): void;
17
19
  /** Observes the origin state bearing ObservableContext store for state changes to update accessors. */
18
20
  watchSource(): void;
19
21
  #private;