UNPKG

mobx

Version:

Simple, scalable state management.

1,385 lines (1,169 loc) 202 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.mobx = {})); }(this, (function (exports) { 'use strict'; var niceErrors = { 0: "Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'", 1: function _(annotationType, key) { return "Cannot apply '" + annotationType + "' to '" + key.toString() + "': Field not found."; }, 5: "'keys()' can only be used on observable objects, arrays, sets and maps", 6: "'values()' can only be used on observable objects, arrays, sets and maps", 7: "'entries()' can only be used on observable objects, arrays and maps", 8: "'set()' can only be used on observable objects, arrays and maps", 9: "'remove()' can only be used on observable objects, arrays and maps", 10: "'has()' can only be used on observable objects, arrays and maps", 11: "'get()' can only be used on observable objects, arrays and maps", 12: "Invalid annotation", 13: "Dynamic observable objects cannot be frozen", 14: "Intercept handlers should return nothing or a change object", 15: "Observable arrays cannot be frozen", 16: "Modification exception: the internal structure of an observable array was changed.", 17: function _(index, length) { return "[mobx.array] Index out of bounds, " + index + " is larger than " + length; }, 18: "mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js", 19: function _(other) { return "Cannot initialize from classes that inherit from Map: " + other.constructor.name; }, 20: function _(other) { return "Cannot initialize map from " + other; }, 21: function _(dataStructure) { return "Cannot convert to map from '" + dataStructure + "'"; }, 22: "mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js", 23: "It is not possible to get index atoms from arrays", 24: function _(thing) { return "Cannot obtain administration from " + thing; }, 25: function _(property, name) { return "the entry '" + property + "' does not exist in the observable map '" + name + "'"; }, 26: "please specify a property", 27: function _(property, name) { return "no observable property '" + property.toString() + "' found on the observable object '" + name + "'"; }, 28: function _(thing) { return "Cannot obtain atom from " + thing; }, 29: "Expecting some object", 30: "invalid action stack. did you forget to finish an action?", 31: "missing option for computed: get", 32: function _(name, derivation) { return "Cycle detected in computation " + name + ": " + derivation; }, 33: function _(name) { return "The setter of computed value '" + name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"; }, 34: function _(name) { return "[ComputedValue '" + name + "'] It is not possible to assign a new value to a computed value."; }, 35: "There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`", 36: "isolateGlobalState should be called before MobX is running any reactions", 37: function _(method) { return "[mobx] `observableArray." + method + "()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()." + method + "()` instead"; } }; var errors = niceErrors ; function die(error) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } { var e = typeof error === "string" ? error : errors[error]; if (typeof e === "function") e = e.apply(null, args); throw new Error("[MobX] " + e); } } var mockGlobal = {}; function getGlobal() { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } if (typeof self !== "undefined") { return self; } return mockGlobal; } var assign = Object.assign; var getDescriptor = Object.getOwnPropertyDescriptor; var defineProperty = Object.defineProperty; var objectPrototype = Object.prototype; var EMPTY_ARRAY = []; Object.freeze(EMPTY_ARRAY); var EMPTY_OBJECT = {}; Object.freeze(EMPTY_OBJECT); var hasProxy = typeof Proxy !== "undefined"; var plainObjectString = /*#__PURE__*/Object.toString(); function assertProxies() { if (!hasProxy) { die( "`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`" ); } } function warnAboutProxyRequirement(msg) { if ( globalState.verifyProxies) { die("MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to " + msg); } } function getNextId() { return ++globalState.mobxGuid; } /** * Makes sure that the provided function is invoked at most once. */ function once(func) { var invoked = false; return function () { if (invoked) return; invoked = true; return func.apply(this, arguments); }; } var noop = function noop() {}; function isFunction(fn) { return typeof fn === "function"; } function isStringish(value) { var t = typeof value; switch (t) { case "string": case "symbol": case "number": return true; } return false; } function isObject(value) { return value !== null && typeof value === "object"; } function isPlainObject(value) { var _proto$constructor; if (!isObject(value)) return false; var proto = Object.getPrototypeOf(value); if (proto == null) return true; return ((_proto$constructor = proto.constructor) == null ? void 0 : _proto$constructor.toString()) === plainObjectString; } // https://stackoverflow.com/a/37865170 function isGenerator(obj) { var constructor = obj == null ? void 0 : obj.constructor; if (!constructor) return false; if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) return true; return false; } function addHiddenProp(object, propName, value) { defineProperty(object, propName, { enumerable: false, writable: true, configurable: true, value: value }); } function addHiddenFinalProp(object, propName, value) { defineProperty(object, propName, { enumerable: false, writable: false, configurable: true, value: value }); } function createInstanceofPredicate(name, theClass) { var propName = "isMobX" + name; theClass.prototype[propName] = true; return function (x) { return isObject(x) && x[propName] === true; }; } function isES6Map(thing) { return thing instanceof Map; } function isES6Set(thing) { return thing instanceof Set; } var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined"; /** * Returns the following: own enumerable keys and symbols. */ function getPlainObjectKeys(object) { var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway... if (!hasGetOwnPropertySymbols) return keys; var symbols = Object.getOwnPropertySymbols(object); if (!symbols.length) return keys; return [].concat(keys, symbols.filter(function (s) { return objectPrototype.propertyIsEnumerable.call(object, s); })); } // From Immer utils // Returns all own keys, including non-enumerable and symbolic var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) { return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj)); } : /* istanbul ignore next */ Object.getOwnPropertyNames; function stringifyKey(key) { if (typeof key === "string") return key; if (typeof key === "symbol") return key.toString(); return new String(key).toString(); } function toPrimitive(value) { return value === null ? null : typeof value === "object" ? "" + value : value; } function hasProp(target, prop) { return objectPrototype.hasOwnProperty.call(target, prop); } // From Immer utils var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) { // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274 var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up ownKeys(target).forEach(function (key) { res[key] = getDescriptor(target, key); }); return res; }; 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; } function _extends() { _extends = Object.assign || 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); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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); } 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; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); } var storedAnnotationsSymbol = /*#__PURE__*/Symbol("mobx-stored-annotations"); /** * Creates a function that acts as * - decorator * - annotation object */ function createDecoratorAnnotation(annotation) { function decorator(target, property) { storeAnnotation(target, property, annotation); } return Object.assign(decorator, annotation); } /** * Stores annotation to prototype, * so it can be inspected later by `makeObservable` called from constructor */ function storeAnnotation(prototype, key, annotation) { if (!hasProp(prototype, storedAnnotationsSymbol)) { addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol])); } // @override must override something if ( isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) { var fieldName = prototype.constructor.name + ".prototype." + key.toString(); die("'" + fieldName + "' is decorated with 'override', " + "but no such decorated member was found on prototype."); } // Cannot re-decorate assertNotDecorated(prototype, annotation, key); // Ignore override if (!isOverride(annotation)) { prototype[storedAnnotationsSymbol][key] = annotation; } } function assertNotDecorated(prototype, annotation, key) { if ( !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) { var fieldName = prototype.constructor.name + ".prototype." + key.toString(); var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_; var requestedAnnotationType = annotation.annotationType_; die("Cannot apply '@" + requestedAnnotationType + "' to '" + fieldName + "':" + ("\nThe field is already decorated with '@" + currentAnnotationType + "'.") + "\nRe-decorating fields is not allowed." + "\nUse '@override' decorator for methods overriden by subclass."); } } /** * Collects annotations from prototypes and stores them on target (instance) */ function collectStoredAnnotations(target) { if (!hasProp(target, storedAnnotationsSymbol)) { if ( !target[storedAnnotationsSymbol]) { die("No annotations were passed to makeObservable, but no decorated members have been found either"); } // We need a copy as we will remove annotation from the list once it's applied. addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol])); } return target[storedAnnotationsSymbol]; } var $mobx = /*#__PURE__*/Symbol("mobx administration"); var Atom = /*#__PURE__*/function () { // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed /** * Create a new atom. For debugging purposes it is recommended to give it a name. * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management. */ function Atom(name_) { if (name_ === void 0) { name_ = "Atom@" + getNextId() ; } this.name_ = void 0; this.isPendingUnobservation_ = false; this.isBeingObserved_ = false; this.observers_ = new Set(); this.diffValue_ = 0; this.lastAccessedBy_ = 0; this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_; this.onBOL = void 0; this.onBUOL = void 0; this.name_ = name_; } // onBecomeObservedListeners var _proto = Atom.prototype; _proto.onBO = function onBO() { if (this.onBOL) { this.onBOL.forEach(function (listener) { return listener(); }); } }; _proto.onBUO = function onBUO() { if (this.onBUOL) { this.onBUOL.forEach(function (listener) { return listener(); }); } } /** * Invoke this method to notify mobx that your atom has been used somehow. * Returns true if there is currently a reactive context. */ ; _proto.reportObserved = function reportObserved$1() { return reportObserved(this); } /** * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate. */ ; _proto.reportChanged = function reportChanged() { startBatch(); propagateChanged(this); endBatch(); }; _proto.toString = function toString() { return this.name_; }; return Atom; }(); var isAtom = /*#__PURE__*/createInstanceofPredicate("Atom", Atom); function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { if (onBecomeObservedHandler === void 0) { onBecomeObservedHandler = noop; } if (onBecomeUnobservedHandler === void 0) { onBecomeUnobservedHandler = noop; } var atom = new Atom(name); // default `noop` listener will not initialize the hook Set if (onBecomeObservedHandler !== noop) { onBecomeObserved(atom, onBecomeObservedHandler); } if (onBecomeUnobservedHandler !== noop) { onBecomeUnobserved(atom, onBecomeUnobservedHandler); } return atom; } function identityComparer(a, b) { return a === b; } function structuralComparer(a, b) { return deepEqual(a, b); } function shallowComparer(a, b) { return deepEqual(a, b, 1); } function defaultComparer(a, b) { return Object.is(a, b); } var comparer = { identity: identityComparer, structural: structuralComparer, "default": defaultComparer, shallow: shallowComparer }; function deepEnhancer(v, _, name) { // it is an observable already, done if (isObservable(v)) return v; // something that can be converted and mutated? if (Array.isArray(v)) return observable.array(v, { name: name }); if (isPlainObject(v)) return observable.object(v, undefined, { name: name }); if (isES6Map(v)) return observable.map(v, { name: name }); if (isES6Set(v)) return observable.set(v, { name: name }); return v; } function shallowEnhancer(v, _, name) { if (v === undefined || v === null) return v; if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) return v; if (Array.isArray(v)) return observable.array(v, { name: name, deep: false }); if (isPlainObject(v)) return observable.object(v, undefined, { name: name, deep: false }); if (isES6Map(v)) return observable.map(v, { name: name, deep: false }); if (isES6Set(v)) return observable.set(v, { name: name, deep: false }); die("The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets"); } function referenceEnhancer(newValue) { // never turn into an observable return newValue; } function refStructEnhancer(v, oldValue) { if ( isObservable(v)) die("observable.struct should not be used with observable values"); if (deepEqual(v, oldValue)) return oldValue; return v; } var OVERRIDE = "override"; var override = /*#__PURE__*/createDecoratorAnnotation({ annotationType_: OVERRIDE, make_: make_, extend_: extend_ }); function isOverride(annotation) { return annotation.annotationType_ === OVERRIDE; } function make_(adm, key) { // Must not be plain object if ( adm.isPlainObject_) { die("Cannot apply '" + this.annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + this.annotationType_ + "' cannot be used on plain objects.")); } // Must override something if ( !hasProp(adm.appliedAnnotations_, key)) { die("'" + adm.name_ + "." + key.toString() + "' is annotated with '" + this.annotationType_ + "', " + "but no such annotated member was found on prototype."); } } function extend_(adm, key, descriptor, proxyTrap) { die("'" + this.annotationType_ + "' can only be used with 'makeObservable'"); } function createActionAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$1, extend_: extend_$1 }; } function make_$1(adm, key) { var _this$options_$bound, _this$options_, _adm$target_$storedAn; var annotated = false; var source = adm.target_; var bound = (_this$options_$bound = (_this$options_ = this.options_) == null ? void 0 : _this$options_.bound) != null ? _this$options_$bound : false; while (source && source !== objectPrototype) { var descriptor = getDescriptor(source, key); if (descriptor) { // Instance or bound // Keep first because the operation can be intercepted // and we don't want to end up with partially annotated proto chain if (source === adm.target_ || bound) { var actionDescriptor = createActionDescriptor(adm, this, key, descriptor); var definePropertyOutcome = adm.defineProperty_(key, actionDescriptor); if (!definePropertyOutcome) { // Intercepted return; } annotated = true; // Don't annotate protos if bound if (bound) { break; } } // Prototype if (source !== adm.target_) { if (isAction(descriptor.value)) { // A prototype could have been annotated already by other constructor, // rest of the proto chain must be annotated already annotated = true; break; } var _actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false); defineProperty(source, key, _actionDescriptor); annotated = true; } } source = Object.getPrototypeOf(source); } if (annotated) { recordAnnotationApplied(adm, this, key); } else if (!((_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? void 0 : _adm$target_$storedAn[key])) { // Throw on missing key, except for decorators: // Decorator annotations are collected from whole prototype chain. // When called from super() some props may not exist yet. // However we don't have to worry about missing prop, // because the decorator must have been applied to something. die(1, this.annotationType_, adm.name_ + "." + key.toString()); } } function extend_$1(adm, key, descriptor, proxyTrap) { var actionDescriptor = createActionDescriptor(adm, this, key, descriptor); return adm.defineProperty_(key, actionDescriptor, proxyTrap); } function assertActionDescriptor(adm, _ref, key, _ref2) { var annotationType_ = _ref.annotationType_; var value = _ref2.value; if ( !isFunction(value)) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a function value.")); } } function createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes safeDescriptors) { var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3; if (safeDescriptors === void 0) { safeDescriptors = globalState.safeDescriptors; } assertActionDescriptor(adm, annotation, key, descriptor); var value = descriptor.value; if ((_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.bound) { var _adm$proxy_; value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); } return { value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false), // Non-configurable for classes // prevents accidental field redefinition in subclass configurable: safeDescriptors ? adm.isPlainObject_ : true, // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 enumerable: false, // Non-obsevable, therefore non-writable // Also prevents rewriting in subclass constructor writable: safeDescriptors ? false : true }; } function createFlowAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$2, extend_: extend_$2 }; } function make_$2(adm, key) { var _adm$target_$storedAn; var annotated = false; var source = adm.target_; while (source && source !== objectPrototype) { var descriptor = getDescriptor(source, key); if (descriptor) { if (source !== adm.target_) { // Prototype if (isFlow(descriptor.value)) { // A prototype could have been annotated already by other constructor, // rest of the proto chain must be annotated already annotated = true; break; } var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false); defineProperty(source, key, flowDescriptor); } else { var _flowDescriptor = createFlowDescriptor(adm, this, key, descriptor); var definePropertyOutcome = adm.defineProperty_(key, _flowDescriptor); if (!definePropertyOutcome) { // Intercepted return; } } annotated = true; } source = Object.getPrototypeOf(source); } if (annotated) { recordAnnotationApplied(adm, this, key); } else if (!((_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? void 0 : _adm$target_$storedAn[key])) { // Throw on missing key, except for decorators: // Decorator annotations are collected from whole prototype chain. // When called from super() some props may not exist yet. // However we don't have to worry about missing prop, // because the decorator must have been applied to something. die(1, this.annotationType_, adm.name_ + "." + key.toString()); } } function extend_$2(adm, key, descriptor, proxyTrap) { var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor); return adm.defineProperty_(key, flowDescriptor, proxyTrap); } function assertFlowDescriptor(adm, _ref, key, _ref2) { var annotationType_ = _ref.annotationType_; var value = _ref2.value; if ( !isFunction(value)) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a generator function value.")); } } function createFlowDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes safeDescriptors) { if (safeDescriptors === void 0) { safeDescriptors = globalState.safeDescriptors; } assertFlowDescriptor(adm, annotation, key, descriptor); return { value: flow(descriptor.value), // Non-configurable for classes // prevents accidental field redefinition in subclass configurable: safeDescriptors ? adm.isPlainObject_ : true, // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058 enumerable: false, // Non-obsevable, therefore non-writable // Also prevents rewriting in subclass constructor writable: safeDescriptors ? false : true }; } function createComputedAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$3, extend_: extend_$3 }; } function make_$3(adm, key) { var _adm$target_$storedAn; var source = adm.target_; while (source && source !== objectPrototype) { var descriptor = getDescriptor(source, key); if (descriptor) { assertComputedDescriptor(adm, this, key, descriptor); var definePropertyOutcome = adm.defineComputedProperty_(key, _extends({}, this.options_, { get: descriptor.get, set: descriptor.set })); if (!definePropertyOutcome) { // Intercepted return; } recordAnnotationApplied(adm, this, key); return; } source = Object.getPrototypeOf(source); } if (!((_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? void 0 : _adm$target_$storedAn[key])) { // Throw on missing key, except for decorators: // Decorator annotations are collected from whole prototype chain. // When called from super() some props may not exist yet. // However we don't have to worry about missing prop, // because the decorator must have been applied to something. die(1, this.annotationType_, adm.name_ + "." + key.toString()); } } function extend_$3(adm, key, descriptor, proxyTrap) { assertComputedDescriptor(adm, this, key, descriptor); return adm.defineComputedProperty_(key, _extends({}, this.options_, { get: descriptor.get, set: descriptor.set }), proxyTrap); } function assertComputedDescriptor(adm, _ref, key, _ref2) { var annotationType_ = _ref.annotationType_; var get = _ref2.get; if ( !get) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on getter(+setter) properties.")); } } function createObservableAnnotation(name, options) { return { annotationType_: name, options_: options, make_: make_$4, extend_: extend_$4 }; } function make_$4(adm, key) { var _adm$target_$storedAn; var source = adm.target_; // Copy props from proto as well, see test: // "decorate should work with Object.create" while (source && source !== objectPrototype) { var descriptor = getDescriptor(source, key); if (descriptor) { var _this$options_$enhanc, _this$options_; assertObservableDescriptor(adm, this, key, descriptor); var definePropertyOutcome = adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer); if (!definePropertyOutcome) { // Intercepted return; } recordAnnotationApplied(adm, this, key); return; } source = Object.getPrototypeOf(source); } if (!((_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? void 0 : _adm$target_$storedAn[key])) { // Throw on missing key, except for decorators: // Decorator annotations are collected from whole prototype chain. // When called from super() some props may not exist yet. // However we don't have to worry about missing prop, // because the decorator must have been applied to something. die(1, this.annotationType_, adm.name_ + "." + key.toString()); } } function extend_$4(adm, key, descriptor, proxyTrap) { var _this$options_$enhanc2, _this$options_2; assertObservableDescriptor(adm, this, key, descriptor); return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc2 = (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.enhancer) != null ? _this$options_$enhanc2 : deepEnhancer, proxyTrap); } function assertObservableDescriptor(adm, _ref, key, descriptor) { var annotationType_ = _ref.annotationType_; if ( !("value" in descriptor)) { die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' cannot be used on getter/setter properties")); } } // in the majority of cases var defaultCreateObservableOptions = { deep: true, name: undefined, defaultDecorator: undefined, proxy: true }; Object.freeze(defaultCreateObservableOptions); function asCreateObservableOptions(thing) { return thing || defaultCreateObservableOptions; } var observableAnnotation = /*#__PURE__*/createObservableAnnotation("observable"); var observableRefAnnotation = /*#__PURE__*/createObservableAnnotation("observable.ref", { enhancer: referenceEnhancer }); var observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation("observable.shallow", { enhancer: shallowEnhancer }); var observableStructAnnotation = /*#__PURE__*/createObservableAnnotation("observable.struct", { enhancer: refStructEnhancer }); var observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation); function getEnhancerFromOptions(options) { return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator); } function getAnnotationFromOptions(options) { return options ? options.deep === true ? observableAnnotation : options.deep === false ? observableRefAnnotation : options.defaultDecorator : undefined; } function getEnhancerFromAnnotation(annotation) { var _annotation$options_$, _annotation$options_; return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer; } /** * Turns an object, array or function into a reactive structure. * @param v the value which should become observable. */ function createObservable(v, arg2, arg3) { // @observable someProp; if (isStringish(arg2)) { storeAnnotation(v, arg2, observableAnnotation); return; } // already observable - ignore if (isObservable(v)) return v; // plain object if (isPlainObject(v)) return observable.object(v, arg2, arg3); // Array if (Array.isArray(v)) return observable.array(v, arg2); // Map if (isES6Map(v)) return observable.map(v, arg2); // Set if (isES6Set(v)) return observable.set(v, arg2); // other object - ignore if (typeof v === "object" && v !== null) return v; // anything else return observable.box(v, arg2); } Object.assign(createObservable, observableDecoratorAnnotation); var observableFactories = { box: function box(value, options) { var o = asCreateObservableOptions(options); return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals); }, array: function array(initialValues, options) { var o = asCreateObservableOptions(options); return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name); }, map: function map(initialValues, options) { var o = asCreateObservableOptions(options); return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name); }, set: function set(initialValues, options) { var o = asCreateObservableOptions(options); return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name); }, object: function object(props, decorators, options) { return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators); }, ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation), shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation), deep: observableDecoratorAnnotation, struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation) }; // eslint-disable-next-line var observable = /*#__PURE__*/assign(createObservable, observableFactories); var COMPUTED = "computed"; var COMPUTED_STRUCT = "computed.struct"; var computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED); var computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, { equals: comparer.structural }); /** * Decorator for class properties: @computed get value() { return expr; }. * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`; */ var computed = function computed(arg1, arg2) { if (isStringish(arg2)) { // @computed return storeAnnotation(arg1, arg2, computedAnnotation); } if (isPlainObject(arg1)) { // @computed({ options }) return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1)); } // computed(expr, options?) { if (!isFunction(arg1)) die("First argument to `computed` should be an expression."); if (isFunction(arg2)) die("A setter as second argument is no longer supported, use `{ set: fn }` option instead"); } var opts = isPlainObject(arg2) ? arg2 : {}; opts.get = arg1; opts.name || (opts.name = arg1.name || ""); /* for generated name */ return new ComputedValue(opts); }; Object.assign(computed, computedAnnotation); computed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation); var _getDescriptor$config, _getDescriptor; // mobx versions var currentActionId = 0; var nextActionId = 1; var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object var tmpNameDescriptor = { value: "action", configurable: true, writable: false, enumerable: false }; function createAction(actionName, fn, autoAction, ref) { if (autoAction === void 0) { autoAction = false; } { if (!isFunction(fn)) die("`action` can only be invoked on functions"); if (typeof actionName !== "string" || !actionName) die("actions should have valid names, got: '" + actionName + "'"); } function res() { return executeAction(actionName, autoAction, fn, ref || this, arguments); } res.isMobxAction = true; if (isFunctionNameConfigurable) { tmpNameDescriptor.value = actionName; Object.defineProperty(res, "name", tmpNameDescriptor); } return res; } function executeAction(actionName, canRunAsDerivation, fn, scope, args) { var runInfo = _startAction(actionName, canRunAsDerivation, scope, args); try { return fn.apply(scope, args); } catch (err) { runInfo.error_ = err; throw err; } finally { _endAction(runInfo); } } function _startAction(actionName, canRunAsDerivation, // true for autoAction scope, args) { var notifySpy_ = isSpyEnabled() && !!actionName; var startTime_ = 0; if ( notifySpy_) { startTime_ = Date.now(); var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY; spyReportStart({ type: ACTION, name: actionName, object: scope, arguments: flattenedArgs }); } var prevDerivation_ = globalState.trackingDerivation; var runAsAction = !canRunAsDerivation || !prevDerivation_; startBatch(); var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow if (runAsAction) { untrackedStart(); prevAllowStateChanges_ = allowStateChangesStart(true); } var prevAllowStateReads_ = allowStateReadsStart(true); var runInfo = { runAsAction_: runAsAction, prevDerivation_: prevDerivation_, prevAllowStateChanges_: prevAllowStateChanges_, prevAllowStateReads_: prevAllowStateReads_, notifySpy_: notifySpy_, startTime_: startTime_, actionId_: nextActionId++, parentActionId_: currentActionId }; currentActionId = runInfo.actionId_; return runInfo; } function _endAction(runInfo) { if (currentActionId !== runInfo.actionId_) { die(30); } currentActionId = runInfo.parentActionId_; if (runInfo.error_ !== undefined) { globalState.suppressReactionErrors = true; } allowStateChangesEnd(runInfo.prevAllowStateChanges_); allowStateReadsEnd(runInfo.prevAllowStateReads_); endBatch(); if (runInfo.runAsAction_) untrackedEnd(runInfo.prevDerivation_); if ( runInfo.notifySpy_) { spyReportEnd({ time: Date.now() - runInfo.startTime_ }); } globalState.suppressReactionErrors = false; } function allowStateChanges(allowStateChanges, func) { var prev = allowStateChangesStart(allowStateChanges); try { return func(); } finally { allowStateChangesEnd(prev); } } function allowStateChangesStart(allowStateChanges) { var prev = globalState.allowStateChanges; globalState.allowStateChanges = allowStateChanges; return prev; } function allowStateChangesEnd(prev) { globalState.allowStateChanges = prev; } var _Symbol$toPrimitive; var CREATE = "create"; _Symbol$toPrimitive = Symbol.toPrimitive; var ObservableValue = /*#__PURE__*/function (_Atom) { _inheritsLoose(ObservableValue, _Atom); function ObservableValue(value, enhancer, name_, notifySpy, equals) { var _this; if (name_ === void 0) { name_ = "ObservableValue@" + getNextId() ; } if (notifySpy === void 0) { notifySpy = true; } if (equals === void 0) { equals = comparer["default"]; } _this = _Atom.call(this, name_) || this; _this.enhancer = void 0; _this.name_ = void 0; _this.equals = void 0; _this.hasUnreportedChange_ = false; _this.interceptors_ = void 0; _this.changeListeners_ = void 0; _this.value_ = void 0; _this.dehancer = void 0; _this.enhancer = enhancer; _this.name_ = name_; _this.equals = equals; _this.value_ = enhancer(value, undefined, name_); if ( notifySpy && isSpyEnabled()) { // only notify spy if this is a stand-alone observable spyReport({ type: CREATE, object: _assertThisInitialized(_this), observableKind: "value", debugObjectName: _this.name_, newValue: "" + _this.value_ }); } return _this; } var _proto = ObservableValue.prototype; _proto.dehanceValue = function dehanceValue(value) { if (this.dehancer !== undefined) return this.dehancer(value); return value; }; _proto.set = function set(newValue) { var oldValue = this.value_; newValue = this.prepareNewValue_(newValue); if (newValue !== globalState.UNCHANGED) { var notifySpy = isSpyEnabled(); if ( notifySpy) { spyReportStart({ type: UPDATE, object: this, observableKind: "value", debugObjectName: this.name_, newValue: newValue, oldValue: oldValue }); } this.setNewValue_(newValue); if ( notifySpy) spyReportEnd(); } }; _proto.prepareNewValue_ = function prepareNewValue_(newValue) { checkIfStateModificationsAreAllowed(this); if (hasInterceptors(this)) { var change = interceptChange(this, { object: this, type: UPDATE, newValue: newValue }); if (!change) return globalState.UNCHANGED; newValue = change.newValue; } // apply modifier newValue = this.enhancer(newValue, this.value_, this.name_); return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue; }; _proto.setNewValue_ = function setNewValue_(newValue) { var oldValue = this.value_; this.value_ = newValue; this.reportChanged(); if (hasListeners(this)) { notifyListeners(this, { type: UPDATE, object: this, newValue: newValue, oldValue: oldValue }); } }; _proto.get = function get() { this.reportObserved(); return this.dehanceValue(this.value_); }; _proto.intercept_ = function intercept_(handler) { return registerInterceptor(this, handler); }; _proto.observe_ = function observe_(listener, fireImmediately) { if (fireImmediately) listener({ observableKind: "value", debugObjectName: this.name_, object: this, type: UPDATE, newValue: this.value_, oldValue: undefined }); return registerListener(this, listener); }; _proto.raw = function raw() { // used by MST ot get undehanced value return this.value_; }; _proto.toJSON = function toJSON() { return this.get(); }; _proto.toString = function toString() { return this.name_ + "[" + this.value_ + "]"; }; _proto.valueOf = function valueOf() { return toPrimitive(this.get()); }; _proto[_Symbol$toPrimitive] = function () { return this.valueOf(); }; return ObservableValue; }(Atom); var isObservableValue = /*#__PURE__*/createInstanceofPredicate("ObservableValue", ObservableValue); var _Symbol$toPrimitive$1; /** * A node in the state dependency root that observes other nodes, and can be observed itself. * * ComputedValue will remember the result of the computation for the duration of the batch, or * while being observed. * * During this time it will recompute only when one of its direct dependencies changed, * but only when it is being accessed with `ComputedValue.get()`. * * Implementation description: * 1. First time it's being accessed it will compute and remember result * give back remembered result until 2. happens * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3. * 3. When it's being accessed, recompute if any shallow dependency changed. * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step. * go to step 2. either way * * If at any point it's outside batch and it isn't observed: reset everything and go to 1. */ _Symbol$toPrimitive$1 = Symbol.toPrimitive; var ComputedValue = /*#__PURE__*/function () { // nodes we are looking at. Our value depends on these nodes // during tracking it's an array with new observed observers // to check for cycles // N.B: unminified as it is used by MST /** * Create a new computed value based on a function expression. * * The `name` property is for debug purposes only. * * The `equals` property specifies the comparer function to use to determine if a newly produced * value differs from the previous value. Two comparers are provided in the library; `defaultComparer` * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure. * Structural comparison can be convenient if you always produce a new aggregated object and * don't want to notify observers if it is structurally the same. * This is useful for working with vectors, mouse coordinates etc. */ function ComputedValue(options) { this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; this.observing_ = []; this.newObserving_ = null; this.isBeingObserved_ = false; this.isPendingUnobservation_ = false; this.observers_ = new Set();