1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645 |
- (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 extendStatics = function(d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- function __extends(d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
- var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
- };
- function __read(o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
- }
- function __spread() {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
- }
- var OBFUSCATED_ERROR = "An invariant failed, however the error is obfuscated because this is an production build.";
- var EMPTY_ARRAY = [];
- Object.freeze(EMPTY_ARRAY);
- var EMPTY_OBJECT = {};
- Object.freeze(EMPTY_OBJECT);
- var mockGlobal = {};
- function getGlobal() {
- if (typeof window !== "undefined") {
- return window;
- }
- if (typeof global !== "undefined") {
- return global;
- }
- if (typeof self !== "undefined") {
- return self;
- }
- return mockGlobal;
- }
- function getNextId() {
- return ++globalState.mobxGuid;
- }
- function fail(message) {
- invariant(false, message);
- throw "X";
- }
- function invariant(check, message) {
- if (!check)
- throw new Error("[mobx] " + (message || OBFUSCATED_ERROR));
- }
-
- var deprecatedMessages = [];
- function deprecated(msg, thing) {
- if (process.env.NODE_ENV === "production")
- return false;
- if (thing) {
- return deprecated("'" + msg + "', use '" + thing + "' instead.");
- }
- if (deprecatedMessages.indexOf(msg) !== -1)
- return false;
- deprecatedMessages.push(msg);
- console.error("[mobx] Deprecated: " + msg);
- return true;
- }
-
- function once(func) {
- var invoked = false;
- return function () {
- if (invoked)
- return;
- invoked = true;
- return func.apply(this, arguments);
- };
- }
- var noop = function () { };
- function unique(list) {
- var res = [];
- list.forEach(function (item) {
- if (res.indexOf(item) === -1)
- res.push(item);
- });
- return res;
- }
- function isObject(value) {
- return value !== null && typeof value === "object";
- }
- function isPlainObject(value) {
- if (value === null || typeof value !== "object")
- return false;
- var proto = Object.getPrototypeOf(value);
- return proto === Object.prototype || proto === null;
- }
- function convertToMap(dataStructure) {
- if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {
- return dataStructure;
- }
- else if (Array.isArray(dataStructure)) {
- return new Map(dataStructure);
- }
- else if (isPlainObject(dataStructure)) {
- return new Map(Object.entries(dataStructure));
- }
- else {
- return fail("Cannot convert to map from '" + dataStructure + "'");
- }
- }
- function makeNonEnumerable(object, propNames) {
- for (var i = 0; i < propNames.length; i++) {
- addHiddenProp(object, propNames[i], object[propNames[i]]);
- }
- }
- function addHiddenProp(object, propName, value) {
- Object.defineProperty(object, propName, {
- enumerable: false,
- writable: true,
- configurable: true,
- value: value
- });
- }
- function addHiddenFinalProp(object, propName, value) {
- Object.defineProperty(object, propName, {
- enumerable: false,
- writable: false,
- configurable: true,
- value: value
- });
- }
- function isPropertyConfigurable(object, prop) {
- var descriptor = Object.getOwnPropertyDescriptor(object, prop);
- return !descriptor || (descriptor.configurable !== false && descriptor.writable !== false);
- }
- function assertPropertyConfigurable(object, prop) {
- if (process.env.NODE_ENV !== "production" && !isPropertyConfigurable(object, prop))
- fail("Cannot make property '" + prop + "' observable, it is not configurable and writable in the target object");
- }
- function createInstanceofPredicate(name, clazz) {
- var propName = "isMobX" + name;
- clazz.prototype[propName] = true;
- return function (x) {
- return isObject(x) && x[propName] === true;
- };
- }
- function areBothNaN(a, b) {
- return typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b);
- }
-
- function isArrayLike(x) {
- return Array.isArray(x) || isObservableArray(x);
- }
- function isES6Map(thing) {
- if (getGlobal().Map !== undefined && thing instanceof getGlobal().Map)
- return true;
- return false;
- }
- function isES6Set(thing) {
- return thing instanceof Set;
- }
-
- function iteratorToArray(it) {
- var res = [];
- while (true) {
- var r = it.next();
- if (r.done)
- break;
- res.push(r.value);
- }
- return res;
- }
- function primitiveSymbol() {
-
- return (typeof Symbol === "function" && Symbol.toPrimitive) || "@@toPrimitive";
- }
- function toPrimitive(value) {
- return value === null ? null : typeof value === "object" ? "" + value : value;
- }
- function iteratorSymbol() {
- return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator";
- }
- function declareIterator(prototType, iteratorFactory) {
- addHiddenFinalProp(prototType, iteratorSymbol(), iteratorFactory);
- }
- function makeIterable(iterator) {
- iterator[iteratorSymbol()] = getSelf;
- return iterator;
- }
- function toStringTagSymbol() {
- return (typeof Symbol === "function" && Symbol.toStringTag) || "@@toStringTag";
- }
- function getSelf() {
- return this;
- }
-
- var Atom = (function () {
-
- function Atom(name) {
- if (name === void 0) { name = "Atom@" + getNextId(); }
- this.name = name;
- this.isPendingUnobservation = false;
- this.isBeingObserved = false;
- this.observers = [];
- this.observersIndexes = {};
- this.diffValue = 0;
- this.lastAccessedBy = 0;
- this.lowestObserverState = exports.IDerivationState.NOT_TRACKING;
- }
- Atom.prototype.onBecomeUnobserved = function () {
-
- };
- Atom.prototype.onBecomeObserved = function () {
-
- };
-
- Atom.prototype.reportObserved = function () {
- return reportObserved(this);
- };
-
- Atom.prototype.reportChanged = function () {
- startBatch();
- propagateChanged(this);
- endBatch();
- };
- Atom.prototype.toString = function () {
- return this.name;
- };
- return Atom;
- }());
- var isAtom = 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);
- onBecomeObserved(atom, onBecomeObservedHandler);
- 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 areBothNaN(a, b) || identityComparer(a, b);
- }
- var comparer = {
- identity: identityComparer,
- structural: structuralComparer,
- default: defaultComparer,
- shallow: shallowComparer
- };
- var enumerableDescriptorCache = {};
- var nonEnumerableDescriptorCache = {};
- function createPropertyInitializerDescriptor(prop, enumerable) {
- var cache = enumerable ? enumerableDescriptorCache : nonEnumerableDescriptorCache;
- return (cache[prop] ||
- (cache[prop] = {
- configurable: true,
- enumerable: enumerable,
- get: function () {
- initializeInstance(this);
- return this[prop];
- },
- set: function (value) {
- initializeInstance(this);
- this[prop] = value;
- }
- }));
- }
- function initializeInstance(target) {
- if (target.__mobxDidRunLazyInitializers === true)
- return;
- var decorators = target.__mobxDecorators;
- if (decorators) {
- addHiddenProp(target, "__mobxDidRunLazyInitializers", true);
- for (var key in decorators) {
- var d = decorators[key];
- d.propertyCreator(target, d.prop, d.descriptor, d.decoratorTarget, d.decoratorArguments);
- }
- }
- }
- function createPropDecorator(propertyInitiallyEnumerable, propertyCreator) {
- return function decoratorFactory() {
- var decoratorArguments;
- var decorator = function decorate(target, prop, descriptor, applyImmediately
- // This is a special parameter to signal the direct application of a decorator, allow extendObservable to skip the entire type decoration part,
- // as the instance to apply the decorator to equals the target
- ) {
- if (applyImmediately === true) {
- propertyCreator(target, prop, descriptor, target, decoratorArguments);
- return null;
- }
- if (process.env.NODE_ENV !== "production" && !quacksLikeADecorator(arguments))
- fail("This function is a decorator, but it wasn't invoked like a decorator");
- if (!Object.prototype.hasOwnProperty.call(target, "__mobxDecorators")) {
- var inheritedDecorators = target.__mobxDecorators;
- addHiddenProp(target, "__mobxDecorators", __assign({}, inheritedDecorators));
- }
- target.__mobxDecorators[prop] = {
- prop: prop,
- propertyCreator: propertyCreator,
- descriptor: descriptor,
- decoratorTarget: target,
- decoratorArguments: decoratorArguments
- };
- return createPropertyInitializerDescriptor(prop, propertyInitiallyEnumerable);
- };
- if (quacksLikeADecorator(arguments)) {
-
- decoratorArguments = EMPTY_ARRAY;
- return decorator.apply(null, arguments);
- }
- else {
-
- decoratorArguments = Array.prototype.slice.call(arguments);
- return decorator;
- }
- };
- }
- function quacksLikeADecorator(args) {
- return (((args.length === 2 || args.length === 3) && typeof args[1] === "string") ||
- (args.length === 4 && args[3] === true));
- }
- function deepEnhancer(v, _, name) {
-
- if (isObservable(v))
- return v;
-
- 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 });
- return fail(process.env.NODE_ENV !== "production" &&
- "The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets");
- }
- function referenceEnhancer(newValue) {
-
- return newValue;
- }
- function refStructEnhancer(v, oldValue, name) {
- if (process.env.NODE_ENV !== "production" && isObservable(v))
- throw "observable.struct should not be used with observable values";
- if (deepEqual(v, oldValue))
- return oldValue;
- return v;
- }
- function createDecoratorForEnhancer(enhancer) {
- var decorator = createPropDecorator(true, function (target, propertyName, descriptor, _decoratorTarget, decoratorArgs) {
- if (process.env.NODE_ENV !== "production") {
- invariant(!descriptor || !descriptor.get, "@observable cannot be used on getter (property \"" + propertyName + "\"), use @computed instead.");
- }
- var initialValue = descriptor
- ? descriptor.initializer
- ? descriptor.initializer.call(target)
- : descriptor.value
- : undefined;
- defineObservableProperty(target, propertyName, initialValue, enhancer);
- });
- var res =
-
- typeof process !== "undefined" && process.env && process.env.NODE_ENV !== "production"
- ? function observableDecorator() {
-
-
- if (arguments.length < 2)
- return fail("Incorrect decorator invocation. @observable decorator doesn't expect any arguments");
- return decorator.apply(null, arguments);
- }
- : decorator;
- res.enhancer = enhancer;
- return res;
- }
-
-
- var defaultCreateObservableOptions = {
- deep: true,
- name: undefined,
- defaultDecorator: undefined
- };
- var shallowCreateObservableOptions = {
- deep: false,
- name: undefined,
- defaultDecorator: undefined
- };
- Object.freeze(defaultCreateObservableOptions);
- Object.freeze(shallowCreateObservableOptions);
- function assertValidOption(key) {
- if (!/^(deep|name|equals|defaultDecorator)$/.test(key))
- fail("invalid option for (extend)observable: " + key);
- }
- function asCreateObservableOptions(thing) {
- if (thing === null || thing === undefined)
- return defaultCreateObservableOptions;
- if (typeof thing === "string")
- return { name: thing, deep: true };
- if (process.env.NODE_ENV !== "production") {
- if (typeof thing !== "object")
- return fail("expected options object");
- Object.keys(thing).forEach(assertValidOption);
- }
- return thing;
- }
- function getEnhancerFromOptions(options) {
- return options.defaultDecorator
- ? options.defaultDecorator.enhancer
- : options.deep === false
- ? referenceEnhancer
- : deepEnhancer;
- }
- var deepDecorator = createDecoratorForEnhancer(deepEnhancer);
- var shallowDecorator = createDecoratorForEnhancer(shallowEnhancer);
- var refDecorator = createDecoratorForEnhancer(referenceEnhancer);
- var refStructDecorator = createDecoratorForEnhancer(refStructEnhancer);
-
- function createObservable(v, arg2, arg3) {
-
- if (typeof arguments[1] === "string") {
- return deepDecorator.apply(null, arguments);
- }
-
- if (isObservable(v))
- return v;
-
- var res = isPlainObject(v)
- ? observable.object(v, arg2, arg3)
- : Array.isArray(v)
- ? observable.array(v, arg2)
- : isES6Map(v)
- ? observable.map(v, arg2)
- : isES6Set(v)
- ? observable.set(v, arg2)
- : v;
-
- if (res !== v)
- return res;
-
- fail(process.env.NODE_ENV !== "production" &&
- "The provided value could not be converted into an observable. If you want just create an observable reference to the object use 'observable.box(value)'");
- }
- var observableFactories = {
- box: function (value, options) {
- if (arguments.length > 2)
- incorrectlyUsedAsDecorator("box");
- var o = asCreateObservableOptions(options);
- return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);
- },
- shallowBox: function (value, name) {
- if (arguments.length > 2)
- incorrectlyUsedAsDecorator("shallowBox");
- deprecated("observable.shallowBox", "observable.box(value, { deep: false })");
- return observable.box(value, { name: name, deep: false });
- },
- array: function (initialValues, options) {
- if (arguments.length > 2)
- incorrectlyUsedAsDecorator("array");
- var o = asCreateObservableOptions(options);
- return new ObservableArray(initialValues, getEnhancerFromOptions(o), o.name);
- },
- shallowArray: function (initialValues, name) {
- if (arguments.length > 2)
- incorrectlyUsedAsDecorator("shallowArray");
- deprecated("observable.shallowArray", "observable.array(values, { deep: false })");
- return observable.array(initialValues, { name: name, deep: false });
- },
- map: function (initialValues, options) {
- if (arguments.length > 2)
- incorrectlyUsedAsDecorator("map");
- var o = asCreateObservableOptions(options);
- return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);
- },
- shallowMap: function (initialValues, name) {
- if (arguments.length > 2)
- incorrectlyUsedAsDecorator("shallowMap");
- deprecated("observable.shallowMap", "observable.map(values, { deep: false })");
- return observable.map(initialValues, { name: name, deep: false });
- },
- set: function (initialValues, options) {
- if (arguments.length > 2)
- incorrectlyUsedAsDecorator("set");
- var o = asCreateObservableOptions(options);
- return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);
- },
- object: function (props, decorators, options) {
- if (typeof arguments[1] === "string")
- incorrectlyUsedAsDecorator("object");
- var o = asCreateObservableOptions(options);
- return extendObservable({}, props, decorators, o);
- },
- shallowObject: function (props, name) {
- if (typeof arguments[1] === "string")
- incorrectlyUsedAsDecorator("shallowObject");
- deprecated("observable.shallowObject", "observable.object(values, {}, { deep: false })");
- return observable.object(props, {}, { name: name, deep: false });
- },
- ref: refDecorator,
- shallow: shallowDecorator,
- deep: deepDecorator,
- struct: refStructDecorator
- };
- var observable = createObservable;
-
- Object.keys(observableFactories).forEach(function (name) { return (observable[name] = observableFactories[name]); });
- function incorrectlyUsedAsDecorator(methodName) {
- fail(
-
- "Expected one or two arguments to observable." + methodName + ". Did you accidentally try to use observable." + methodName + " as decorator?");
- }
- var computedDecorator = createPropDecorator(false, function (instance, propertyName, descriptor, decoratorTarget, decoratorArgs) {
- var get = descriptor.get, set = descriptor.set; // initialValue is the descriptor for get / set props
- // Optimization: faster on decorator target or instance? Assuming target
- // Optimization: find out if declaring on instance isn't just faster. (also makes the property descriptor simpler). But, more memory usage..
- // Forcing instance now, fixes hot reloadig issues on React Native:
- var options = decoratorArgs[0] || {};
- defineComputedProperty(instance, propertyName, __assign({ get: get, set: set }, options));
- });
- var computedStructDecorator = computedDecorator({ equals: comparer.structural });
-
- var computed = function computed(arg1, arg2, arg3) {
- if (typeof arg2 === "string") {
-
- return computedDecorator.apply(null, arguments);
- }
- if (arg1 !== null && typeof arg1 === "object" && arguments.length === 1) {
-
- return computedDecorator.apply(null, arguments);
- }
-
- if (process.env.NODE_ENV !== "production") {
- invariant(typeof arg1 === "function", "First argument to `computed` should be an expression.");
- invariant(arguments.length < 3, "Computed takes one or two arguments if used as function");
- }
- var opts = typeof arg2 === "object" ? arg2 : {};
- opts.get = arg1;
- opts.set = typeof arg2 === "function" ? arg2 : opts.set;
- opts.name = opts.name || arg1.name || "";
- return new ComputedValue(opts);
- };
- computed.struct = computedStructDecorator;
- (function (IDerivationState) {
-
-
- IDerivationState[IDerivationState["NOT_TRACKING"] = -1] = "NOT_TRACKING";
-
-
-
- IDerivationState[IDerivationState["UP_TO_DATE"] = 0] = "UP_TO_DATE";
-
-
-
-
-
-
- IDerivationState[IDerivationState["POSSIBLY_STALE"] = 1] = "POSSIBLY_STALE";
-
-
- IDerivationState[IDerivationState["STALE"] = 2] = "STALE";
- })(exports.IDerivationState || (exports.IDerivationState = {}));
- var TraceMode;
- (function (TraceMode) {
- TraceMode[TraceMode["NONE"] = 0] = "NONE";
- TraceMode[TraceMode["LOG"] = 1] = "LOG";
- TraceMode[TraceMode["BREAK"] = 2] = "BREAK";
- })(TraceMode || (TraceMode = {}));
- var CaughtException = (function () {
- function CaughtException(cause) {
- this.cause = cause;
-
- }
- return CaughtException;
- }());
- function isCaughtException(e) {
- return e instanceof CaughtException;
- }
-
- function shouldCompute(derivation) {
- switch (derivation.dependenciesState) {
- case exports.IDerivationState.UP_TO_DATE:
- return false;
- case exports.IDerivationState.NOT_TRACKING:
- case exports.IDerivationState.STALE:
- return true;
- case exports.IDerivationState.POSSIBLY_STALE: {
- var prevUntracked = untrackedStart();
- var obs = derivation.observing, l = obs.length;
- for (var i = 0; i < l; i++) {
- var obj = obs[i];
- if (isComputedValue(obj)) {
- if (globalState.disableErrorBoundaries) {
- obj.get();
- }
- else {
- try {
- obj.get();
- }
- catch (e) {
-
- untrackedEnd(prevUntracked);
- return true;
- }
- }
-
-
-
- if (derivation.dependenciesState === exports.IDerivationState.STALE) {
- untrackedEnd(prevUntracked);
- return true;
- }
- }
- }
- changeDependenciesStateTo0(derivation);
- untrackedEnd(prevUntracked);
- return false;
- }
- }
- }
-
-
-
-
-
-
-
-
-
- function isComputingDerivation() {
- return globalState.trackingDerivation !== null;
- }
- function checkIfStateModificationsAreAllowed(atom) {
- var hasObservers = atom.observers.length > 0;
-
- if (globalState.computationDepth > 0 && hasObservers)
- fail(process.env.NODE_ENV !== "production" &&
- "Computed values are not allowed to cause side effects by changing observables that are already being observed. Tried to modify: " + atom.name);
-
- if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === "strict"))
- fail(process.env.NODE_ENV !== "production" &&
- (globalState.enforceActions
- ? "Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: "
- : "Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, the render function of a React component? Tried to modify: ") +
- atom.name);
- }
- function checkIfStateReadsAreAllowed(observable) {
- if (process.env.NODE_ENV !== "production" &&
- !globalState.allowStateReads &&
- globalState.observableRequiresReaction) {
- console.warn("[mobx] Observable " + observable.name + " being read outside a reactive context");
- }
- }
-
- function trackDerivedFunction(derivation, f, context) {
- var prevAllowStateReads = allowStateReadsStart(true);
-
-
- changeDependenciesStateTo0(derivation);
- derivation.newObserving = new Array(derivation.observing.length + 100);
- derivation.unboundDepsCount = 0;
- derivation.runId = ++globalState.runId;
- var prevTracking = globalState.trackingDerivation;
- globalState.trackingDerivation = derivation;
- var result;
- if (globalState.disableErrorBoundaries === true) {
- result = f.call(context);
- }
- else {
- try {
- result = f.call(context);
- }
- catch (e) {
- result = new CaughtException(e);
- }
- }
- globalState.trackingDerivation = prevTracking;
- bindDependencies(derivation);
- if (derivation.observing.length === 0) {
- warnAboutDerivationWithoutDependencies(derivation);
- }
- allowStateReadsEnd(prevAllowStateReads);
- return result;
- }
- function warnAboutDerivationWithoutDependencies(derivation) {
- if (process.env.NODE_ENV === "production")
- return;
- if (globalState.reactionRequiresObservable || derivation.requiresObservable) {
- console.warn("[mobx] Derivation " + derivation.name + " is created/updated without reading any observable value");
- }
- }
-
- function bindDependencies(derivation) {
-
- var prevObserving = derivation.observing;
- var observing = (derivation.observing = derivation.newObserving);
- var lowestNewObservingDerivationState = exports.IDerivationState.UP_TO_DATE;
-
-
-
- var i0 = 0, l = derivation.unboundDepsCount;
- for (var i = 0; i < l; i++) {
- var dep = observing[i];
- if (dep.diffValue === 0) {
- dep.diffValue = 1;
- if (i0 !== i)
- observing[i0] = dep;
- i0++;
- }
-
-
- if (dep.dependenciesState > lowestNewObservingDerivationState) {
- lowestNewObservingDerivationState = dep.dependenciesState;
- }
- }
- observing.length = i0;
- derivation.newObserving = null;
-
-
-
- l = prevObserving.length;
- while (l--) {
- var dep = prevObserving[l];
- if (dep.diffValue === 0) {
- removeObserver(dep, derivation);
- }
- dep.diffValue = 0;
- }
-
-
-
- while (i0--) {
- var dep = observing[i0];
- if (dep.diffValue === 1) {
- dep.diffValue = 0;
- addObserver(dep, derivation);
- }
- }
-
-
- if (lowestNewObservingDerivationState !== exports.IDerivationState.UP_TO_DATE) {
- derivation.dependenciesState = lowestNewObservingDerivationState;
- derivation.onBecomeStale();
- }
- }
- function clearObserving(derivation) {
-
- var obs = derivation.observing;
- derivation.observing = [];
- var i = obs.length;
- while (i--)
- removeObserver(obs[i], derivation);
- derivation.dependenciesState = exports.IDerivationState.NOT_TRACKING;
- }
- function untracked(action) {
- var prev = untrackedStart();
- var res = action();
- untrackedEnd(prev);
- return res;
- }
- function untrackedStart() {
- var prev = globalState.trackingDerivation;
- globalState.trackingDerivation = null;
- return prev;
- }
- function untrackedEnd(prev) {
- globalState.trackingDerivation = prev;
- }
- function allowStateReadsStart(allowStateReads) {
- var prev = globalState.allowStateReads;
- globalState.allowStateReads = allowStateReads;
- return prev;
- }
- function allowStateReadsEnd(prev) {
- globalState.allowStateReads = prev;
- }
-
- function changeDependenciesStateTo0(derivation) {
- if (derivation.dependenciesState === exports.IDerivationState.UP_TO_DATE)
- return;
- derivation.dependenciesState = exports.IDerivationState.UP_TO_DATE;
- var obs = derivation.observing;
- var i = obs.length;
- while (i--)
- obs[i].lowestObserverState = exports.IDerivationState.UP_TO_DATE;
- }
-
-
- var currentActionId = 0;
- var nextActionId = 1;
- function createAction(actionName, fn) {
- if (process.env.NODE_ENV !== "production") {
- invariant(typeof fn === "function", "`action` can only be invoked on functions");
- if (typeof actionName !== "string" || !actionName)
- fail("actions should have valid names, got: '" + actionName + "'");
- }
- var res = function () {
- return executeAction(actionName, fn, this, arguments);
- };
- res.isMobxAction = true;
- return res;
- }
- function executeAction(actionName, fn, scope, args) {
- var runInfo = _startAction(actionName, scope, args);
- try {
- return fn.apply(scope, args);
- }
- catch (err) {
- runInfo.error = err;
- throw err;
- }
- finally {
- _endAction(runInfo);
- }
- }
- function _startAction(actionName, scope, args) {
- var notifySpy = isSpyEnabled() && !!actionName;
- var startTime = 0;
- if (notifySpy) {
- startTime = Date.now();
- var l = (args && args.length) || 0;
- var flattendArgs = new Array(l);
- if (l > 0)
- for (var i = 0; i < l; i++)
- flattendArgs[i] = args[i];
- spyReportStart({
- type: "action",
- name: actionName,
- object: scope,
- arguments: flattendArgs
- });
- }
- var prevDerivation = untrackedStart();
- startBatch();
- var prevAllowStateChanges = allowStateChangesStart(true);
- var prevAllowStateReads = allowStateReadsStart(true);
- var runInfo = {
- 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) {
- fail("invalid action stack. did you forget to finish an action?");
- }
- currentActionId = runInfo.parentActionId;
- if (runInfo.error !== undefined) {
- globalState.suppressReactionErrors = true;
- }
- allowStateChangesEnd(runInfo.prevAllowStateChanges);
- allowStateReadsEnd(runInfo.prevAllowStateReads);
- endBatch();
- untrackedEnd(runInfo.prevDerivation);
- if (runInfo.notifySpy) {
- spyReportEnd({ time: Date.now() - runInfo.startTime });
- }
- globalState.suppressReactionErrors = false;
- }
- function allowStateChanges(allowStateChanges, func) {
- var prev = allowStateChangesStart(allowStateChanges);
- var res;
- try {
- res = func();
- }
- finally {
- allowStateChangesEnd(prev);
- }
- return res;
- }
- function allowStateChangesStart(allowStateChanges) {
- var prev = globalState.allowStateChanges;
- globalState.allowStateChanges = allowStateChanges;
- return prev;
- }
- function allowStateChangesEnd(prev) {
- globalState.allowStateChanges = prev;
- }
- function allowStateChangesInsideComputed(func) {
- var prev = globalState.computationDepth;
- globalState.computationDepth = 0;
- var res;
- try {
- res = func();
- }
- finally {
- globalState.computationDepth = prev;
- }
- return res;
- }
- var ObservableValue = (function (_super) {
- __extends(ObservableValue, _super);
- function ObservableValue(value, enhancer, name, notifySpy, equals) {
- if (name === void 0) { name = "ObservableValue@" + getNextId(); }
- if (notifySpy === void 0) { notifySpy = true; }
- if (equals === void 0) { equals = comparer.default; }
- var _this = _super.call(this, name) || this;
- _this.enhancer = enhancer;
- _this.name = name;
- _this.equals = equals;
- _this.hasUnreportedChange = false;
- _this.value = enhancer(value, undefined, name);
- if (notifySpy && isSpyEnabled()) {
-
- spyReport({ type: "create", name: _this.name, newValue: "" + _this.value });
- }
- return _this;
- }
- ObservableValue.prototype.dehanceValue = function (value) {
- if (this.dehancer !== undefined)
- return this.dehancer(value);
- return value;
- };
- ObservableValue.prototype.set = function (newValue) {
- var oldValue = this.value;
- newValue = this.prepareNewValue(newValue);
- if (newValue !== globalState.UNCHANGED) {
- var notifySpy = isSpyEnabled();
- if (notifySpy) {
- spyReportStart({
- type: "update",
- name: this.name,
- newValue: newValue,
- oldValue: oldValue
- });
- }
- this.setNewValue(newValue);
- if (notifySpy)
- spyReportEnd();
- }
- };
- ObservableValue.prototype.prepareNewValue = function (newValue) {
- checkIfStateModificationsAreAllowed(this);
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- object: this,
- type: "update",
- newValue: newValue
- });
- if (!change)
- return globalState.UNCHANGED;
- newValue = change.newValue;
- }
-
- newValue = this.enhancer(newValue, this.value, this.name);
- return this.equals(this.value, newValue) ? globalState.UNCHANGED : newValue;
- };
- ObservableValue.prototype.setNewValue = function (newValue) {
- var oldValue = this.value;
- this.value = newValue;
- this.reportChanged();
- if (hasListeners(this)) {
- notifyListeners(this, {
- type: "update",
- object: this,
- newValue: newValue,
- oldValue: oldValue
- });
- }
- };
- ObservableValue.prototype.get = function () {
- this.reportObserved();
- return this.dehanceValue(this.value);
- };
- ObservableValue.prototype.intercept = function (handler) {
- return registerInterceptor(this, handler);
- };
- ObservableValue.prototype.observe = function (listener, fireImmediately) {
- if (fireImmediately)
- listener({
- object: this,
- type: "update",
- newValue: this.value,
- oldValue: undefined
- });
- return registerListener(this, listener);
- };
- ObservableValue.prototype.toJSON = function () {
- return this.get();
- };
- ObservableValue.prototype.toString = function () {
- return this.name + "[" + this.value + "]";
- };
- ObservableValue.prototype.valueOf = function () {
- return toPrimitive(this.get());
- };
- return ObservableValue;
- }(Atom));
- ObservableValue.prototype[primitiveSymbol()] = ObservableValue.prototype.valueOf;
- var isObservableValue = createInstanceofPredicate("ObservableValue", ObservableValue);
-
- var ComputedValue = (function () {
-
- function ComputedValue(options) {
- this.dependenciesState = exports.IDerivationState.NOT_TRACKING;
- this.observing = [];
- this.newObserving = null;
- this.isBeingObserved = false;
- this.isPendingUnobservation = false;
- this.observers = [];
- this.observersIndexes = {};
- this.diffValue = 0;
- this.runId = 0;
- this.lastAccessedBy = 0;
- this.lowestObserverState = exports.IDerivationState.UP_TO_DATE;
- this.unboundDepsCount = 0;
- this.__mapid = "#" + getNextId();
- this.value = new CaughtException(null);
- this.isComputing = false;
- this.isRunningSetter = false;
- this.isTracing = TraceMode.NONE;
- if (process.env.NODE_ENV !== "production" && !options.get)
- return fail("missing option for computed: get");
- this.derivation = options.get;
- this.name = options.name || "ComputedValue@" + getNextId();
- if (options.set)
- this.setter = createAction(this.name + "-setter", options.set);
- this.equals =
- options.equals ||
- (options.compareStructural || options.struct
- ? comparer.structural
- : comparer.default);
- this.scope = options.context;
- this.requiresReaction = !!options.requiresReaction;
- this.keepAlive = !!options.keepAlive;
- }
- ComputedValue.prototype.onBecomeStale = function () {
- propagateMaybeChanged(this);
- };
- ComputedValue.prototype.onBecomeUnobserved = function () { };
- ComputedValue.prototype.onBecomeObserved = function () { };
-
- ComputedValue.prototype.get = function () {
- if (this.isComputing)
- fail("Cycle detected in computation " + this.name + ": " + this.derivation);
- if (globalState.inBatch === 0 && this.observers.length === 0 && !this.keepAlive) {
- if (shouldCompute(this)) {
- this.warnAboutUntrackedRead();
- startBatch();
- this.value = this.computeValue(false);
- endBatch();
- }
- }
- else {
- reportObserved(this);
- if (shouldCompute(this))
- if (this.trackAndCompute())
- propagateChangeConfirmed(this);
- }
- var result = this.value;
- if (isCaughtException(result))
- throw result.cause;
- return result;
- };
- ComputedValue.prototype.peek = function () {
- var res = this.computeValue(false);
- if (isCaughtException(res))
- throw res.cause;
- return res;
- };
- ComputedValue.prototype.set = function (value) {
- if (this.setter) {
- invariant(!this.isRunningSetter, "The setter of computed value '" + this.name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?");
- this.isRunningSetter = true;
- try {
- this.setter.call(this.scope, value);
- }
- finally {
- this.isRunningSetter = false;
- }
- }
- else
- invariant(false, process.env.NODE_ENV !== "production" &&
- "[ComputedValue '" + this.name + "'] It is not possible to assign a new value to a computed value.");
- };
- ComputedValue.prototype.trackAndCompute = function () {
- if (isSpyEnabled()) {
- spyReport({
- object: this.scope,
- type: "compute",
- name: this.name
- });
- }
- var oldValue = this.value;
- var wasSuspended =
- this.dependenciesState === exports.IDerivationState.NOT_TRACKING;
- var newValue = this.computeValue(true);
- var changed = wasSuspended ||
- isCaughtException(oldValue) ||
- isCaughtException(newValue) ||
- !this.equals(oldValue, newValue);
- if (changed) {
- this.value = newValue;
- }
- return changed;
- };
- ComputedValue.prototype.computeValue = function (track) {
- this.isComputing = true;
- globalState.computationDepth++;
- var res;
- if (track) {
- res = trackDerivedFunction(this, this.derivation, this.scope);
- }
- else {
- if (globalState.disableErrorBoundaries === true) {
- res = this.derivation.call(this.scope);
- }
- else {
- try {
- res = this.derivation.call(this.scope);
- }
- catch (e) {
- res = new CaughtException(e);
- }
- }
- }
- globalState.computationDepth--;
- this.isComputing = false;
- return res;
- };
- ComputedValue.prototype.suspend = function () {
- if (!this.keepAlive) {
- clearObserving(this);
- this.value = undefined;
- }
- };
- ComputedValue.prototype.observe = function (listener, fireImmediately) {
- var _this = this;
- var firstTime = true;
- var prevValue = undefined;
- return autorun(function () {
- var newValue = _this.get();
- if (!firstTime || fireImmediately) {
- var prevU = untrackedStart();
- listener({
- type: "update",
- object: _this,
- newValue: newValue,
- oldValue: prevValue
- });
- untrackedEnd(prevU);
- }
- firstTime = false;
- prevValue = newValue;
- });
- };
- ComputedValue.prototype.warnAboutUntrackedRead = function () {
- if (process.env.NODE_ENV === "production")
- return;
- if (this.requiresReaction === true) {
- fail("[mobx] Computed value " + this.name + " is read outside a reactive context");
- }
- if (this.isTracing !== TraceMode.NONE) {
- console.log("[mobx.trace] '" + this.name + "' is being read outside a reactive context. Doing a full recompute");
- }
- if (globalState.computedRequiresReaction) {
- console.warn("[mobx] Computed value " + this.name + " is being read outside a reactive context. Doing a full recompute");
- }
- };
- ComputedValue.prototype.toJSON = function () {
- return this.get();
- };
- ComputedValue.prototype.toString = function () {
- return this.name + "[" + this.derivation.toString() + "]";
- };
- ComputedValue.prototype.valueOf = function () {
- return toPrimitive(this.get());
- };
- return ComputedValue;
- }());
- ComputedValue.prototype[primitiveSymbol()] = ComputedValue.prototype.valueOf;
- var isComputedValue = createInstanceofPredicate("ComputedValue", ComputedValue);
-
- var persistentKeys = [
- "mobxGuid",
- "spyListeners",
- "enforceActions",
- "computedRequiresReaction",
- "reactionRequiresObservable",
- "observableRequiresReaction",
- "allowStateReads",
- "disableErrorBoundaries",
- "runId",
- "UNCHANGED"
- ];
- var MobXGlobals = (function () {
- function MobXGlobals() {
-
- this.version = 5;
-
- this.UNCHANGED = {};
-
- this.trackingDerivation = null;
-
- this.computationDepth = 0;
-
- this.runId = 0;
-
- this.mobxGuid = 0;
-
- this.inBatch = 0;
-
- this.pendingUnobservations = [];
-
- this.pendingReactions = [];
-
- this.isRunningReactions = false;
-
- this.allowStateChanges = true;
-
- this.allowStateReads = true;
-
- this.enforceActions = false;
-
- this.spyListeners = [];
-
- this.globalReactionErrorHandlers = [];
-
- this.computedRequiresReaction = false;
-
- this.reactionRequiresObservable = false;
-
- this.observableRequiresReaction = false;
-
- this.computedConfigurable = false;
-
- this.disableErrorBoundaries = false;
-
- this.suppressReactionErrors = false;
- }
- return MobXGlobals;
- }());
- var canMergeGlobalState = true;
- var isolateCalled = false;
- var globalState = (function () {
- var global = getGlobal();
- if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals)
- canMergeGlobalState = false;
- if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version)
- canMergeGlobalState = false;
- if (!canMergeGlobalState) {
- setTimeout(function () {
- if (!isolateCalled) {
- fail("There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`");
- }
- }, 1);
- return new MobXGlobals();
- }
- else if (global.__mobxGlobals) {
- global.__mobxInstanceCount += 1;
- if (!global.__mobxGlobals.UNCHANGED)
- global.__mobxGlobals.UNCHANGED = {};
- return global.__mobxGlobals;
- }
- else {
- global.__mobxInstanceCount = 1;
- return (global.__mobxGlobals = new MobXGlobals());
- }
- })();
- function isolateGlobalState() {
- if (globalState.pendingReactions.length ||
- globalState.inBatch ||
- globalState.isRunningReactions)
- fail("isolateGlobalState should be called before MobX is running any reactions");
- isolateCalled = true;
- if (canMergeGlobalState) {
- if (--getGlobal().__mobxInstanceCount === 0)
- getGlobal().__mobxGlobals = undefined;
- globalState = new MobXGlobals();
- }
- }
- function getGlobalState() {
- return globalState;
- }
-
- function resetGlobalState() {
- var defaultGlobals = new MobXGlobals();
- for (var key in defaultGlobals)
- if (persistentKeys.indexOf(key) === -1)
- globalState[key] = defaultGlobals[key];
- globalState.allowStateChanges = !globalState.enforceActions;
- }
- function hasObservers(observable) {
- return observable.observers && observable.observers.length > 0;
- }
- function getObservers(observable) {
- return observable.observers;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- function addObserver(observable, node) {
-
-
-
- var l = observable.observers.length;
- if (l) {
-
- observable.observersIndexes[node.__mapid] = l;
- }
- observable.observers[l] = node;
- if (observable.lowestObserverState > node.dependenciesState)
- observable.lowestObserverState = node.dependenciesState;
-
-
- }
- function removeObserver(observable, node) {
-
-
-
- if (observable.observers.length === 1) {
-
- observable.observers.length = 0;
- queueForUnobservation(observable);
- }
- else {
-
- var list = observable.observers;
- var map = observable.observersIndexes;
- var filler = list.pop();
- if (filler !== node) {
-
- var index = map[node.__mapid] || 0;
- if (index) {
-
- map[filler.__mapid] = index;
- }
- else {
- delete map[filler.__mapid];
- }
- list[index] = filler;
- }
- delete map[node.__mapid];
- }
-
-
- }
- function queueForUnobservation(observable) {
- if (observable.isPendingUnobservation === false) {
-
- observable.isPendingUnobservation = true;
- globalState.pendingUnobservations.push(observable);
- }
- }
-
- function startBatch() {
- globalState.inBatch++;
- }
- function endBatch() {
- if (--globalState.inBatch === 0) {
- runReactions();
-
- var list = globalState.pendingUnobservations;
- for (var i = 0; i < list.length; i++) {
- var observable = list[i];
- observable.isPendingUnobservation = false;
- if (observable.observers.length === 0) {
- if (observable.isBeingObserved) {
-
- observable.isBeingObserved = false;
- observable.onBecomeUnobserved();
- }
- if (observable instanceof ComputedValue) {
-
-
- observable.suspend();
- }
- }
- }
- globalState.pendingUnobservations = [];
- }
- }
- function reportObserved(observable) {
- checkIfStateReadsAreAllowed(observable);
- var derivation = globalState.trackingDerivation;
- if (derivation !== null) {
-
- if (derivation.runId !== observable.lastAccessedBy) {
- observable.lastAccessedBy = derivation.runId;
- derivation.newObserving[derivation.unboundDepsCount++] = observable;
- if (!observable.isBeingObserved) {
- observable.isBeingObserved = true;
- observable.onBecomeObserved();
- }
- }
- return true;
- }
- else if (observable.observers.length === 0 && globalState.inBatch > 0) {
- queueForUnobservation(observable);
- }
- return false;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- function propagateChanged(observable) {
-
- if (observable.lowestObserverState === exports.IDerivationState.STALE)
- return;
- observable.lowestObserverState = exports.IDerivationState.STALE;
- var observers = observable.observers;
- var i = observers.length;
- while (i--) {
- var d = observers[i];
- if (d.dependenciesState === exports.IDerivationState.UP_TO_DATE) {
- if (d.isTracing !== TraceMode.NONE) {
- logTraceInfo(d, observable);
- }
- d.onBecomeStale();
- }
- d.dependenciesState = exports.IDerivationState.STALE;
- }
-
- }
-
- function propagateChangeConfirmed(observable) {
-
- if (observable.lowestObserverState === exports.IDerivationState.STALE)
- return;
- observable.lowestObserverState = exports.IDerivationState.STALE;
- var observers = observable.observers;
- var i = observers.length;
- while (i--) {
- var d = observers[i];
- if (d.dependenciesState === exports.IDerivationState.POSSIBLY_STALE)
- d.dependenciesState = exports.IDerivationState.STALE;
- else if (d.dependenciesState === exports.IDerivationState.UP_TO_DATE
- )
- observable.lowestObserverState = exports.IDerivationState.UP_TO_DATE;
- }
-
- }
-
- function propagateMaybeChanged(observable) {
-
- if (observable.lowestObserverState !== exports.IDerivationState.UP_TO_DATE)
- return;
- observable.lowestObserverState = exports.IDerivationState.POSSIBLY_STALE;
- var observers = observable.observers;
- var i = observers.length;
- while (i--) {
- var d = observers[i];
- if (d.dependenciesState === exports.IDerivationState.UP_TO_DATE) {
- d.dependenciesState = exports.IDerivationState.POSSIBLY_STALE;
- if (d.isTracing !== TraceMode.NONE) {
- logTraceInfo(d, observable);
- }
- d.onBecomeStale();
- }
- }
-
- }
- function logTraceInfo(derivation, observable) {
- console.log("[mobx.trace] '" + derivation.name + "' is invalidated due to a change in: '" + observable.name + "'");
- if (derivation.isTracing === TraceMode.BREAK) {
- var lines = [];
- printDepTree(getDependencyTree(derivation), lines, 1);
-
- new Function("debugger;\n/*\nTracing '" + derivation.name + "'\n\nYou are entering this break point because derivation '" + derivation.name + "' is being traced and '" + observable.name + "' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\//g, "/") : "") + "\n\nThe dependencies for this derivation are:\n\n" + lines.join("\n") + "\n*/\n ")();
- }
- }
- function printDepTree(tree, lines, depth) {
- if (lines.length >= 1000) {
- lines.push("(and many more)");
- return;
- }
- lines.push("" + new Array(depth).join("\t") + tree.name);
- if (tree.dependencies)
- tree.dependencies.forEach(function (child) { return printDepTree(child, lines, depth + 1); });
- }
- var Reaction = (function () {
- function Reaction(name, onInvalidate, errorHandler, requiresObservable) {
- if (name === void 0) { name = "Reaction@" + getNextId(); }
- if (requiresObservable === void 0) { requiresObservable = false; }
- this.name = name;
- this.onInvalidate = onInvalidate;
- this.errorHandler = errorHandler;
- this.requiresObservable = requiresObservable;
- this.observing = [];
- this.newObserving = [];
- this.dependenciesState = exports.IDerivationState.NOT_TRACKING;
- this.diffValue = 0;
- this.runId = 0;
- this.unboundDepsCount = 0;
- this.__mapid = "#" + getNextId();
- this.isDisposed = false;
- this._isScheduled = false;
- this._isTrackPending = false;
- this._isRunning = false;
- this.isTracing = TraceMode.NONE;
- }
- Reaction.prototype.onBecomeStale = function () {
- this.schedule();
- };
- Reaction.prototype.schedule = function () {
- if (!this._isScheduled) {
- this._isScheduled = true;
- globalState.pendingReactions.push(this);
- runReactions();
- }
- };
- Reaction.prototype.isScheduled = function () {
- return this._isScheduled;
- };
-
- Reaction.prototype.runReaction = function () {
- if (!this.isDisposed) {
- startBatch();
- this._isScheduled = false;
- if (shouldCompute(this)) {
- this._isTrackPending = true;
- try {
- this.onInvalidate();
- if (this._isTrackPending && isSpyEnabled()) {
-
- spyReport({
- name: this.name,
- type: "scheduled-reaction"
- });
- }
- }
- catch (e) {
- this.reportExceptionInDerivation(e);
- }
- }
- endBatch();
- }
- };
- Reaction.prototype.track = function (fn) {
- startBatch();
- var notify = isSpyEnabled();
- var startTime;
- if (notify) {
- startTime = Date.now();
- spyReportStart({
- name: this.name,
- type: "reaction"
- });
- }
- this._isRunning = true;
- var result = trackDerivedFunction(this, fn, undefined);
- this._isRunning = false;
- this._isTrackPending = false;
- if (this.isDisposed) {
-
- clearObserving(this);
- }
- if (isCaughtException(result))
- this.reportExceptionInDerivation(result.cause);
- if (notify) {
- spyReportEnd({
- time: Date.now() - startTime
- });
- }
- endBatch();
- };
- Reaction.prototype.reportExceptionInDerivation = function (error) {
- var _this = this;
- if (this.errorHandler) {
- this.errorHandler(error, this);
- return;
- }
- if (globalState.disableErrorBoundaries)
- throw error;
- var message = "[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '" + this + "'";
- if (globalState.suppressReactionErrors) {
- console.warn("[mobx] (error in reaction '" + this.name + "' suppressed, fix error of causing action below)");
- }
- else {
- console.error(message, error);
-
- }
- if (isSpyEnabled()) {
- spyReport({
- type: "error",
- name: this.name,
- message: message,
- error: "" + error
- });
- }
- globalState.globalReactionErrorHandlers.forEach(function (f) { return f(error, _this); });
- };
- Reaction.prototype.dispose = function () {
- if (!this.isDisposed) {
- this.isDisposed = true;
- if (!this._isRunning) {
-
- startBatch();
- clearObserving(this);
- endBatch();
- }
- }
- };
- Reaction.prototype.getDisposer = function () {
- var r = this.dispose.bind(this);
- r.$mobx = this;
- return r;
- };
- Reaction.prototype.toString = function () {
- return "Reaction[" + this.name + "]";
- };
- Reaction.prototype.trace = function (enterBreakPoint) {
- if (enterBreakPoint === void 0) { enterBreakPoint = false; }
- trace(this, enterBreakPoint);
- };
- return Reaction;
- }());
- function onReactionError(handler) {
- globalState.globalReactionErrorHandlers.push(handler);
- return function () {
- var idx = globalState.globalReactionErrorHandlers.indexOf(handler);
- if (idx >= 0)
- globalState.globalReactionErrorHandlers.splice(idx, 1);
- };
- }
-
- var MAX_REACTION_ITERATIONS = 100;
- var reactionScheduler = function (f) { return f(); };
- function runReactions() {
-
- if (globalState.inBatch > 0 || globalState.isRunningReactions)
- return;
- reactionScheduler(runReactionsHelper);
- }
- function runReactionsHelper() {
- globalState.isRunningReactions = true;
- var allReactions = globalState.pendingReactions;
- var iterations = 0;
-
-
-
- while (allReactions.length > 0) {
- if (++iterations === MAX_REACTION_ITERATIONS) {
- console.error("Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations." +
- (" Probably there is a cycle in the reactive function: " + allReactions[0]));
- allReactions.splice(0);
- }
- var remainingReactions = allReactions.splice(0);
- for (var i = 0, l = remainingReactions.length; i < l; i++)
- remainingReactions[i].runReaction();
- }
- globalState.isRunningReactions = false;
- }
- var isReaction = createInstanceofPredicate("Reaction", Reaction);
- function setReactionScheduler(fn) {
- var baseScheduler = reactionScheduler;
- reactionScheduler = function (f) { return fn(function () { return baseScheduler(f); }); };
- }
- function isSpyEnabled() {
- return !!globalState.spyListeners.length;
- }
- function spyReport(event) {
- if (!globalState.spyListeners.length)
- return;
- var listeners = globalState.spyListeners;
- for (var i = 0, l = listeners.length; i < l; i++)
- listeners[i](event);
- }
- function spyReportStart(event) {
- var change = __assign(__assign({}, event), { spyReportStart: true });
- spyReport(change);
- }
- var END_EVENT = { spyReportEnd: true };
- function spyReportEnd(change) {
- if (change)
- spyReport(__assign(__assign({}, change), { spyReportEnd: true }));
- else
- spyReport(END_EVENT);
- }
- function spy(listener) {
- globalState.spyListeners.push(listener);
- return once(function () {
- globalState.spyListeners = globalState.spyListeners.filter(function (l) { return l !== listener; });
- });
- }
- function dontReassignFields() {
- fail(process.env.NODE_ENV !== "production" && "@action fields are not reassignable");
- }
- function namedActionDecorator(name) {
- return function (target, prop, descriptor) {
- if (descriptor) {
- if (process.env.NODE_ENV !== "production" && descriptor.get !== undefined) {
- return fail("@action cannot be used with getters");
- }
-
-
- if (descriptor.value) {
-
- return {
- value: createAction(name, descriptor.value),
- enumerable: false,
- configurable: true,
- writable: true
- };
- }
-
- var initializer_1 = descriptor.initializer;
- return {
- enumerable: false,
- configurable: true,
- writable: true,
- initializer: function () {
-
- return createAction(name, initializer_1.call(this));
- }
- };
- }
-
- return actionFieldDecorator(name).apply(this, arguments);
- };
- }
- function actionFieldDecorator(name) {
-
- return function (target, prop, descriptor) {
- Object.defineProperty(target, prop, {
- configurable: true,
- enumerable: false,
- get: function () {
- return undefined;
- },
- set: function (value) {
- addHiddenProp(this, prop, action(name, value));
- }
- });
- };
- }
- function boundActionDecorator(target, propertyName, descriptor, applyToInstance) {
- if (applyToInstance === true) {
- defineBoundAction(target, propertyName, descriptor.value);
- return null;
- }
- if (descriptor) {
-
-
-
- return {
- configurable: true,
- enumerable: false,
- get: function () {
- defineBoundAction(this, propertyName, descriptor.value || descriptor.initializer.call(this));
- return this[propertyName];
- },
- set: dontReassignFields
- };
- }
-
- return {
- enumerable: false,
- configurable: true,
- set: function (v) {
- defineBoundAction(this, propertyName, v);
- },
- get: function () {
- return undefined;
- }
- };
- }
- var action = function action(arg1, arg2, arg3, arg4) {
-
- if (arguments.length === 1 && typeof arg1 === "function")
- return createAction(arg1.name || "<unnamed action>", arg1);
-
- if (arguments.length === 2 && typeof arg2 === "function")
- return createAction(arg1, arg2);
-
- if (arguments.length === 1 && typeof arg1 === "string")
- return namedActionDecorator(arg1);
-
- if (arg4 === true) {
-
- arg1[arg2] = createAction(arg1.name || arg2, arg3.value);
- }
- else {
- return namedActionDecorator(arg2).apply(null, arguments);
- }
- };
- action.bound = boundActionDecorator;
- function runInAction(arg1, arg2) {
-
- var actionName = typeof arg1 === "string" ? arg1 : arg1.name || "<unnamed action>";
- var fn = typeof arg1 === "function" ? arg1 : arg2;
- if (process.env.NODE_ENV !== "production") {
- invariant(typeof fn === "function" && fn.length === 0, "`runInAction` expects a function without arguments");
- if (typeof actionName !== "string" || !actionName)
- fail("actions should have valid names, got: '" + actionName + "'");
- }
- return executeAction(actionName, fn, this, undefined);
- }
- function isAction(thing) {
- return typeof thing === "function" && thing.isMobxAction === true;
- }
- function defineBoundAction(target, propertyName, fn) {
- addHiddenProp(target, propertyName, createAction(propertyName, fn.bind(target)));
- }
-
- function autorun(view, opts) {
- if (opts === void 0) { opts = EMPTY_OBJECT; }
- if (process.env.NODE_ENV !== "production") {
- invariant(typeof view === "function", "Autorun expects a function as first argument");
- invariant(isAction(view) === false, "Autorun does not accept actions since actions are untrackable");
- }
- var name = (opts && opts.name) || view.name || "Autorun@" + getNextId();
- var runSync = !opts.scheduler && !opts.delay;
- var reaction;
- if (runSync) {
-
- reaction = new Reaction(name, function () {
- this.track(reactionRunner);
- }, opts.onError, opts.requiresObservable);
- }
- else {
- var scheduler_1 = createSchedulerFromOptions(opts);
-
- var isScheduled_1 = false;
- reaction = new Reaction(name, function () {
- if (!isScheduled_1) {
- isScheduled_1 = true;
- scheduler_1(function () {
- isScheduled_1 = false;
- if (!reaction.isDisposed)
- reaction.track(reactionRunner);
- });
- }
- }, opts.onError, opts.requiresObservable);
- }
- function reactionRunner() {
- view(reaction);
- }
- reaction.schedule();
- return reaction.getDisposer();
- }
- var run = function (f) { return f(); };
- function createSchedulerFromOptions(opts) {
- return opts.scheduler
- ? opts.scheduler
- : opts.delay
- ? function (f) { return setTimeout(f, opts.delay); }
- : run;
- }
- function reaction(expression, effect, opts) {
- if (opts === void 0) { opts = EMPTY_OBJECT; }
- if (typeof opts === "boolean") {
- opts = { fireImmediately: opts };
- deprecated("Using fireImmediately as argument is deprecated. Use '{ fireImmediately: true }' instead");
- }
- if (process.env.NODE_ENV !== "production") {
- invariant(typeof expression === "function", "First argument to reaction should be a function");
- invariant(typeof opts === "object", "Third argument of reactions should be an object");
- }
- var name = opts.name || "Reaction@" + getNextId();
- var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);
- var runSync = !opts.scheduler && !opts.delay;
- var scheduler = createSchedulerFromOptions(opts);
- var firstTime = true;
- var isScheduled = false;
- var value;
- var equals = opts.compareStructural
- ? comparer.structural
- : opts.equals || comparer.default;
- var r = new Reaction(name, function () {
- if (firstTime || runSync) {
- reactionRunner();
- }
- else if (!isScheduled) {
- isScheduled = true;
- scheduler(reactionRunner);
- }
- }, opts.onError, opts.requiresObservable);
- function reactionRunner() {
- isScheduled = false;
- if (r.isDisposed)
- return;
- var changed = false;
- r.track(function () {
- var nextValue = expression(r);
- changed = firstTime || !equals(value, nextValue);
- value = nextValue;
- });
- if (firstTime && opts.fireImmediately)
- effectAction(value, r);
- if (!firstTime && changed === true)
- effectAction(value, r);
- if (firstTime)
- firstTime = false;
- }
- r.schedule();
- return r.getDisposer();
- }
- function wrapErrorHandler(errorHandler, baseFn) {
- return function () {
- try {
- return baseFn.apply(this, arguments);
- }
- catch (e) {
- errorHandler.call(this, e);
- }
- };
- }
- function onBecomeObserved(thing, arg2, arg3) {
- return interceptHook("onBecomeObserved", thing, arg2, arg3);
- }
- function onBecomeUnobserved(thing, arg2, arg3) {
- return interceptHook("onBecomeUnobserved", thing, arg2, arg3);
- }
- function interceptHook(hook, thing, arg2, arg3) {
- var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing);
- var cb = typeof arg3 === "function" ? arg3 : arg2;
- var orig = atom[hook];
- if (typeof orig !== "function")
- return fail(process.env.NODE_ENV !== "production" && "Not an atom that can be (un)observed");
- atom[hook] = function () {
- orig.call(this);
- cb.call(this);
- };
- return function () {
- atom[hook] = orig;
- };
- }
- function configure(options) {
- var enforceActions = options.enforceActions, computedRequiresReaction = options.computedRequiresReaction, computedConfigurable = options.computedConfigurable, disableErrorBoundaries = options.disableErrorBoundaries, arrayBuffer = options.arrayBuffer, reactionScheduler = options.reactionScheduler, reactionRequiresObservable = options.reactionRequiresObservable, observableRequiresReaction = options.observableRequiresReaction;
- if (options.isolateGlobalState === true) {
- isolateGlobalState();
- }
- if (enforceActions !== undefined) {
- if (typeof enforceActions === "boolean" || enforceActions === "strict")
- deprecated("Deprecated value for 'enforceActions', use 'false' => '\"never\"', 'true' => '\"observed\"', '\"strict\"' => \"'always'\" instead");
- var ea = void 0;
- switch (enforceActions) {
- case true:
- case "observed":
- ea = true;
- break;
- case false:
- case "never":
- ea = false;
- break;
- case "strict":
- case "always":
- ea = "strict";
- break;
- default:
- fail("Invalid value for 'enforceActions': '" + enforceActions + "', expected 'never', 'always' or 'observed'");
- }
- globalState.enforceActions = ea;
- globalState.allowStateChanges = ea === true || ea === "strict" ? false : true;
- }
- if (computedRequiresReaction !== undefined) {
- globalState.computedRequiresReaction = !!computedRequiresReaction;
- }
- if (reactionRequiresObservable !== undefined) {
- globalState.reactionRequiresObservable = !!reactionRequiresObservable;
- }
- if (observableRequiresReaction !== undefined) {
- globalState.observableRequiresReaction = !!observableRequiresReaction;
- globalState.allowStateReads = !globalState.observableRequiresReaction;
- }
- if (computedConfigurable !== undefined) {
- globalState.computedConfigurable = !!computedConfigurable;
- }
- if (disableErrorBoundaries !== undefined) {
- if (disableErrorBoundaries === true)
- console.warn("WARNING: Debug feature only. MobX will NOT recover from errors if this is on.");
- globalState.disableErrorBoundaries = !!disableErrorBoundaries;
- }
- if (typeof arrayBuffer === "number") {
- reserveArrayBuffer(arrayBuffer);
- }
- if (reactionScheduler) {
- setReactionScheduler(reactionScheduler);
- }
- }
- function decorate(thing, decorators) {
- if (process.env.NODE_ENV !== "production" && !isPlainObject(decorators))
- fail("Decorators should be a key value map");
- var target = typeof thing === "function" ? thing.prototype : thing;
- var _loop_1 = function (prop) {
- var propertyDecorators = decorators[prop];
- if (!Array.isArray(propertyDecorators)) {
- propertyDecorators = [propertyDecorators];
- }
-
- if (process.env.NODE_ENV !== "production" && !propertyDecorators.every(function (decorator) { return typeof decorator === "function"; }))
- fail("Decorate: expected a decorator function or array of decorator functions for '" + prop + "'");
- var descriptor = Object.getOwnPropertyDescriptor(target, prop);
- var newDescriptor = propertyDecorators.reduce(function (accDescriptor, decorator) { return decorator(target, prop, accDescriptor); }, descriptor);
- if (newDescriptor)
- Object.defineProperty(target, prop, newDescriptor);
- };
- for (var prop in decorators) {
- _loop_1(prop);
- }
- return thing;
- }
- function extendShallowObservable(target, properties, decorators) {
- deprecated("'extendShallowObservable' is deprecated, use 'extendObservable(target, props, { deep: false })' instead");
- return extendObservable(target, properties, decorators, shallowCreateObservableOptions);
- }
- function extendObservable(target, properties, decorators, options) {
- if (process.env.NODE_ENV !== "production") {
- invariant(arguments.length >= 2 && arguments.length <= 4, "'extendObservable' expected 2-4 arguments");
- invariant(typeof target === "object", "'extendObservable' expects an object as first argument");
- invariant(!isObservableMap(target), "'extendObservable' should not be used on maps, use map.merge instead");
- invariant(!isObservable(properties), "Extending an object with another observable (object) is not supported. Please construct an explicit propertymap, using `toJS` if need. See issue #540");
- if (decorators)
- for (var key in decorators)
- if (!(key in properties))
- fail("Trying to declare a decorator for unspecified property '" + key + "'");
- }
- options = asCreateObservableOptions(options);
- var defaultDecorator = options.defaultDecorator || (options.deep === false ? refDecorator : deepDecorator);
- initializeInstance(target);
- asObservableObject(target, options.name, defaultDecorator.enhancer);
- startBatch();
- try {
- for (var key in properties) {
- var descriptor = Object.getOwnPropertyDescriptor(properties, key);
- if (process.env.NODE_ENV !== "production") {
- if (Object.getOwnPropertyDescriptor(target, key))
- fail("'extendObservable' can only be used to introduce new properties. Use 'set' or 'decorate' instead. The property '" + key + "' already exists on '" + target + "'");
- if (isComputed(descriptor.value))
- fail("Passing a 'computed' as initial property value is no longer supported by extendObservable. Use a getter or decorator instead");
- }
- var decorator = decorators && key in decorators
- ? decorators[key]
- : descriptor.get
- ? computedDecorator
- : defaultDecorator;
- if (process.env.NODE_ENV !== "production" && typeof decorator !== "function")
- return fail("Not a valid decorator for '" + key + "', got: " + decorator);
- var resultDescriptor = decorator(target, key, descriptor, true);
- if (resultDescriptor
- )
- Object.defineProperty(target, key, resultDescriptor);
- }
- }
- finally {
- endBatch();
- }
- return target;
- }
- function getDependencyTree(thing, property) {
- return nodeToDependencyTree(getAtom(thing, property));
- }
- function nodeToDependencyTree(node) {
- var result = {
- name: node.name
- };
- if (node.observing && node.observing.length > 0)
- result.dependencies = unique(node.observing).map(nodeToDependencyTree);
- return result;
- }
- function getObserverTree(thing, property) {
- return nodeToObserverTree(getAtom(thing, property));
- }
- function nodeToObserverTree(node) {
- var result = {
- name: node.name
- };
- if (hasObservers(node))
- result.observers = getObservers(node).map(nodeToObserverTree);
- return result;
- }
- var generatorId = 0;
- function FlowCancellationError() {
- this.message = "FLOW_CANCELLED";
- }
- FlowCancellationError.prototype = Object.create(Error.prototype);
- function isFlowCancellationError(error) {
- return error instanceof FlowCancellationError;
- }
- function flow(generator) {
- if (arguments.length !== 1)
- fail(!!process.env.NODE_ENV && "Flow expects one 1 argument and cannot be used as decorator");
- var name = generator.name || "<unnamed flow>";
-
- return function () {
- var ctx = this;
- var args = arguments;
- var runId = ++generatorId;
- var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args);
- var rejector;
- var pendingPromise = undefined;
- var res = new Promise(function (resolve, reject) {
- var stepId = 0;
- rejector = reject;
- function onFulfilled(res) {
- pendingPromise = undefined;
- var ret;
- try {
- ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res);
- }
- catch (e) {
- return reject(e);
- }
- next(ret);
- }
- function onRejected(err) {
- pendingPromise = undefined;
- var ret;
- try {
- ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.throw).call(gen, err);
- }
- catch (e) {
- return reject(e);
- }
- next(ret);
- }
- function next(ret) {
- if (ret && typeof ret.then === "function") {
-
- ret.then(next, reject);
- return;
- }
- if (ret.done)
- return resolve(ret.value);
- pendingPromise = Promise.resolve(ret.value);
- return pendingPromise.then(onFulfilled, onRejected);
- }
- onFulfilled(undefined);
- });
- res.cancel = action(name + " - runid: " + runId + " - cancel", function () {
- try {
- if (pendingPromise)
- cancelPromise(pendingPromise);
-
- var res_1 = gen.return();
-
- var yieldedPromise = Promise.resolve(res_1.value);
- yieldedPromise.then(noop, noop);
- cancelPromise(yieldedPromise);
-
- rejector(new FlowCancellationError());
- }
- catch (e) {
- rejector(e);
- }
- });
- return res;
- };
- }
- function cancelPromise(promise) {
- if (typeof promise.cancel === "function")
- promise.cancel();
- }
- function interceptReads(thing, propOrHandler, handler) {
- var target;
- if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {
- target = getAdministration(thing);
- }
- else if (isObservableObject(thing)) {
- if (typeof propOrHandler !== "string")
- return fail(process.env.NODE_ENV !== "production" &&
- "InterceptReads can only be used with a specific property, not with an object in general");
- target = getAdministration(thing, propOrHandler);
- }
- else {
- return fail(process.env.NODE_ENV !== "production" &&
- "Expected observable map, object or array as first array");
- }
- if (target.dehancer !== undefined)
- return fail(process.env.NODE_ENV !== "production" && "An intercept reader was already established");
- target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler;
- return function () {
- target.dehancer = undefined;
- };
- }
- function intercept(thing, propOrHandler, handler) {
- if (typeof handler === "function")
- return interceptProperty(thing, propOrHandler, handler);
- else
- return interceptInterceptable(thing, propOrHandler);
- }
- function interceptInterceptable(thing, handler) {
- return getAdministration(thing).intercept(handler);
- }
- function interceptProperty(thing, property, handler) {
- return getAdministration(thing, property).intercept(handler);
- }
- function _isComputed(value, property) {
- if (value === null || value === undefined)
- return false;
- if (property !== undefined) {
- if (isObservableObject(value) === false)
- return false;
- if (!value.$mobx.values[property])
- return false;
- var atom = getAtom(value, property);
- return isComputedValue(atom);
- }
- return isComputedValue(value);
- }
- function isComputed(value) {
- if (arguments.length > 1)
- return fail(process.env.NODE_ENV !== "production" &&
- "isComputed expects only 1 argument. Use isObservableProp to inspect the observability of a property");
- return _isComputed(value);
- }
- function isComputedProp(value, propName) {
- if (typeof propName !== "string")
- return fail(process.env.NODE_ENV !== "production" &&
- "isComputed expected a property name as second argument");
- return _isComputed(value, propName);
- }
- function _isObservable(value, property) {
- if (value === null || value === undefined)
- return false;
- if (property !== undefined) {
- if (process.env.NODE_ENV !== "production" &&
- (isObservableMap(value) || isObservableArray(value)))
- return fail("isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");
- if (isObservableObject(value)) {
- var o = value.$mobx;
- return o.values && !!o.values[property];
- }
- return false;
- }
-
- return (isObservableObject(value) ||
- !!value.$mobx ||
- isAtom(value) ||
- isReaction(value) ||
- isComputedValue(value));
- }
- function isObservable(value) {
- if (arguments.length !== 1)
- fail(process.env.NODE_ENV !== "production" &&
- "isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property");
- return _isObservable(value);
- }
- function isObservableProp(value, propName) {
- if (typeof propName !== "string")
- return fail(process.env.NODE_ENV !== "production" && "expected a property name as second argument");
- return _isObservable(value, propName);
- }
- function keys(obj) {
- if (isObservableObject(obj)) {
- return obj.$mobx.getKeys();
- }
- if (isObservableMap(obj)) {
- return obj._keys.slice();
- }
- if (isObservableSet(obj)) {
- return iteratorToArray(obj.keys());
- }
- if (isObservableArray(obj)) {
- return obj.map(function (_, index) { return index; });
- }
- return fail(process.env.NODE_ENV !== "production" &&
- "'keys()' can only be used on observable objects, arrays, sets and maps");
- }
- function values(obj) {
- if (isObservableObject(obj)) {
- return keys(obj).map(function (key) { return obj[key]; });
- }
- if (isObservableMap(obj)) {
- return keys(obj).map(function (key) { return obj.get(key); });
- }
- if (isObservableSet(obj)) {
- return iteratorToArray(obj.values());
- }
- if (isObservableArray(obj)) {
- return obj.slice();
- }
- return fail(process.env.NODE_ENV !== "production" &&
- "'values()' can only be used on observable objects, arrays, sets and maps");
- }
- function entries(obj) {
- if (isObservableObject(obj)) {
- return keys(obj).map(function (key) { return [key, obj[key]]; });
- }
- if (isObservableMap(obj)) {
- return keys(obj).map(function (key) { return [key, obj.get(key)]; });
- }
- if (isObservableSet(obj)) {
- return iteratorToArray(obj.entries());
- }
- if (isObservableArray(obj)) {
- return obj.map(function (key, index) { return [index, key]; });
- }
- return fail(process.env.NODE_ENV !== "production" &&
- "'entries()' can only be used on observable objects, arrays and maps");
- }
- function set(obj, key, value) {
- if (arguments.length === 2 && !isObservableSet(obj)) {
- startBatch();
- var values_1 = key;
- try {
- for (var key_1 in values_1)
- set(obj, key_1, values_1[key_1]);
- }
- finally {
- endBatch();
- }
- return;
- }
- if (isObservableObject(obj)) {
- var adm = obj.$mobx;
- var existingObservable = adm.values[key];
- if (existingObservable) {
- adm.write(obj, key, value);
- }
- else {
- defineObservableProperty(obj, key, value, adm.defaultEnhancer);
- }
- }
- else if (isObservableMap(obj)) {
- obj.set(key, value);
- }
- else if (isObservableSet(obj)) {
- obj.add(key);
- }
- else if (isObservableArray(obj)) {
- if (typeof key !== "number")
- key = parseInt(key, 10);
- invariant(key >= 0, "Not a valid index: '" + key + "'");
- startBatch();
- if (key >= obj.length)
- obj.length = key + 1;
- obj[key] = value;
- endBatch();
- }
- else {
- return fail(process.env.NODE_ENV !== "production" &&
- "'set()' can only be used on observable objects, arrays and maps");
- }
- }
- function remove(obj, key) {
- if (isObservableObject(obj)) {
- obj.$mobx.remove(key);
- }
- else if (isObservableMap(obj)) {
- obj.delete(key);
- }
- else if (isObservableSet(obj)) {
- obj.delete(key);
- }
- else if (isObservableArray(obj)) {
- if (typeof key !== "number")
- key = parseInt(key, 10);
- invariant(key >= 0, "Not a valid index: '" + key + "'");
- obj.splice(key, 1);
- }
- else {
- return fail(process.env.NODE_ENV !== "production" &&
- "'remove()' can only be used on observable objects, arrays and maps");
- }
- }
- function has(obj, key) {
- if (isObservableObject(obj)) {
-
- var adm = getAdministration(obj);
- adm.getKeys();
- return !!adm.values[key];
- }
- else if (isObservableMap(obj)) {
- return obj.has(key);
- }
- else if (isObservableSet(obj)) {
- return obj.has(key);
- }
- else if (isObservableArray(obj)) {
- return key >= 0 && key < obj.length;
- }
- else {
- return fail(process.env.NODE_ENV !== "production" &&
- "'has()' can only be used on observable objects, arrays and maps");
- }
- }
- function get(obj, key) {
- if (!has(obj, key))
- return undefined;
- if (isObservableObject(obj)) {
- return obj[key];
- }
- else if (isObservableMap(obj)) {
- return obj.get(key);
- }
- else if (isObservableArray(obj)) {
- return obj[key];
- }
- else {
- return fail(process.env.NODE_ENV !== "production" &&
- "'get()' can only be used on observable objects, arrays and maps");
- }
- }
- function observe(thing, propOrCb, cbOrFire, fireImmediately) {
- if (typeof cbOrFire === "function")
- return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);
- else
- return observeObservable(thing, propOrCb, cbOrFire);
- }
- function observeObservable(thing, listener, fireImmediately) {
- return getAdministration(thing).observe(listener, fireImmediately);
- }
- function observeObservableProperty(thing, property, listener, fireImmediately) {
- return getAdministration(thing, property).observe(listener, fireImmediately);
- }
- var defaultOptions = {
- detectCycles: true,
- exportMapsAsObjects: true,
- recurseEverything: false
- };
- function cache(map, key, value, options) {
- if (options.detectCycles)
- map.set(key, value);
- return value;
- }
- function toJSHelper(source, options, __alreadySeen) {
- if (!options.recurseEverything && !isObservable(source))
- return source;
- if (typeof source !== "object")
- return source;
-
- if (source === null)
- return null;
-
- if (source instanceof Date)
- return source;
- if (isObservableValue(source))
- return toJSHelper(source.get(), options, __alreadySeen);
-
- if (isObservable(source))
- keys(source);
- var detectCycles = options.detectCycles === true;
- if (detectCycles && source !== null && __alreadySeen.has(source)) {
- return __alreadySeen.get(source);
- }
- if (isObservableArray(source) || Array.isArray(source)) {
- var res_1 = cache(__alreadySeen, source, [], options);
- var toAdd = source.map(function (value) { return toJSHelper(value, options, __alreadySeen); });
- res_1.length = toAdd.length;
- for (var i = 0, l = toAdd.length; i < l; i++)
- res_1[i] = toAdd[i];
- return res_1;
- }
- if (isObservableSet(source) || Object.getPrototypeOf(source) === Set.prototype) {
- if (options.exportMapsAsObjects === false) {
- var res_2 = cache(__alreadySeen, source, new Set(), options);
- source.forEach(function (value) {
- res_2.add(toJSHelper(value, options, __alreadySeen));
- });
- return res_2;
- }
- else {
- var res_3 = cache(__alreadySeen, source, [], options);
- source.forEach(function (value) {
- res_3.push(toJSHelper(value, options, __alreadySeen));
- });
- return res_3;
- }
- }
- if (isObservableMap(source) || Object.getPrototypeOf(source) === Map.prototype) {
- if (options.exportMapsAsObjects === false) {
- var res_4 = cache(__alreadySeen, source, new Map(), options);
- source.forEach(function (value, key) {
- res_4.set(key, toJSHelper(value, options, __alreadySeen));
- });
- return res_4;
- }
- else {
- var res_5 = cache(__alreadySeen, source, {}, options);
- source.forEach(function (value, key) {
- res_5[key] = toJSHelper(value, options, __alreadySeen);
- });
- return res_5;
- }
- }
-
- var res = cache(__alreadySeen, source, {}, options);
- for (var key in source) {
- res[key] = toJSHelper(source[key], options, __alreadySeen);
- }
- return res;
- }
- function toJS(source, options) {
-
- if (typeof options === "boolean")
- options = { detectCycles: options };
- if (!options)
- options = defaultOptions;
- options.detectCycles =
- options.detectCycles === undefined
- ? options.recurseEverything === true
- : options.detectCycles === true;
- var __alreadySeen;
- if (options.detectCycles)
- __alreadySeen = new Map();
- return toJSHelper(source, options, __alreadySeen);
- }
- function trace() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var enterBreakPoint = false;
- if (typeof args[args.length - 1] === "boolean")
- enterBreakPoint = args.pop();
- var derivation = getAtomFromArgs(args);
- if (!derivation) {
- return fail(process.env.NODE_ENV !== "production" &&
- "'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly");
- }
- if (derivation.isTracing === TraceMode.NONE) {
- console.log("[mobx.trace] '" + derivation.name + "' tracing enabled");
- }
- derivation.isTracing = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;
- }
- function getAtomFromArgs(args) {
- switch (args.length) {
- case 0:
- return globalState.trackingDerivation;
- case 1:
- return getAtom(args[0]);
- case 2:
- return getAtom(args[0], args[1]);
- }
- }
-
- function transaction(action, thisArg) {
- if (thisArg === void 0) { thisArg = undefined; }
- startBatch();
- try {
- return action.apply(thisArg);
- }
- finally {
- endBatch();
- }
- }
- function when(predicate, arg1, arg2) {
- if (arguments.length === 1 || (arg1 && typeof arg1 === "object"))
- return whenPromise(predicate, arg1);
- return _when(predicate, arg1, arg2 || {});
- }
- function _when(predicate, effect, opts) {
- var timeoutHandle;
- if (typeof opts.timeout === "number") {
- timeoutHandle = setTimeout(function () {
- if (!disposer.$mobx.isDisposed) {
- disposer();
- var error = new Error("WHEN_TIMEOUT");
- if (opts.onError)
- opts.onError(error);
- else
- throw error;
- }
- }, opts.timeout);
- }
- opts.name = opts.name || "When@" + getNextId();
- var effectAction = createAction(opts.name + "-effect", effect);
- var disposer = autorun(function (r) {
- if (predicate()) {
- r.dispose();
- if (timeoutHandle)
- clearTimeout(timeoutHandle);
- effectAction();
- }
- }, opts);
- return disposer;
- }
- function whenPromise(predicate, opts) {
- if (process.env.NODE_ENV !== "production" && opts && opts.onError)
- return fail("the options 'onError' and 'promise' cannot be combined");
- var cancel;
- var res = new Promise(function (resolve, reject) {
- var disposer = _when(predicate, resolve, __assign(__assign({}, opts), { onError: reject }));
- cancel = function () {
- disposer();
- reject("WHEN_CANCELLED");
- };
- });
- res.cancel = cancel;
- return res;
- }
- function hasInterceptors(interceptable) {
- return interceptable.interceptors !== undefined && interceptable.interceptors.length > 0;
- }
- function registerInterceptor(interceptable, handler) {
- var interceptors = interceptable.interceptors || (interceptable.interceptors = []);
- interceptors.push(handler);
- return once(function () {
- var idx = interceptors.indexOf(handler);
- if (idx !== -1)
- interceptors.splice(idx, 1);
- });
- }
- function interceptChange(interceptable, change) {
- var prevU = untrackedStart();
- try {
- var interceptors = interceptable.interceptors;
- if (interceptors)
- for (var i = 0, l = interceptors.length; i < l; i++) {
- change = interceptors[i](change);
- invariant(!change || change.type, "Intercept handlers should return nothing or a change object");
- if (!change)
- break;
- }
- return change;
- }
- finally {
- untrackedEnd(prevU);
- }
- }
- function hasListeners(listenable) {
- return listenable.changeListeners !== undefined && listenable.changeListeners.length > 0;
- }
- function registerListener(listenable, handler) {
- var listeners = listenable.changeListeners || (listenable.changeListeners = []);
- listeners.push(handler);
- return once(function () {
- var idx = listeners.indexOf(handler);
- if (idx !== -1)
- listeners.splice(idx, 1);
- });
- }
- function notifyListeners(listenable, change) {
- var prevU = untrackedStart();
- var listeners = listenable.changeListeners;
- if (!listeners)
- return;
- listeners = listeners.slice();
- for (var i = 0, l = listeners.length; i < l; i++) {
- listeners[i](change);
- }
- untrackedEnd(prevU);
- }
- var MAX_SPLICE_SIZE = 10000;
-
- var safariPrototypeSetterInheritanceBug = (function () {
- var v = false;
- var p = {};
- Object.defineProperty(p, "0", {
- set: function () {
- v = true;
- }
- });
- Object.create(p)["0"] = 1;
- return v === false;
- })();
-
- var OBSERVABLE_ARRAY_BUFFER_SIZE = 0;
-
- var StubArray = (function () {
- function StubArray() {
- }
- return StubArray;
- }());
- function inherit(ctor, proto) {
- if (typeof Object["setPrototypeOf"] !== "undefined") {
- Object["setPrototypeOf"](ctor.prototype, proto);
- }
- else if (typeof ctor.prototype.__proto__ !== "undefined") {
- ctor.prototype.__proto__ = proto;
- }
- else {
- ctor["prototype"] = proto;
- }
- }
- inherit(StubArray, Array.prototype);
-
-
-
- if (Object.isFrozen(Array)) {
- [
- "constructor",
- "push",
- "shift",
- "concat",
- "pop",
- "unshift",
- "replace",
- "find",
- "findIndex",
- "splice",
- "reverse",
- "sort"
- ].forEach(function (key) {
- Object.defineProperty(StubArray.prototype, key, {
- configurable: true,
- writable: true,
- value: Array.prototype[key]
- });
- });
- }
- var ObservableArrayAdministration = (function () {
- function ObservableArrayAdministration(name, enhancer, array, owned) {
- this.array = array;
- this.owned = owned;
- this.values = [];
- this.lastKnownLength = 0;
- this.atom = new Atom(name || "ObservableArray@" + getNextId());
- this.enhancer = function (newV, oldV) { return enhancer(newV, oldV, name + "[..]"); };
- }
- ObservableArrayAdministration.prototype.dehanceValue = function (value) {
- if (this.dehancer !== undefined)
- return this.dehancer(value);
- return value;
- };
- ObservableArrayAdministration.prototype.dehanceValues = function (values) {
- if (this.dehancer !== undefined && values.length > 0)
- return values.map(this.dehancer);
- return values;
- };
- ObservableArrayAdministration.prototype.intercept = function (handler) {
- return registerInterceptor(this, handler);
- };
- ObservableArrayAdministration.prototype.observe = function (listener, fireImmediately) {
- if (fireImmediately === void 0) { fireImmediately = false; }
- if (fireImmediately) {
- listener({
- object: this.array,
- type: "splice",
- index: 0,
- added: this.values.slice(),
- addedCount: this.values.length,
- removed: [],
- removedCount: 0
- });
- }
- return registerListener(this, listener);
- };
- ObservableArrayAdministration.prototype.getArrayLength = function () {
- this.atom.reportObserved();
- return this.values.length;
- };
- ObservableArrayAdministration.prototype.setArrayLength = function (newLength) {
- if (typeof newLength !== "number" || newLength < 0)
- throw new Error("[mobx.array] Out of range: " + newLength);
- var currentLength = this.values.length;
- if (newLength === currentLength)
- return;
- else if (newLength > currentLength) {
- var newItems = new Array(newLength - currentLength);
- for (var i = 0; i < newLength - currentLength; i++)
- newItems[i] = undefined;
- this.spliceWithArray(currentLength, 0, newItems);
- }
- else
- this.spliceWithArray(newLength, currentLength - newLength);
- };
-
- ObservableArrayAdministration.prototype.updateArrayLength = function (oldLength, delta) {
- if (oldLength !== this.lastKnownLength)
- throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");
- this.lastKnownLength += delta;
- if (delta > 0 && oldLength + delta + 1 > OBSERVABLE_ARRAY_BUFFER_SIZE)
- reserveArrayBuffer(oldLength + delta + 1);
- };
- ObservableArrayAdministration.prototype.spliceWithArray = function (index, deleteCount, newItems) {
- var _this = this;
- checkIfStateModificationsAreAllowed(this.atom);
- var length = this.values.length;
- if (index === undefined)
- index = 0;
- else if (index > length)
- index = length;
- else if (index < 0)
- index = Math.max(0, length + index);
- if (arguments.length === 1)
- deleteCount = length - index;
- else if (deleteCount === undefined || deleteCount === null)
- deleteCount = 0;
- else
- deleteCount = Math.max(0, Math.min(deleteCount, length - index));
- if (newItems === undefined)
- newItems = EMPTY_ARRAY;
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- object: this.array,
- type: "splice",
- index: index,
- removedCount: deleteCount,
- added: newItems
- });
- if (!change)
- return EMPTY_ARRAY;
- deleteCount = change.removedCount;
- newItems = change.added;
- }
- newItems =
- newItems.length === 0 ? newItems : newItems.map(function (v) { return _this.enhancer(v, undefined); });
- var lengthDelta = newItems.length - deleteCount;
- this.updateArrayLength(length, lengthDelta);
- var res = this.spliceItemsIntoValues(index, deleteCount, newItems);
- if (deleteCount !== 0 || newItems.length !== 0)
- this.notifyArraySplice(index, newItems, res);
- return this.dehanceValues(res);
- };
- ObservableArrayAdministration.prototype.spliceItemsIntoValues = function (index, deleteCount, newItems) {
- var _a;
- if (newItems.length < MAX_SPLICE_SIZE) {
- return (_a = this.values).splice.apply(_a, __spread([index, deleteCount], newItems));
- }
- else {
- var res = this.values.slice(index, index + deleteCount);
- this.values = this.values
- .slice(0, index)
- .concat(newItems, this.values.slice(index + deleteCount));
- return res;
- }
- };
- ObservableArrayAdministration.prototype.notifyArrayChildUpdate = function (index, newValue, oldValue) {
- var notifySpy = !this.owned && isSpyEnabled();
- var notify = hasListeners(this);
- var change = notify || notifySpy
- ? {
- object: this.array,
- type: "update",
- index: index,
- newValue: newValue,
- oldValue: oldValue
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: this.atom.name }));
- this.atom.reportChanged();
- if (notify)
- notifyListeners(this, change);
- if (notifySpy)
- spyReportEnd();
- };
- ObservableArrayAdministration.prototype.notifyArraySplice = function (index, added, removed) {
- var notifySpy = !this.owned && isSpyEnabled();
- var notify = hasListeners(this);
- var change = notify || notifySpy
- ? {
- object: this.array,
- type: "splice",
- index: index,
- removed: removed,
- added: added,
- removedCount: removed.length,
- addedCount: added.length
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: this.atom.name }));
- this.atom.reportChanged();
-
- if (notify)
- notifyListeners(this, change);
- if (notifySpy)
- spyReportEnd();
- };
- return ObservableArrayAdministration;
- }());
- var ObservableArray = (function (_super) {
- __extends(ObservableArray, _super);
- function ObservableArray(initialValues, enhancer, name, owned) {
- if (name === void 0) { name = "ObservableArray@" + getNextId(); }
- if (owned === void 0) { owned = false; }
- var _this = _super.call(this) || this;
- var adm = new ObservableArrayAdministration(name, enhancer, _this, owned);
- addHiddenFinalProp(_this, "$mobx", adm);
- if (initialValues && initialValues.length) {
- var prev = allowStateChangesStart(true);
- _this.spliceWithArray(0, 0, initialValues);
- allowStateChangesEnd(prev);
- }
- if (safariPrototypeSetterInheritanceBug) {
-
-
- Object.defineProperty(adm.array, "0", ENTRY_0);
- }
- return _this;
- }
- ObservableArray.prototype.intercept = function (handler) {
- return this.$mobx.intercept(handler);
- };
- ObservableArray.prototype.observe = function (listener, fireImmediately) {
- if (fireImmediately === void 0) { fireImmediately = false; }
- return this.$mobx.observe(listener, fireImmediately);
- };
- ObservableArray.prototype.clear = function () {
- return this.splice(0);
- };
- ObservableArray.prototype.concat = function () {
- var arrays = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- arrays[_i] = arguments[_i];
- }
- this.$mobx.atom.reportObserved();
- return Array.prototype.concat.apply(this.peek(), arrays.map(function (a) { return (isObservableArray(a) ? a.peek() : a); }));
- };
- ObservableArray.prototype.replace = function (newItems) {
- return this.$mobx.spliceWithArray(0, this.$mobx.values.length, newItems);
- };
-
- ObservableArray.prototype.toJS = function () {
- return this.slice();
- };
- ObservableArray.prototype.toJSON = function () {
-
- return this.toJS();
- };
- ObservableArray.prototype.peek = function () {
- this.$mobx.atom.reportObserved();
- return this.$mobx.dehanceValues(this.$mobx.values);
- };
-
- ObservableArray.prototype.find = function (predicate, thisArg, fromIndex) {
- if (fromIndex === void 0) { fromIndex = 0; }
- if (arguments.length === 3)
- deprecated("The array.find fromIndex argument to find will not be supported anymore in the next major");
- var idx = this.findIndex.apply(this, arguments);
- return idx === -1 ? undefined : this.get(idx);
- };
-
- ObservableArray.prototype.findIndex = function (predicate, thisArg, fromIndex) {
- if (fromIndex === void 0) { fromIndex = 0; }
- if (arguments.length === 3)
- deprecated("The array.findIndex fromIndex argument to find will not be supported anymore in the next major");
- var items = this.peek(), l = items.length;
- for (var i = fromIndex; i < l; i++)
- if (predicate.call(thisArg, items[i], i, this))
- return i;
- return -1;
- };
-
- ObservableArray.prototype.splice = function (index, deleteCount) {
- var newItems = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- newItems[_i - 2] = arguments[_i];
- }
- switch (arguments.length) {
- case 0:
- return [];
- case 1:
- return this.$mobx.spliceWithArray(index);
- case 2:
- return this.$mobx.spliceWithArray(index, deleteCount);
- }
- return this.$mobx.spliceWithArray(index, deleteCount, newItems);
- };
- ObservableArray.prototype.spliceWithArray = function (index, deleteCount, newItems) {
- return this.$mobx.spliceWithArray(index, deleteCount, newItems);
- };
- ObservableArray.prototype.push = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- var adm = this.$mobx;
- adm.spliceWithArray(adm.values.length, 0, items);
- return adm.values.length;
- };
- ObservableArray.prototype.pop = function () {
- return this.splice(Math.max(this.$mobx.values.length - 1, 0), 1)[0];
- };
- ObservableArray.prototype.shift = function () {
- return this.splice(0, 1)[0];
- };
- ObservableArray.prototype.unshift = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- var adm = this.$mobx;
- adm.spliceWithArray(0, 0, items);
- return adm.values.length;
- };
- ObservableArray.prototype.reverse = function () {
-
-
-
- var clone = this.slice();
- return clone.reverse.apply(clone, arguments);
- };
- ObservableArray.prototype.sort = function (compareFn) {
-
-
- var clone = this.slice();
- return clone.sort.apply(clone, arguments);
- };
- ObservableArray.prototype.remove = function (value) {
- var idx = this.$mobx.dehanceValues(this.$mobx.values).indexOf(value);
- if (idx > -1) {
- this.splice(idx, 1);
- return true;
- }
- return false;
- };
- ObservableArray.prototype.move = function (fromIndex, toIndex) {
- deprecated("observableArray.move is deprecated, use .slice() & .replace() instead");
- function checkIndex(index) {
- if (index < 0) {
- throw new Error("[mobx.array] Index out of bounds: " + index + " is negative");
- }
- var length = this.$mobx.values.length;
- if (index >= length) {
- throw new Error("[mobx.array] Index out of bounds: " + index + " is not smaller than " + length);
- }
- }
- checkIndex.call(this, fromIndex);
- checkIndex.call(this, toIndex);
- if (fromIndex === toIndex) {
- return;
- }
- var oldItems = this.$mobx.values;
- var newItems;
- if (fromIndex < toIndex) {
- newItems = __spread(oldItems.slice(0, fromIndex), oldItems.slice(fromIndex + 1, toIndex + 1), [
- oldItems[fromIndex]
- ], oldItems.slice(toIndex + 1));
- }
- else {
-
- newItems = __spread(oldItems.slice(0, toIndex), [
- oldItems[fromIndex]
- ], oldItems.slice(toIndex, fromIndex), oldItems.slice(fromIndex + 1));
- }
- this.replace(newItems);
- };
-
- ObservableArray.prototype.get = function (index) {
- var impl = this.$mobx;
- if (impl) {
- if (index < impl.values.length) {
- impl.atom.reportObserved();
- return impl.dehanceValue(impl.values[index]);
- }
- console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + impl.values.length + "). Please check length first. Out of bound indices will not be tracked by MobX");
- }
- return undefined;
- };
-
- ObservableArray.prototype.set = function (index, newValue) {
- var adm = this.$mobx;
- var values = adm.values;
- if (index < values.length) {
-
- checkIfStateModificationsAreAllowed(adm.atom);
- var oldValue = values[index];
- if (hasInterceptors(adm)) {
- var change = interceptChange(adm, {
- type: "update",
- object: this,
- index: index,
- newValue: newValue
- });
- if (!change)
- return;
- newValue = change.newValue;
- }
- newValue = adm.enhancer(newValue, oldValue);
- var changed = newValue !== oldValue;
- if (changed) {
- values[index] = newValue;
- adm.notifyArrayChildUpdate(index, newValue, oldValue);
- }
- }
- else if (index === values.length) {
-
- adm.spliceWithArray(index, 0, [newValue]);
- }
- else {
-
- throw new Error("[mobx.array] Index out of bounds, " + index + " is larger than " + values.length);
- }
- };
- return ObservableArray;
- }(StubArray));
- declareIterator(ObservableArray.prototype, function () {
- this.$mobx.atom.reportObserved();
- var self = this;
- var nextIndex = 0;
- return makeIterable({
- next: function () {
- return nextIndex < self.length
- ? { value: self[nextIndex++], done: false }
- : { done: true, value: undefined };
- }
- });
- });
- Object.defineProperty(ObservableArray.prototype, "length", {
- enumerable: false,
- configurable: true,
- get: function () {
- return this.$mobx.getArrayLength();
- },
- set: function (newLength) {
- this.$mobx.setArrayLength(newLength);
- }
- });
- addHiddenProp(ObservableArray.prototype, toStringTagSymbol(), "Array");
- [
- "every",
- "filter",
- "forEach",
- "indexOf",
- "join",
- "lastIndexOf",
- "map",
- "reduce",
- "reduceRight",
- "slice",
- "some",
- "toString",
- "toLocaleString"
- ].forEach(function (funcName) {
- var baseFunc = Array.prototype[funcName];
- invariant(typeof baseFunc === "function", "Base function not defined on Array prototype: '" + funcName + "'");
- addHiddenProp(ObservableArray.prototype, funcName, function () {
- return baseFunc.apply(this.peek(), arguments);
- });
- });
-
- makeNonEnumerable(ObservableArray.prototype, [
- "constructor",
- "intercept",
- "observe",
- "clear",
- "concat",
- "get",
- "replace",
- "toJS",
- "toJSON",
- "peek",
- "find",
- "findIndex",
- "splice",
- "spliceWithArray",
- "push",
- "pop",
- "set",
- "shift",
- "unshift",
- "reverse",
- "sort",
- "remove",
- "move",
- "toString",
- "toLocaleString"
- ]);
-
- var ENTRY_0 = createArrayEntryDescriptor(0);
- function createArrayEntryDescriptor(index) {
- return {
- enumerable: false,
- configurable: false,
- get: function () {
- return this.get(index);
- },
- set: function (value) {
- this.set(index, value);
- }
- };
- }
- function createArrayBufferItem(index) {
- Object.defineProperty(ObservableArray.prototype, "" + index, createArrayEntryDescriptor(index));
- }
- function reserveArrayBuffer(max) {
- for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max; index++)
- createArrayBufferItem(index);
- OBSERVABLE_ARRAY_BUFFER_SIZE = max;
- }
- reserveArrayBuffer(1000);
- var isObservableArrayAdministration = createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration);
- function isObservableArray(thing) {
- return isObject(thing) && isObservableArrayAdministration(thing.$mobx);
- }
- var ObservableMapMarker = {};
- var ObservableMap = (function () {
- function ObservableMap(initialData, enhancer, name) {
- if (enhancer === void 0) { enhancer = deepEnhancer; }
- if (name === void 0) { name = "ObservableMap@" + getNextId(); }
- this.enhancer = enhancer;
- this.name = name;
- this.$mobx = ObservableMapMarker;
- this._keys = (new ObservableArray(undefined, referenceEnhancer, this.name + ".keys()", true));
- if (typeof Map !== "function") {
- throw new Error("mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js");
- }
- this._data = new Map();
- this._hasMap = new Map();
- this.merge(initialData);
- }
- ObservableMap.prototype._has = function (key) {
- return this._data.has(key);
- };
- ObservableMap.prototype.has = function (key) {
- var _this = this;
- if (!globalState.trackingDerivation)
- return this._has(key);
- var entry = this._hasMap.get(key);
- if (!entry) {
-
- var newEntry = (entry = new ObservableValue(this._has(key), referenceEnhancer, this.name + "." + stringifyKey(key) + "?", false));
- this._hasMap.set(key, newEntry);
- onBecomeUnobserved(newEntry, function () { return _this._hasMap.delete(key); });
- }
- return entry.get();
- };
- ObservableMap.prototype.set = function (key, value) {
- var hasKey = this._has(key);
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- type: hasKey ? "update" : "add",
- object: this,
- newValue: value,
- name: key
- });
- if (!change)
- return this;
- value = change.newValue;
- }
- if (hasKey) {
- this._updateValue(key, value);
- }
- else {
- this._addValue(key, value);
- }
- return this;
- };
- ObservableMap.prototype.delete = function (key) {
- var _this = this;
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- type: "delete",
- object: this,
- name: key
- });
- if (!change)
- return false;
- }
- if (this._has(key)) {
- var notifySpy = isSpyEnabled();
- var notify = hasListeners(this);
- var change = notify || notifySpy
- ? {
- type: "delete",
- object: this,
- oldValue: this._data.get(key).value,
- name: key
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: this.name, key: key }));
- transaction(function () {
- _this._keys.remove(key);
- _this._updateHasMapEntry(key, false);
- var observable = _this._data.get(key);
- observable.setNewValue(undefined);
- _this._data.delete(key);
- });
- if (notify)
- notifyListeners(this, change);
- if (notifySpy)
- spyReportEnd();
- return true;
- }
- return false;
- };
- ObservableMap.prototype._updateHasMapEntry = function (key, value) {
- var entry = this._hasMap.get(key);
- if (entry) {
- entry.setNewValue(value);
- }
- };
- ObservableMap.prototype._updateValue = function (key, newValue) {
- var observable = this._data.get(key);
- newValue = observable.prepareNewValue(newValue);
- if (newValue !== globalState.UNCHANGED) {
- var notifySpy = isSpyEnabled();
- var notify = hasListeners(this);
- var change = notify || notifySpy
- ? {
- type: "update",
- object: this,
- oldValue: observable.value,
- name: key,
- newValue: newValue
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: this.name, key: key }));
- observable.setNewValue(newValue);
- if (notify)
- notifyListeners(this, change);
- if (notifySpy)
- spyReportEnd();
- }
- };
- ObservableMap.prototype._addValue = function (key, newValue) {
- var _this = this;
- transaction(function () {
- var observable = new ObservableValue(newValue, _this.enhancer, _this.name + "." + stringifyKey(key), false);
- _this._data.set(key, observable);
- newValue = observable.value;
- _this._updateHasMapEntry(key, true);
- _this._keys.push(key);
- });
- var notifySpy = isSpyEnabled();
- var notify = hasListeners(this);
- var change = notify || notifySpy
- ? {
- type: "add",
- object: this,
- name: key,
- newValue: newValue
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: this.name, key: key }));
- if (notify)
- notifyListeners(this, change);
- if (notifySpy)
- spyReportEnd();
- };
- ObservableMap.prototype.get = function (key) {
- if (this.has(key))
- return this.dehanceValue(this._data.get(key).get());
- return this.dehanceValue(undefined);
- };
- ObservableMap.prototype.dehanceValue = function (value) {
- if (this.dehancer !== undefined) {
- return this.dehancer(value);
- }
- return value;
- };
- ObservableMap.prototype.keys = function () {
- return this._keys[iteratorSymbol()]();
- };
- ObservableMap.prototype.values = function () {
- var self = this;
- var nextIndex = 0;
- return makeIterable({
- next: function () {
- return nextIndex < self._keys.length
- ? { value: self.get(self._keys[nextIndex++]), done: false }
- : { value: undefined, done: true };
- }
- });
- };
- ObservableMap.prototype.entries = function () {
- var self = this;
- var nextIndex = 0;
- return makeIterable({
- next: function () {
- if (nextIndex < self._keys.length) {
- var key = self._keys[nextIndex++];
- return {
- value: [key, self.get(key)],
- done: false
- };
- }
- return { done: true };
- }
- });
- };
- ObservableMap.prototype.forEach = function (callback, thisArg) {
- var _this = this;
- this._keys.forEach(function (key) { return callback.call(thisArg, _this.get(key), key, _this); });
- };
-
- ObservableMap.prototype.merge = function (other) {
- var _this = this;
- if (isObservableMap(other)) {
- other = other.toJS();
- }
- transaction(function () {
- if (isPlainObject(other))
- Object.keys(other).forEach(function (key) { return _this.set(key, other[key]); });
- else if (Array.isArray(other))
- other.forEach(function (_a) {
- var _b = __read(_a, 2), key = _b[0], value = _b[1];
- return _this.set(key, value);
- });
- else if (isES6Map(other)) {
- if (other.constructor !== Map)
- fail("Cannot initialize from classes that inherit from Map: " + other.constructor.name);
- else
- other.forEach(function (value, key) { return _this.set(key, value); });
- }
- else if (other !== null && other !== undefined)
- fail("Cannot initialize map from " + other);
- });
- return this;
- };
- ObservableMap.prototype.clear = function () {
- var _this = this;
- transaction(function () {
- untracked(function () {
- _this._keys.slice().forEach(function (key) { return _this.delete(key); });
- });
- });
- };
- ObservableMap.prototype.replace = function (values) {
- var _this = this;
- transaction(function () {
- var replacementMap = convertToMap(values);
- var oldKeys = _this._keys;
- var newKeys = Array.from(replacementMap.keys());
- var keysChanged = false;
- for (var i = 0; i < oldKeys.length; i++) {
- var oldKey = oldKeys[i];
-
- if (oldKeys.length === newKeys.length && oldKey !== newKeys[i]) {
- keysChanged = true;
- }
-
- if (!replacementMap.has(oldKey)) {
- keysChanged = true;
- _this.delete(oldKey);
- }
- }
- replacementMap.forEach(function (value, key) {
-
- if (!_this._data.has(key)) {
- keysChanged = true;
- }
- _this.set(key, value);
- });
- if (keysChanged) {
- _this._keys.replace(newKeys);
- }
- });
- return this;
- };
- Object.defineProperty(ObservableMap.prototype, "size", {
- get: function () {
- return this._keys.length;
- },
- enumerable: true,
- configurable: true
- });
-
- ObservableMap.prototype.toPOJO = function () {
- var _this = this;
- var res = {};
- this._keys.forEach(function (key) { return (res[typeof key === "symbol" ? key : stringifyKey(key)] = _this.get(key)); });
- return res;
- };
-
- ObservableMap.prototype.toJS = function () {
- var _this = this;
- var res = new Map();
- this._keys.forEach(function (key) { return res.set(key, _this.get(key)); });
- return res;
- };
- ObservableMap.prototype.toJSON = function () {
-
- return this.toPOJO();
- };
- ObservableMap.prototype.toString = function () {
- var _this = this;
- return (this.name +
- "[{ " +
- this._keys.map(function (key) { return stringifyKey(key) + ": " + ("" + _this.get(key)); }).join(", ") +
- " }]");
- };
-
- ObservableMap.prototype.observe = function (listener, fireImmediately) {
- process.env.NODE_ENV !== "production" &&
- invariant(fireImmediately !== true, "`observe` doesn't support fireImmediately=true in combination with maps.");
- return registerListener(this, listener);
- };
- ObservableMap.prototype.intercept = function (handler) {
- return registerInterceptor(this, handler);
- };
- return ObservableMap;
- }());
- function stringifyKey(key) {
- if (key && key.toString)
- return key.toString();
- else
- return new String(key).toString();
- }
- declareIterator(ObservableMap.prototype, function () {
- return this.entries();
- });
- addHiddenFinalProp(ObservableMap.prototype, toStringTagSymbol(), "Map");
-
- var isObservableMap = createInstanceofPredicate("ObservableMap", ObservableMap);
- var ObservableSetMarker = {};
- var ObservableSet = (function () {
- function ObservableSet(initialData, enhancer, name) {
- if (enhancer === void 0) { enhancer = deepEnhancer; }
- if (name === void 0) { name = "ObservableSet@" + getNextId(); }
- this.name = name;
- this.$mobx = ObservableSetMarker;
- this._data = new Set();
- this._atom = createAtom(this.name);
- if (typeof Set !== "function") {
- throw new Error("mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js");
- }
- this.enhancer = function (newV, oldV) { return enhancer(newV, oldV, name); };
- if (initialData) {
- this.replace(initialData);
- }
- }
- ObservableSet.prototype.dehanceValue = function (value) {
- if (this.dehancer !== undefined) {
- return this.dehancer(value);
- }
- return value;
- };
- ObservableSet.prototype.clear = function () {
- var _this = this;
- transaction(function () {
- untracked(function () {
- _this._data.forEach(function (value) {
- _this.delete(value);
- });
- });
- });
- };
- ObservableSet.prototype.forEach = function (callbackFn, thisArg) {
- var _this = this;
- this._data.forEach(function (value) {
- callbackFn.call(thisArg, value, value, _this);
- });
- };
- Object.defineProperty(ObservableSet.prototype, "size", {
- get: function () {
- this._atom.reportObserved();
- return this._data.size;
- },
- enumerable: true,
- configurable: true
- });
- ObservableSet.prototype.add = function (value) {
- var _this = this;
- checkIfStateModificationsAreAllowed(this._atom);
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- type: "add",
- object: this,
- newValue: value
- });
- if (!change)
- return this;
-
-
- }
- if (!this.has(value)) {
- transaction(function () {
- _this._data.add(_this.enhancer(value, undefined));
- _this._atom.reportChanged();
- });
- var notifySpy = isSpyEnabled();
- var notify = hasListeners(this);
- var change = notify || notifySpy
- ? {
- type: "add",
- object: this,
- newValue: value
- }
- : null;
- if (notifySpy && process.env.NODE_ENV !== "production")
- spyReportStart(change);
- if (notify)
- notifyListeners(this, change);
- if (notifySpy && process.env.NODE_ENV !== "production")
- spyReportEnd();
- }
- return this;
- };
- ObservableSet.prototype.delete = function (value) {
- var _this = this;
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- type: "delete",
- object: this,
- oldValue: value
- });
- if (!change)
- return false;
- }
- if (this.has(value)) {
- var notifySpy = isSpyEnabled();
- var notify = hasListeners(this);
- var change = notify || notifySpy
- ? {
- type: "delete",
- object: this,
- oldValue: value
- }
- : null;
- if (notifySpy && process.env.NODE_ENV !== "production")
- spyReportStart(__assign(__assign({}, change), { name: this.name }));
- transaction(function () {
- _this._atom.reportChanged();
- _this._data.delete(value);
- });
- if (notify)
- notifyListeners(this, change);
- if (notifySpy && process.env.NODE_ENV !== "production")
- spyReportEnd();
- return true;
- }
- return false;
- };
- ObservableSet.prototype.has = function (value) {
- this._atom.reportObserved();
- return this._data.has(this.dehanceValue(value));
- };
- ObservableSet.prototype.entries = function () {
- var nextIndex = 0;
- var keys = iteratorToArray(this.keys());
- var values = iteratorToArray(this.values());
- return makeIterable({
- next: function () {
- var index = nextIndex;
- nextIndex += 1;
- return index < values.length
- ? { value: [keys[index], values[index]], done: false }
- : { done: true };
- }
- });
- };
- ObservableSet.prototype.keys = function () {
- return this.values();
- };
- ObservableSet.prototype.values = function () {
- this._atom.reportObserved();
- var self = this;
- var nextIndex = 0;
- var observableValues;
- if (this._data.values !== undefined) {
- observableValues = iteratorToArray(this._data.values());
- }
- else {
-
- observableValues = [];
- this._data.forEach(function (e) { return observableValues.push(e); });
- }
- return makeIterable({
- next: function () {
- return nextIndex < observableValues.length
- ? { value: self.dehanceValue(observableValues[nextIndex++]), done: false }
- : { done: true };
- }
- });
- };
- ObservableSet.prototype.replace = function (other) {
- var _this = this;
- if (isObservableSet(other)) {
- other = other.toJS();
- }
- transaction(function () {
- if (Array.isArray(other)) {
- _this.clear();
- other.forEach(function (value) { return _this.add(value); });
- }
- else if (isES6Set(other)) {
- _this.clear();
- other.forEach(function (value) { return _this.add(value); });
- }
- else if (other !== null && other !== undefined) {
- fail("Cannot initialize set from " + other);
- }
- });
- return this;
- };
- ObservableSet.prototype.observe = function (listener, fireImmediately) {
-
- process.env.NODE_ENV !== "production" &&
- invariant(fireImmediately !== true, "`observe` doesn't support fireImmediately=true in combination with sets.");
- return registerListener(this, listener);
- };
- ObservableSet.prototype.intercept = function (handler) {
- return registerInterceptor(this, handler);
- };
- ObservableSet.prototype.toJS = function () {
- return new Set(this);
- };
- ObservableSet.prototype.toString = function () {
- return this.name + "[ " + iteratorToArray(this.keys()).join(", ") + " ]";
- };
- return ObservableSet;
- }());
- declareIterator(ObservableSet.prototype, function () {
- return this.values();
- });
- addHiddenFinalProp(ObservableSet.prototype, toStringTagSymbol(), "Set");
- var isObservableSet = createInstanceofPredicate("ObservableSet", ObservableSet);
- var ObservableObjectAdministration = (function () {
- function ObservableObjectAdministration(target, name, defaultEnhancer) {
- this.target = target;
- this.name = name;
- this.defaultEnhancer = defaultEnhancer;
- this.values = {};
- }
- ObservableObjectAdministration.prototype.read = function (owner, key) {
- if (process.env.NODE_ENV === "production" && this.target !== owner) {
- this.illegalAccess(owner, key);
- if (!this.values[key])
- return undefined;
- }
- return this.values[key].get();
- };
- ObservableObjectAdministration.prototype.write = function (owner, key, newValue) {
- var instance = this.target;
- if (process.env.NODE_ENV === "production" && instance !== owner) {
- this.illegalAccess(owner, key);
- }
- var observable = this.values[key];
- if (observable instanceof ComputedValue) {
- observable.set(newValue);
- return;
- }
-
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- type: "update",
- object: instance,
- name: key,
- newValue: newValue
- });
- if (!change)
- return;
- newValue = change.newValue;
- }
- newValue = observable.prepareNewValue(newValue);
-
- if (newValue !== globalState.UNCHANGED) {
- var notify = hasListeners(this);
- var notifySpy = isSpyEnabled();
- var change = notify || notifySpy
- ? {
- type: "update",
- object: instance,
- oldValue: observable.value,
- name: key,
- newValue: newValue
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: this.name, key: key }));
- observable.setNewValue(newValue);
- if (notify)
- notifyListeners(this, change);
- if (notifySpy)
- spyReportEnd();
- }
- };
- ObservableObjectAdministration.prototype.remove = function (key) {
- if (!this.values[key])
- return;
- var target = this.target;
- if (hasInterceptors(this)) {
- var change = interceptChange(this, {
- object: target,
- name: key,
- type: "remove"
- });
- if (!change)
- return;
- }
- try {
- startBatch();
- var notify = hasListeners(this);
- var notifySpy = isSpyEnabled();
- var oldValue = this.values[key].get();
- if (this.keys)
- this.keys.remove(key);
- delete this.values[key];
- delete this.target[key];
- var change = notify || notifySpy
- ? {
- type: "remove",
- object: target,
- oldValue: oldValue,
- name: key
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: this.name, key: key }));
- if (notify)
- notifyListeners(this, change);
- if (notifySpy)
- spyReportEnd();
- }
- finally {
- endBatch();
- }
- };
- ObservableObjectAdministration.prototype.illegalAccess = function (owner, propName) {
-
- console.warn("Property '" + propName + "' of '" + owner + "' was accessed through the prototype chain. Use 'decorate' instead to declare the prop or access it statically through it's owner");
- };
-
- ObservableObjectAdministration.prototype.observe = function (callback, fireImmediately) {
- process.env.NODE_ENV !== "production" &&
- invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects.");
- return registerListener(this, callback);
- };
- ObservableObjectAdministration.prototype.intercept = function (handler) {
- return registerInterceptor(this, handler);
- };
- ObservableObjectAdministration.prototype.getKeys = function () {
- var _this = this;
- if (this.keys === undefined) {
- this.keys = (new ObservableArray(Object.keys(this.values).filter(function (key) { return _this.values[key] instanceof ObservableValue; }), referenceEnhancer, "keys(" + this.name + ")", true));
- }
- return this.keys.slice();
- };
- return ObservableObjectAdministration;
- }());
- function asObservableObject(target, name, defaultEnhancer) {
- if (name === void 0) { name = ""; }
- if (defaultEnhancer === void 0) { defaultEnhancer = deepEnhancer; }
- var adm = target.$mobx;
- if (adm)
- return adm;
- process.env.NODE_ENV !== "production" &&
- invariant(Object.isExtensible(target), "Cannot make the designated object observable; it is not extensible");
- if (!isPlainObject(target))
- name = (target.constructor.name || "ObservableObject") + "@" + getNextId();
- if (!name)
- name = "ObservableObject@" + getNextId();
- adm = new ObservableObjectAdministration(target, name, defaultEnhancer);
- addHiddenFinalProp(target, "$mobx", adm);
- return adm;
- }
- function defineObservableProperty(target, propName, newValue, enhancer) {
- var adm = asObservableObject(target);
- assertPropertyConfigurable(target, propName);
- if (hasInterceptors(adm)) {
- var change = interceptChange(adm, {
- object: target,
- name: propName,
- type: "add",
- newValue: newValue
- });
- if (!change)
- return;
- newValue = change.newValue;
- }
- var observable = (adm.values[propName] = new ObservableValue(newValue, enhancer, adm.name + "." + propName, false));
- newValue = observable.value;
- Object.defineProperty(target, propName, generateObservablePropConfig(propName));
- if (adm.keys)
- adm.keys.push(propName);
- notifyPropertyAddition(adm, target, propName, newValue);
- }
- function defineComputedProperty(target, // which objects holds the observable and provides `this` context?
- propName, options) {
- var adm = asObservableObject(target);
- options.name = adm.name + "." + propName;
- options.context = target;
- adm.values[propName] = new ComputedValue(options);
- Object.defineProperty(target, propName, generateComputedPropConfig(propName));
- }
- var observablePropertyConfigs = Object.create(null);
- var computedPropertyConfigs = Object.create(null);
- function generateObservablePropConfig(propName) {
- return (observablePropertyConfigs[propName] ||
- (observablePropertyConfigs[propName] = {
- configurable: true,
- enumerable: true,
- get: function () {
- return this.$mobx.read(this, propName);
- },
- set: function (v) {
- this.$mobx.write(this, propName, v);
- }
- }));
- }
- function getAdministrationForComputedPropOwner(owner) {
- var adm = owner.$mobx;
- if (!adm) {
-
-
- initializeInstance(owner);
- return owner.$mobx;
- }
- return adm;
- }
- function generateComputedPropConfig(propName) {
- return (computedPropertyConfigs[propName] ||
- (computedPropertyConfigs[propName] = {
- configurable: globalState.computedConfigurable,
- enumerable: false,
- get: function () {
- return getAdministrationForComputedPropOwner(this).read(this, propName);
- },
- set: function (v) {
- getAdministrationForComputedPropOwner(this).write(this, propName, v);
- }
- }));
- }
- function notifyPropertyAddition(adm, object, key, newValue) {
- var notify = hasListeners(adm);
- var notifySpy = isSpyEnabled();
- var change = notify || notifySpy
- ? {
- type: "add",
- object: object,
- name: key,
- newValue: newValue
- }
- : null;
- if (notifySpy)
- spyReportStart(__assign(__assign({}, change), { name: adm.name, key: key }));
- if (notify)
- notifyListeners(adm, change);
- if (notifySpy)
- spyReportEnd();
- }
- var isObservableObjectAdministration = createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration);
- function isObservableObject(thing) {
- if (isObject(thing)) {
-
- initializeInstance(thing);
- return isObservableObjectAdministration(thing.$mobx);
- }
- return false;
- }
- function getAtom(thing, property) {
- if (typeof thing === "object" && thing !== null) {
- if (isObservableArray(thing)) {
- if (property !== undefined)
- fail(process.env.NODE_ENV !== "production" &&
- "It is not possible to get index atoms from arrays");
- return thing.$mobx.atom;
- }
- if (isObservableSet(thing)) {
- return thing.$mobx;
- }
- if (isObservableMap(thing)) {
- var anyThing = thing;
- if (property === undefined)
- return getAtom(anyThing._keys);
- var observable = anyThing._data.get(property) || anyThing._hasMap.get(property);
- if (!observable)
- fail(process.env.NODE_ENV !== "production" &&
- "the entry '" + property + "' does not exist in the observable map '" + getDebugName(thing) + "'");
- return observable;
- }
-
- initializeInstance(thing);
- if (property && !thing.$mobx)
- thing[property];
- if (isObservableObject(thing)) {
- if (!property)
- return fail(process.env.NODE_ENV !== "production" && "please specify a property");
- var observable = thing.$mobx.values[property];
- if (!observable)
- fail(process.env.NODE_ENV !== "production" &&
- "no observable property '" + property + "' found on the observable object '" + getDebugName(thing) + "'");
- return observable;
- }
- if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {
- return thing;
- }
- }
- else if (typeof thing === "function") {
- if (isReaction(thing.$mobx)) {
-
- return thing.$mobx;
- }
- }
- return fail(process.env.NODE_ENV !== "production" && "Cannot obtain atom from " + thing);
- }
- function getAdministration(thing, property) {
- if (!thing)
- fail("Expecting some object");
- if (property !== undefined)
- return getAdministration(getAtom(thing, property));
- if (isAtom(thing) || isComputedValue(thing) || isReaction(thing))
- return thing;
- if (isObservableMap(thing) || isObservableSet(thing))
- return thing;
-
- initializeInstance(thing);
- if (thing.$mobx)
- return thing.$mobx;
- fail(process.env.NODE_ENV !== "production" && "Cannot obtain administration from " + thing);
- }
- function getDebugName(thing, property) {
- var named;
- if (property !== undefined)
- named = getAtom(thing, property);
- else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing))
- named = getAdministration(thing);
- else
- named = getAtom(thing);
- return named.name;
- }
- var toString = Object.prototype.toString;
- function deepEqual(a, b, depth) {
- if (depth === void 0) { depth = -1; }
- return eq(a, b, depth);
- }
-
-
- function eq(a, b, depth, aStack, bStack) {
-
-
- if (a === b)
- return a !== 0 || 1 / a === 1 / b;
-
- if (a == null || b == null)
- return false;
-
- if (a !== a)
- return b !== b;
-
- var type = typeof a;
- if (type !== "function" && type !== "object" && typeof b != "object")
- return false;
-
- a = unwrap(a);
- b = unwrap(b);
-
- var className = toString.call(a);
- if (className !== toString.call(b))
- return false;
- switch (className) {
-
- case "[object RegExp]":
-
- case "[object String]":
-
-
- return "" + a === "" + b;
- case "[object Number]":
-
-
- if (+a !== +a)
- return +b !== +b;
-
- return +a === 0 ? 1 / +a === 1 / b : +a === +b;
- case "[object Date]":
- case "[object Boolean]":
-
-
-
- return +a === +b;
- case "[object Symbol]":
- return (
-
- typeof Symbol !== "undefined" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b));
- }
- var areArrays = className === "[object Array]";
- if (!areArrays) {
- if (typeof a != "object" || typeof b != "object")
- return false;
-
-
- var aCtor = a.constructor, bCtor = b.constructor;
- if (aCtor !== bCtor &&
- !(typeof aCtor === "function" &&
- aCtor instanceof aCtor &&
- typeof bCtor === "function" &&
- bCtor instanceof bCtor) &&
- ("constructor" in a && "constructor" in b)) {
- return false;
- }
- }
- if (depth === 0) {
- return false;
- }
- else if (depth < 0) {
- depth = -1;
- }
-
-
-
-
- aStack = aStack || [];
- bStack = bStack || [];
- var length = aStack.length;
- while (length--) {
-
-
- if (aStack[length] === a)
- return bStack[length] === b;
- }
-
- aStack.push(a);
- bStack.push(b);
-
- if (areArrays) {
-
- length = a.length;
- if (length !== b.length)
- return false;
-
- while (length--) {
- if (!eq(a[length], b[length], depth - 1, aStack, bStack))
- return false;
- }
- }
- else {
-
- var keys = Object.keys(a);
- var key = void 0;
- length = keys.length;
-
- if (Object.keys(b).length !== length)
- return false;
- while (length--) {
-
- key = keys[length];
- if (!(has$1(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack)))
- return false;
- }
- }
-
- aStack.pop();
- bStack.pop();
- return true;
- }
- function unwrap(a) {
- if (isObservableArray(a))
- return a.peek();
- if (isES6Map(a) || isObservableMap(a))
- return iteratorToArray(a.entries());
- if (isES6Set(a) || isObservableSet(a))
- return iteratorToArray(a.entries());
- return a;
- }
- function has$1(a, key) {
- return Object.prototype.hasOwnProperty.call(a, key);
- }
-
-
- try {
-
-
-
-
- process.env.NODE_ENV;
- }
- catch (e) {
- var g = getGlobal();
- if (typeof process === "undefined")
- g.process = {};
- g.process.env = {};
- }
- (function () {
- function testCodeMinification() { }
- if (testCodeMinification.name !== "testCodeMinification" &&
- process.env.NODE_ENV !== "production" &&
- process.env.IGNORE_MOBX_MINIFY_WARNING !== "true") {
-
- var varName = ["process", "env", "NODE_ENV"].join(".");
- console.warn("[mobx] you are running a minified build, but '" + varName + "' was not set to 'production' in your bundler. This results in an unnecessarily large and slow bundle");
- }
- })();
-
- var $mobx = "$mobx";
- if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") {
-
- __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({
- spy: spy,
- extras: {
- getDebugName: getDebugName
- },
- $mobx: $mobx
- });
- }
-
- if (process.env.NODE_ENV !== "production" &&
- typeof module !== "undefined" &&
- typeof module.exports !== "undefined") {
- var warnedAboutDefaultExport_1 = false;
- Object.defineProperty(module.exports, "default", {
- enumerable: false,
- get: function () {
- if (!warnedAboutDefaultExport_1) {
- warnedAboutDefaultExport_1 = true;
- console.warn("The MobX package does not have a default export. Use 'import { thing } from \"mobx\"' (recommended) or 'import * as mobx from \"mobx\"' instead.\"");
- }
- return undefined;
- }
- });
- [
- "extras",
- "Atom",
- "BaseAtom",
- "asFlat",
- "asMap",
- "asReference",
- "asStructure",
- "autorunAsync",
- "createTranformer",
- "expr",
- "isModifierDescriptor",
- "isStrictModeEnabled",
- "map",
- "useStrict",
- "whyRun"
- ].forEach(function (prop) {
- Object.defineProperty(module.exports, prop, {
- enumerable: false,
- get: function () {
- fail("'" + prop + "' is no longer part of the public MobX api. Please consult the changelog to find out where this functionality went");
- },
- set: function () { }
- });
- });
- }
- exports.$mobx = $mobx;
- exports.FlowCancellationError = FlowCancellationError;
- exports.ObservableMap = ObservableMap;
- exports.ObservableSet = ObservableSet;
- exports.Reaction = Reaction;
- exports._allowStateChanges = allowStateChanges;
- exports._allowStateChangesInsideComputed = allowStateChangesInsideComputed;
- exports._endAction = _endAction;
- exports._getAdministration = getAdministration;
- exports._getGlobalState = getGlobalState;
- exports._interceptReads = interceptReads;
- exports._isComputingDerivation = isComputingDerivation;
- exports._resetGlobalState = resetGlobalState;
- exports._startAction = _startAction;
- exports.action = action;
- exports.autorun = autorun;
- exports.comparer = comparer;
- exports.computed = computed;
- exports.configure = configure;
- exports.createAtom = createAtom;
- exports.decorate = decorate;
- exports.entries = entries;
- exports.extendObservable = extendObservable;
- exports.extendShallowObservable = extendShallowObservable;
- exports.flow = flow;
- exports.get = get;
- exports.getAtom = getAtom;
- exports.getDebugName = getDebugName;
- exports.getDependencyTree = getDependencyTree;
- exports.getObserverTree = getObserverTree;
- exports.has = has;
- exports.intercept = intercept;
- exports.isAction = isAction;
- exports.isArrayLike = isArrayLike;
- exports.isBoxedObservable = isObservableValue;
- exports.isComputed = isComputed;
- exports.isComputedProp = isComputedProp;
- exports.isFlowCancellationError = isFlowCancellationError;
- exports.isObservable = isObservable;
- exports.isObservableArray = isObservableArray;
- exports.isObservableMap = isObservableMap;
- exports.isObservableObject = isObservableObject;
- exports.isObservableProp = isObservableProp;
- exports.isObservableSet = isObservableSet;
- exports.keys = keys;
- exports.observable = observable;
- exports.observe = observe;
- exports.onBecomeObserved = onBecomeObserved;
- exports.onBecomeUnobserved = onBecomeUnobserved;
- exports.onReactionError = onReactionError;
- exports.reaction = reaction;
- exports.remove = remove;
- exports.runInAction = runInAction;
- exports.set = set;
- exports.spy = spy;
- exports.toJS = toJS;
- exports.trace = trace;
- exports.transaction = transaction;
- exports.untracked = untracked;
- exports.values = values;
- exports.when = when;
- Object.defineProperty(exports, '__esModule', { value: true });
- }));
|