@stated-library/base
Version:
1,034 lines (860 loc) • 30.2 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global['@stated-library/base'] = {}));
}(this, function (exports) { 'use strict';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
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, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
var isObject_1 = isObject;
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = _freeGlobal || freeSelf || Function('return this')();
var _root = root;
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function () {
return _root.Date.now();
};
var now_1 = now;
/** Built-in value references. */
var Symbol$1 = _root.Symbol;
var _Symbol = Symbol$1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
var _getRawTag = getRawTag;
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$1.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString$1.call(value);
}
var _objectToString = objectToString;
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
}
var _baseGetTag = baseGetTag;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
var isObjectLike_1 = isObjectLike;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag;
}
var isSymbol_1 = isSymbol;
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol_1(value)) {
return NAN;
}
if (isObject_1(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject_1(other) ? other + '' : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_1 = toNumber;
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber_1(wait) || 0;
if (isObject_1(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber_1(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time; // Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait); // Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = now_1();
if (shouldInvoke(time)) {
return trailingEdge(time);
} // Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now_1());
}
function debounced() {
var time = now_1(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
var debounce_1 = debounce;
/** Error message constants. */
var FUNC_ERROR_TEXT$1 = 'Expected a function';
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT$1);
}
if (isObject_1(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce_1(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
var throttle_1 = throttle;
function _defineProperty$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/* getValue: when an observable is fed by other observables, it might
unsubscribe from those observables if it doesn't have any subscriptions
itself. in that case, it won't be updationg "value", so value could be
invalid if there are no subscriptions. getValue supports this case by
allowing the observable to temporarily subscribe to the feeding observables
in order to get the proper value.
*/
function createObservable(initialValue, opts) {
var observers = [];
var value = initialValue;
var _Object$assign = Object.assign({}, opts),
onSubscribe = _Object$assign.onSubscribe,
onUnsubscribe = _Object$assign.onUnsubscribe,
getValue = _Object$assign.getValue;
return _defineProperty$1({
get value() {
return getValue ? getValue() : value;
},
subscribe: function subscribe(observer) {
if (observers.length === 0 && onSubscribe) {
onSubscribe();
}
if (typeof observer === 'function') {
observer = {
next: observer
};
}
observers.push(observer); // behave like a BehaviorSubject and emit the current value
// upon subscription
// most reactive operations will need this behavior
// in cases (like React) where the initial value is retrieved before
// subscribing, the subscriber will get the same value upon subscribing,
// assuming it hasn't changed, so this behavior should result in minimal
// overhead
observer.next(this.value);
return {
unsubscribe: function unsubscribe() {
observers = observers.filter(function (l) {
return l !== observer;
});
if (observers.length === 0 && onUnsubscribe) {
onUnsubscribe();
}
}
};
},
next: function next(nextValue) {
value = nextValue;
observers.map(function (obs) {
return obs.next(value);
});
}
}, Symbol && Symbol.observable || '@@observable', function () {
return this;
});
}
var hasOwn = Object.prototype.hasOwnProperty;
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function shallowEqual(objA, objB) {
if (is(objA, objB)) return true;
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
function createMultiConnector(opts) {
var onState = opts.onState,
onStateEvent = opts.onStateEvent,
onConnectLib = opts.onConnectLib,
onDisconnectLib = opts.onDisconnectLib;
var stateSubs = {};
var stateEventSubs = {};
return {
connectedLibs: {},
connect: function connect(lib, key) {
var _this = this;
if (this.connectedLibs[key]) {
throw new Error("A library is already connected with key: ".concat(key));
}
var partialSub = {
disconnect: function disconnect() {
onDisconnectLib && onDisconnectLib(key, lib);
delete _this.connectedLibs[key];
stateSubs[key].unsubscribe();
delete stateSubs[key];
}
};
var sub = onConnectLib ? onConnectLib(key, lib, partialSub) : partialSub;
if (onState) {
stateSubs[key] = lib.state$.subscribe(function (state) {
return onState(state, key, lib);
});
}
if (onStateEvent) {
stateEventSubs[key] = lib.stateEvent$.subscribe(function (stateEvent) {
return onStateEvent(stateEvent, key, lib);
});
}
this.connectedLibs[key] = lib;
return sub;
},
disconnect: function disconnect() {
var _this2 = this;
Object.keys(this.connectedLibs).map(function (key) {
if (stateSubs[key]) {
stateSubs[key].unsubscribe();
delete stateSubs[key];
}
if (stateEventSubs[key]) {
stateEventSubs[key].unsubscribe();
delete stateEventSubs[key];
}
delete _this2.connectedLibs[key];
});
}
};
}
var DEVTOOLS_SET_EVENT = '**__DEVTOOLS__**';
function createDevToolsConnector() {
var devTools;
var combinedState = {};
var multi; // https://extension.remotedev.io/docs/API/Methods.html
// @ts-ignore
if (window.__REDUX_DEVTOOLS_EXTENSION__) {
// @ts-ignore
devTools = window.__REDUX_DEVTOOLS_EXTENSION__.connect({
name: 'StatedLibraries'
});
devTools.subscribe(function (message) {
if (message.type === 'DISPATCH' && message.state) {
console.log('DevTools requested to change the state to', message.state);
var libStates = JSON.parse(message.state);
Object.keys(libStates).forEach(function (lib) {
return multi.connectedLibs[lib].resetState(libStates[lib], DEVTOOLS_SET_EVENT);
});
}
});
devTools.init(combinedState);
}
multi = createMultiConnector({
onStateEvent: function onStateEvent(stateEvent, key) {
var rawState = stateEvent.rawState,
event = stateEvent.event;
combinedState[key] = rawState;
if (event === DEVTOOLS_SET_EVENT) {
return;
}
devTools && devTools.send("".concat(key, "::").concat(event), combinedState);
}
});
return multi;
}
var devTools = createDevToolsConnector();
function _objectSpread$1(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty$1(target, key, source[key]);
});
}
return target;
}
function getStateFromLocalStorage(name) {
try {
var data = localStorage.getItem(name);
return data ? JSON.parse(data) : undefined;
} catch (_unused) {
return undefined;
}
}
function createLocalStorageConnector() {
var writeFns = {};
var multi = createMultiConnector({
onConnectLib: function onConnectLib(key, lib, sub) {
var initial = getStateFromLocalStorage(key);
if (initial != null) {
lib.resetState(initial, 'RESET_FROM_LOCAL_STATE');
}
var writeState = function writeState(state) {
localStorage.setItem(key, JSON.stringify(state));
};
writeFns[key] = throttle_1(writeState, 300, {
leading: true,
trailing: true
});
return _objectSpread$1({}, sub, {
clear: function clear() {
return localStorage.removeItem(key);
}
});
},
onStateEvent: function onStateEvent(stateEvent, key) {
var rawState = stateEvent.rawState;
writeFns[key](rawState);
}
});
return _objectSpread$1({}, multi, {
clear: function clear() {
Object.keys(this.connectedLibs).map(function (key) {
localStorage.removeItem(key);
});
}
});
}
var locStorage = createLocalStorageConnector();
var identity = function identity(x) {
return x;
};
function makeStateEvent(rawState, event, meta, opts) {
var deriveState = opts && opts.deriveState || identity;
var stateData = {
rawState: rawState,
event: event,
state: deriveState(rawState),
meta: meta
};
{
Object.freeze(stateData);
Object.freeze(stateData.state);
Object.freeze(stateData.rawState);
}
return stateData;
}
function bindMethodsFromProto(obj) {
var proto = Object.getPrototypeOf(obj);
var descriptors = Object.getOwnPropertyDescriptors(proto);
for (var _i = 0, _Object$keys = Object.keys(descriptors); _i < _Object$keys.length; _i++) {
var key = _Object$keys[_i];
if (key === 'constructor') {
continue;
}
if (typeof descriptors[key].value === 'function') {
obj[key] = obj[key].bind(obj);
}
}
}
var StatedLibBase =
/*#__PURE__*/
function () {
function StatedLibBase(initialState, opts) {
_classCallCheck(this, StatedLibBase);
this.opts = void 0;
this.stateEvent$ = void 0;
this.state$ = void 0;
this.opts = Object.assign({}, opts);
var createObs = this.opts.createObs || createObservable;
var initialEvent = makeStateEvent(initialState, 'INIT', undefined, opts);
this.stateEvent$ = createObs(initialEvent);
this.state$ = createObs(initialEvent.state);
}
_createClass(StatedLibBase, [{
key: "setState",
value: function setState(rawState, event, meta) {
var stateData = shallowEqual(rawState, this.stateEvent$.value.rawState) ? _objectSpread({}, this.stateEvent$.value, {
event: event,
meta: meta
}) : makeStateEvent(rawState, event, meta, this.opts);
if (!Object.is(stateData.state, this.state$.value)) {
this.state$.next(stateData.state);
}
this.stateEvent$.next(stateData);
}
}, {
key: "updateState",
value: function updateState(updatesOrGetUpdates, event, meta) {
var updates = typeof updatesOrGetUpdates === 'function' ? updatesOrGetUpdates(this.state) : updatesOrGetUpdates;
var rawState = Object.assign({}, this.stateEvent$.value.rawState, updates);
this.setState(rawState, event, meta);
}
}, {
key: "resetState",
value: function resetState(rawState, event, meta) {
this.setState(rawState, event, meta);
}
}, {
key: "state",
get: function get() {
return this.stateEvent$.value.state;
}
}], [{
key: "bindMethods",
value: function bindMethods(obj) {
bindMethodsFromProto(obj);
}
}]);
return StatedLibBase;
}();
function createStatedLib(initialState, methodsOrGetMethods, opts) {
var base = new StatedLibBase(initialState, opts);
bindMethodsFromProto(base);
var methods = typeof methodsOrGetMethods === 'function' ? methodsOrGetMethods(base) : methodsOrGetMethods;
var obj = {
get state() {
return this.stateEvent$.value.state;
}
};
Object.assign(obj, base);
Object.keys(methods).forEach(function (method) {
if (typeof methods[method] === 'function') {
obj[method] = methods[method].bind(obj);
}
}); // @ts-ignore
return obj;
}
exports.default = StatedLibBase;
exports.bindMethodsFromProto = bindMethodsFromProto;
exports.StatedLibBase = StatedLibBase;
exports.createStatedLib = createStatedLib;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=index.umd.development.js.map