From e60b36c9c78ff9871be1bd324831343c279dd69f Mon Sep 17 00:00:00 2001 From: Egor Gorbachev <7gorbachevm@gmail.com> Date: Sun, 13 Feb 2022 09:38:12 +0300 Subject: [PATCH] Apply 'curly' ESLint rule + run Prettier on changed files (#3294) --- .eslintrc.js | 1 + packages/mobx-react/src/utils/utils.ts | 8 +- packages/mobx/src/api/action.ts | 11 +- packages/mobx/src/api/annotation.ts | 3 +- packages/mobx/src/api/autorun.ts | 30 +++-- packages/mobx/src/api/computed.ts | 7 +- packages/mobx/src/api/configure.ts | 8 +- packages/mobx/src/api/extendobservable.ts | 16 ++- packages/mobx/src/api/extras.ts | 6 +- packages/mobx/src/api/flow.ts | 15 ++- packages/mobx/src/api/intercept-read.ts | 6 +- packages/mobx/src/api/intercept.ts | 7 +- packages/mobx/src/api/iscomputed.ts | 14 ++- packages/mobx/src/api/isobservable.ts | 14 ++- packages/mobx/src/api/makeObservable.ts | 6 +- packages/mobx/src/api/object-api.ts | 46 +++++--- packages/mobx/src/api/observable.ts | 32 ++++-- packages/mobx/src/api/observe.ts | 6 +- packages/mobx/src/api/tojs.ts | 10 +- packages/mobx/src/api/trace.ts | 8 +- packages/mobx/src/api/when.ts | 17 ++- packages/mobx/src/core/action.ts | 11 +- packages/mobx/src/core/computedvalue.ts | 38 ++++-- packages/mobx/src/core/derivation.ts | 34 ++++-- packages/mobx/src/core/globalstate.ts | 25 ++-- packages/mobx/src/core/observable.ts | 19 ++- packages/mobx/src/core/reaction.ts | 21 +++- packages/mobx/src/core/spy.ts | 27 +++-- packages/mobx/src/types/actionannotation.ts | 4 +- packages/mobx/src/types/dynamicobject.ts | 14 ++- packages/mobx/src/types/flowannotation.ts | 4 +- packages/mobx/src/types/intercept-utils.ts | 12 +- .../mobx/src/types/legacyobservablearray.ts | 7 +- packages/mobx/src/types/listen-utils.ts | 8 +- packages/mobx/src/types/modifiers.ts | 53 ++++++--- packages/mobx/src/types/observablearray.ts | 108 +++++++++++++----- packages/mobx/src/types/observablemap.ts | 78 +++++++++---- packages/mobx/src/types/observableobject.ts | 70 +++++++++--- packages/mobx/src/types/observableset.ts | 39 +++++-- packages/mobx/src/types/observablevalue.ts | 18 ++- packages/mobx/src/types/type-utils.ts | 44 +++++-- packages/mobx/src/utils/comparer.ts | 8 +- packages/mobx/src/utils/eq.ts | 60 +++++++--- packages/mobx/src/utils/utils.ts | 38 ++++-- 44 files changed, 733 insertions(+), 278 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index d87fb45f1..b0e009e16 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -15,6 +15,7 @@ module.exports = { rules: { "no-fallthrough": "off", "no-constant-condition": "off", + curly: "error", "getter-return": "off", "no-console": "off", "no-var": "error", diff --git a/packages/mobx-react/src/utils/utils.ts b/packages/mobx-react/src/utils/utils.ts index 9b7a8323f..c79efa456 100644 --- a/packages/mobx-react/src/utils/utils.ts +++ b/packages/mobx-react/src/utils/utils.ts @@ -18,13 +18,17 @@ export function newSymbol(name: string): symbol | string { export function shallowEqual(objA: any, objB: any): boolean { //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js - if (is(objA, objB)) return true + if (is(objA, objB)) { + return true + } if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) { return false } const keysA = Object.keys(objA) const keysB = Object.keys(objB) - if (keysA.length !== keysB.length) return false + if (keysA.length !== keysB.length) { + return false + } for (let i = 0; i < keysA.length; i++) { if (!Object.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false diff --git a/packages/mobx/src/api/action.ts b/packages/mobx/src/api/action.ts index 377e9a0d1..ab5e38601 100644 --- a/packages/mobx/src/api/action.ts +++ b/packages/mobx/src/api/action.ts @@ -45,10 +45,13 @@ export interface IActionFactory extends Annotation, PropertyDecorator { function createActionFactory(autoAction: boolean): IActionFactory { const res: IActionFactory = function action(arg1, arg2?): any { // action(fn() {}) - if (isFunction(arg1)) + if (isFunction(arg1)) { return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction) + } // action("name", fn() {}) - if (isFunction(arg2)) return createAction(arg1, arg2, autoAction) + if (isFunction(arg2)) { + return createAction(arg1, arg2, autoAction) + } // @action if (isStringish(arg2)) { return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation) @@ -63,7 +66,9 @@ function createActionFactory(autoAction: boolean): IActionFactory { ) } - if (__DEV__) die("Invalid arguments for `action`") + if (__DEV__) { + die("Invalid arguments for `action`") + } } as IActionFactory return res } diff --git a/packages/mobx/src/api/annotation.ts b/packages/mobx/src/api/annotation.ts index 12949a81f..87a9ea607 100644 --- a/packages/mobx/src/api/annotation.ts +++ b/packages/mobx/src/api/annotation.ts @@ -32,8 +32,7 @@ export type AnnotationMapEntry = // declare annotations for private/ protected members, see #2339 export type AnnotationsMap = { [P in Exclude]?: AnnotationMapEntry -} & - Record +} & Record export function isAnnotation(thing: any) { return ( diff --git a/packages/mobx/src/api/autorun.ts b/packages/mobx/src/api/autorun.ts index 01ed02657..1ddc23e4b 100644 --- a/packages/mobx/src/api/autorun.ts +++ b/packages/mobx/src/api/autorun.ts @@ -38,8 +38,12 @@ export function autorun( opts: IAutorunOptions = EMPTY_OBJECT ): IReactionDisposer { if (__DEV__) { - if (!isFunction(view)) die("Autorun expects a function as first argument") - if (isAction(view)) die("Autorun does not accept actions since actions are untrackable") + if (!isFunction(view)) { + die("Autorun expects a function as first argument") + } + if (isAction(view)) { + die("Autorun does not accept actions since actions are untrackable") + } } const name: string = @@ -69,7 +73,9 @@ export function autorun( isScheduled = true scheduler(() => { isScheduled = false - if (!reaction.isDisposed_) reaction.track(reactionRunner) + if (!reaction.isDisposed_) { + reaction.track(reactionRunner) + } }) } }, @@ -111,9 +117,12 @@ export function reaction( opts: IReactionOptions = EMPTY_OBJECT ): IReactionDisposer { if (__DEV__) { - if (!isFunction(expression) || !isFunction(effect)) + if (!isFunction(expression) || !isFunction(effect)) { die("First and second argument to reaction should be functions") - if (!isPlainObject(opts)) die("Third argument of reactions should be an object") + } + if (!isPlainObject(opts)) { + die("Third argument of reactions should be an object") + } } const name = opts.name ?? (__DEV__ ? "Reaction@" + getNextId() : "Reaction") const effectAction = action( @@ -148,7 +157,9 @@ export function reaction( function reactionRunner() { isScheduled = false - if (r.isDisposed_) return + if (r.isDisposed_) { + return + } let changed: boolean = false r.track(() => { const nextValue = allowStateChanges(false, () => expression(r)) @@ -159,8 +170,11 @@ export function reaction( // This casting is nesessary as TS cannot infer proper type in current funciton implementation type OldValue = FireImmediately extends true ? T | undefined : T - if (firstTime && opts.fireImmediately!) effectAction(value, oldValue as OldValue, r) - else if (!firstTime && changed) effectAction(value, oldValue as OldValue, r) + if (firstTime && opts.fireImmediately!) { + effectAction(value, oldValue as OldValue, r) + } else if (!firstTime && changed) { + effectAction(value, oldValue as OldValue, r) + } firstTime = false } diff --git a/packages/mobx/src/api/computed.ts b/packages/mobx/src/api/computed.ts index e6ee0bf81..104932bd3 100644 --- a/packages/mobx/src/api/computed.ts +++ b/packages/mobx/src/api/computed.ts @@ -46,11 +46,14 @@ export const computed: IComputedFactory = function computed(arg1, arg2) { // computed(expr, options?) if (__DEV__) { - if (!isFunction(arg1)) die("First argument to `computed` should be an expression.") - if (isFunction(arg2)) + if (!isFunction(arg1)) { + die("First argument to `computed` should be an expression.") + } + if (isFunction(arg2)) { die( "A setter as second argument is no longer supported, use `{ set: fn }` option instead" ) + } } const opts: IComputedValueOptions = isPlainObject(arg2) ? arg2 : {} opts.get = arg1 diff --git a/packages/mobx/src/api/configure.ts b/packages/mobx/src/api/configure.ts index 60a08621b..cfabf9f2d 100644 --- a/packages/mobx/src/api/configure.ts +++ b/packages/mobx/src/api/configure.ts @@ -34,7 +34,9 @@ export function configure(options: { ? false : typeof Proxy !== "undefined" } - if (useProxies === "ifavailable") globalState.verifyProxies = true + if (useProxies === "ifavailable") { + globalState.verifyProxies = true + } if (enforceActions !== undefined) { const ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED globalState.enforceActions = ea @@ -47,7 +49,9 @@ export function configure(options: { "disableErrorBoundaries", "safeDescriptors" ].forEach(key => { - if (key in options) globalState[key] = !!options[key] + if (key in options) { + globalState[key] = !!options[key] + } }) globalState.allowStateReads = !globalState.observableRequiresReaction if (__DEV__ && globalState.disableErrorBoundaries === true) { diff --git a/packages/mobx/src/api/extendobservable.ts b/packages/mobx/src/api/extendobservable.ts index 4d6576fff..7b223152a 100644 --- a/packages/mobx/src/api/extendobservable.ts +++ b/packages/mobx/src/api/extendobservable.ts @@ -21,15 +21,21 @@ export function extendObservable( options?: CreateObservableOptions ): A & B { if (__DEV__) { - if (arguments.length > 4) die("'extendObservable' expected 2-4 arguments") - if (typeof target !== "object") + if (arguments.length > 4) { + die("'extendObservable' expected 2-4 arguments") + } + if (typeof target !== "object") { die("'extendObservable' expects an object as first argument") - if (isObservableMap(target)) + } + if (isObservableMap(target)) { die("'extendObservable' should not be used on maps, use map.merge instead") - if (!isPlainObject(properties)) + } + if (!isPlainObject(properties)) { die(`'extendObservable' only accepts plain objects as second argument`) - if (isObservable(properties) || isObservable(annotations)) + } + if (isObservable(properties) || isObservable(annotations)) { die(`Extending an object with another observable (object) is not supported`) + } } // Pull descriptors first, so we don't have to deal with props added by administration ($mobx) const descriptors = getOwnPropertyDescriptors(properties) diff --git a/packages/mobx/src/api/extras.ts b/packages/mobx/src/api/extras.ts index 3bab07929..5a7bd40fe 100644 --- a/packages/mobx/src/api/extras.ts +++ b/packages/mobx/src/api/extras.ts @@ -18,8 +18,9 @@ function nodeToDependencyTree(node: IDepTreeNode): IDependencyTree { const result: IDependencyTree = { name: node.name_ } - if (node.observing_ && node.observing_.length > 0) + if (node.observing_ && node.observing_.length > 0) { result.dependencies = unique(node.observing_).map(nodeToDependencyTree) + } return result } @@ -31,8 +32,9 @@ function nodeToObserverTree(node: IDepTreeNode): IObserverTree { const result: IObserverTree = { name: node.name_ } - if (hasObservers(node as any)) + if (hasObservers(node as any)) { result.observers = Array.from(getObservers(node as any)).map(nodeToObserverTree) + } return result } diff --git a/packages/mobx/src/api/flow.ts b/packages/mobx/src/api/flow.ts index d7eb804e5..daad7a7e5 100644 --- a/packages/mobx/src/api/flow.ts +++ b/packages/mobx/src/api/flow.ts @@ -42,8 +42,9 @@ export const flow: Flow = Object.assign( return storeAnnotation(arg1, arg2, flowAnnotation) } // flow(fn) - if (__DEV__ && arguments.length !== 1) + if (__DEV__ && arguments.length !== 1) { die(`Flow expects single argument with generator function`) + } const generator = arg1 const name = generator.name || "" @@ -95,7 +96,9 @@ export const flow: Flow = Object.assign( ret.then(next, reject) return } - if (ret.done) return resolve(ret.value) + if (ret.done) { + return resolve(ret.value) + } pendingPromise = Promise.resolve(ret.value) as any return pendingPromise!.then(onFulfilled, onRejected) } @@ -105,7 +108,9 @@ export const flow: Flow = Object.assign( promise.cancel = action(`${name} - runid: ${runId} - cancel`, function () { try { - if (pendingPromise) cancelPromise(pendingPromise) + if (pendingPromise) { + cancelPromise(pendingPromise) + } // Finally block can return (or yield) stuff.. const res = gen.return!(undefined as any) // eat anything that promise would do, it's cancelled! @@ -129,7 +134,9 @@ export const flow: Flow = Object.assign( flow.bound = createDecoratorAnnotation(flowBoundAnnotation) function cancelPromise(promise) { - if (isFunction(promise.cancel)) promise.cancel() + if (isFunction(promise.cancel)) { + promise.cancel() + } } export function flowResult( diff --git a/packages/mobx/src/api/intercept-read.ts b/packages/mobx/src/api/intercept-read.ts index d1ef39f32..1a741b2b9 100644 --- a/packages/mobx/src/api/intercept-read.ts +++ b/packages/mobx/src/api/intercept-read.ts @@ -39,16 +39,18 @@ export function interceptReads(thing, propOrHandler?, handler?): Lambda { if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) { target = getAdministration(thing) } else if (isObservableObject(thing)) { - if (__DEV__ && !isStringish(propOrHandler)) + if (__DEV__ && !isStringish(propOrHandler)) { return die( `InterceptReads can only be used with a specific property, not with an object in general` ) + } target = getAdministration(thing, propOrHandler) } else if (__DEV__) { return die(`Expected observable map, object or array as first array`) } - if (__DEV__ && target.dehancer !== undefined) + if (__DEV__ && target.dehancer !== undefined) { return die(`An intercept reader was already established`) + } target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler return () => { target.dehancer = undefined diff --git a/packages/mobx/src/api/intercept.ts b/packages/mobx/src/api/intercept.ts index 08fe78e33..d72f4604e 100644 --- a/packages/mobx/src/api/intercept.ts +++ b/packages/mobx/src/api/intercept.ts @@ -43,8 +43,11 @@ export function intercept( handler: IInterceptor> ): Lambda export function intercept(thing, propOrHandler?, handler?): Lambda { - if (isFunction(handler)) return interceptProperty(thing, propOrHandler, handler) - else return interceptInterceptable(thing, propOrHandler) + if (isFunction(handler)) { + return interceptProperty(thing, propOrHandler, handler) + } else { + return interceptInterceptable(thing, propOrHandler) + } } function interceptInterceptable(thing, handler) { diff --git a/packages/mobx/src/api/iscomputed.ts b/packages/mobx/src/api/iscomputed.ts index d4b3eeb86..692da37e3 100644 --- a/packages/mobx/src/api/iscomputed.ts +++ b/packages/mobx/src/api/iscomputed.ts @@ -4,22 +4,28 @@ export function _isComputed(value, property?: PropertyKey): boolean { if (property === undefined) { return isComputedValue(value) } - if (isObservableObject(value) === false) return false - if (!value[$mobx].values_.has(property)) return false + if (isObservableObject(value) === false) { + return false + } + if (!value[$mobx].values_.has(property)) { + return false + } const atom = getAtom(value, property) return isComputedValue(atom) } export function isComputed(value: any): boolean { - if (__DEV__ && arguments.length > 1) + if (__DEV__ && arguments.length > 1) { return die( `isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property` ) + } return _isComputed(value) } export function isComputedProp(value: any, propName: PropertyKey): boolean { - if (__DEV__ && !isStringish(propName)) + if (__DEV__ && !isStringish(propName)) { return die(`isComputed expected a property name as second argument`) + } return _isComputed(value, propName) } diff --git a/packages/mobx/src/api/isobservable.ts b/packages/mobx/src/api/isobservable.ts index 9cf461025..0aab5643d 100644 --- a/packages/mobx/src/api/isobservable.ts +++ b/packages/mobx/src/api/isobservable.ts @@ -11,12 +11,15 @@ import { } from "../internal" function _isObservable(value, property?: PropertyKey): boolean { - if (!value) return false + if (!value) { + return false + } if (property !== undefined) { - if (__DEV__ && (isObservableMap(value) || isObservableArray(value))) + if (__DEV__ && (isObservableMap(value) || isObservableArray(value))) { return die( "isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead." ) + } if (isObservableObject(value)) { return value[$mobx].values_.has(property) } @@ -33,14 +36,17 @@ function _isObservable(value, property?: PropertyKey): boolean { } export function isObservable(value: any): boolean { - if (__DEV__ && arguments.length !== 1) + if (__DEV__ && arguments.length !== 1) { die( `isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property` ) + } return _isObservable(value) } export function isObservableProp(value: any, propName: PropertyKey): boolean { - if (__DEV__ && !isStringish(propName)) return die(`expected a property name as second argument`) + if (__DEV__ && !isStringish(propName)) { + return die(`expected a property name as second argument`) + } return _isObservable(value, propName) } diff --git a/packages/mobx/src/api/makeObservable.ts b/packages/mobx/src/api/makeObservable.ts index 96e870055..afdd49d7c 100644 --- a/packages/mobx/src/api/makeObservable.ts +++ b/packages/mobx/src/api/makeObservable.ts @@ -56,10 +56,12 @@ export function makeAutoObservable(set: ObservableSet): ReadonlyArray export function keys(obj: T): ReadonlyArray export function keys(obj: any): any { if (isObservableObject(obj)) { - return (((obj as any) as IIsObservableObject)[ - $mobx - ] as ObservableObjectAdministration).keys_() + return ( + (obj as any as IIsObservableObject)[$mobx] as ObservableObjectAdministration + ).keys_() } if (isObservableMap(obj) || isObservableSet(obj)) { return Array.from(obj.keys()) @@ -86,26 +86,36 @@ export function set(obj: any, key: any, value?: any): void { startBatch() const values = key try { - for (let key in values) set(obj, key, values[key]) + for (let key in values) { + set(obj, key, values[key]) + } } finally { endBatch() } return } if (isObservableObject(obj)) { - ;((obj as any) as IIsObservableObject)[$mobx].set_(key, value) + ;(obj as any as IIsObservableObject)[$mobx].set_(key, value) } 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) - if (key < 0) die(`Invalid index: '${key}'`) + if (typeof key !== "number") { + key = parseInt(key, 10) + } + if (key < 0) { + die(`Invalid index: '${key}'`) + } startBatch() - if (key >= obj.length) obj.length = key + 1 + if (key >= obj.length) { + obj.length = key + 1 + } obj[key] = value endBatch() - } else die(8) + } else { + die(8) + } } export function remove(obj: ObservableMap, key: K) @@ -114,13 +124,15 @@ export function remove(obj: IObservableArray, index: number) export function remove(obj: T, key: string) export function remove(obj: any, key: any): void { if (isObservableObject(obj)) { - ;((obj as any) as IIsObservableObject)[$mobx].delete_(key) + ;(obj as any as IIsObservableObject)[$mobx].delete_(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) + if (typeof key !== "number") { + key = parseInt(key, 10) + } obj.splice(key, 1) } else { die(9) @@ -133,7 +145,7 @@ export function has(obj: IObservableArray, index: number): boolean export function has(obj: T, key: string): boolean export function has(obj: any, key: any): boolean { if (isObservableObject(obj)) { - return ((obj as any) as IIsObservableObject)[$mobx].has_(key) + return (obj as any as IIsObservableObject)[$mobx].has_(key) } else if (isObservableMap(obj)) { return obj.has(key) } else if (isObservableSet(obj)) { @@ -148,9 +160,11 @@ export function get(obj: ObservableMap, key: K): V | undefined export function get(obj: IObservableArray, index: number): T | undefined export function get(obj: T, key: string): any export function get(obj: any, key: any): any { - if (!has(obj, key)) return undefined + if (!has(obj, key)) { + return undefined + } if (isObservableObject(obj)) { - return ((obj as any) as IIsObservableObject)[$mobx].get_(key) + return (obj as any as IIsObservableObject)[$mobx].get_(key) } else if (isObservableMap(obj)) { return obj.get(key) } else if (isObservableArray(obj)) { @@ -161,14 +175,14 @@ export function get(obj: any, key: any): any { export function apiDefineProperty(obj: Object, key: PropertyKey, descriptor: PropertyDescriptor) { if (isObservableObject(obj)) { - return ((obj as any) as IIsObservableObject)[$mobx].defineProperty_(key, descriptor) + return (obj as any as IIsObservableObject)[$mobx].defineProperty_(key, descriptor) } die(39) } export function apiOwnKeys(obj: Object) { if (isObservableObject(obj)) { - return ((obj as any) as IIsObservableObject)[$mobx].ownKeys_() + return (obj as any as IIsObservableObject)[$mobx].ownKeys_() } die(38) } diff --git a/packages/mobx/src/api/observable.ts b/packages/mobx/src/api/observable.ts index 67bd9194a..9967a6d00 100644 --- a/packages/mobx/src/api/observable.ts +++ b/packages/mobx/src/api/observable.ts @@ -102,22 +102,34 @@ function createObservable(v: any, arg2?: any, arg3?: any) { } // already observable - ignore - if (isObservable(v)) return v + if (isObservable(v)) { + return v + } // plain object - if (isPlainObject(v)) return observable.object(v, arg2, arg3) + if (isPlainObject(v)) { + return observable.object(v, arg2, arg3) + } // Array - if (Array.isArray(v)) return observable.array(v, arg2) + if (Array.isArray(v)) { + return observable.array(v, arg2) + } // Map - if (isES6Map(v)) return observable.map(v, arg2) + if (isES6Map(v)) { + return observable.map(v, arg2) + } // Set - if (isES6Set(v)) return observable.set(v, arg2) + if (isES6Set(v)) { + return observable.set(v, arg2) + } // other object - ignore - if (typeof v === "object" && v !== null) return v + if (typeof v === "object" && v !== null) { + return v + } // anything else return observable.box(v, arg2) @@ -169,9 +181,11 @@ const observableFactories: IObservableFactory = { }, array(initialValues?: T[], options?: CreateObservableOptions): IObservableArray { const o = asCreateObservableOptions(options) - return (globalState.useProxies === false || o.proxy === false - ? createLegacyArray - : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name) + return ( + globalState.useProxies === false || o.proxy === false + ? createLegacyArray + : createObservableArray + )(initialValues, getEnhancerFromOptions(o), o.name) }, map( initialValues?: IObservableMapInitialValues, diff --git a/packages/mobx/src/api/observe.ts b/packages/mobx/src/api/observe.ts index abfcf674b..13656c80d 100644 --- a/packages/mobx/src/api/observe.ts +++ b/packages/mobx/src/api/observe.ts @@ -53,9 +53,11 @@ export function observe( fireImmediately?: boolean ): Lambda export function observe(thing, propOrCb?, cbOrFire?, fireImmediately?): Lambda { - if (isFunction(cbOrFire)) + if (isFunction(cbOrFire)) { return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately) - else return observeObservable(thing, propOrCb, cbOrFire) + } else { + return observeObservable(thing, propOrCb, cbOrFire) + } } function observeObservable(thing, listener, fireImmediately: boolean) { diff --git a/packages/mobx/src/api/tojs.ts b/packages/mobx/src/api/tojs.ts index 4fab1e24b..2cc927b36 100644 --- a/packages/mobx/src/api/tojs.ts +++ b/packages/mobx/src/api/tojs.ts @@ -21,11 +21,13 @@ function toJSHelper(source, __alreadySeen: Map) { typeof source !== "object" || source instanceof Date || !isObservable(source) - ) + ) { return source + } - if (isObservableValue(source) || isComputedValue(source)) + if (isObservableValue(source) || isComputedValue(source)) { return toJSHelper(source.get(), __alreadySeen) + } if (__alreadySeen.has(source)) { return __alreadySeen.get(source) } @@ -68,6 +70,8 @@ function toJSHelper(source, __alreadySeen: Map) { * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib. */ export function toJS(source: T, options?: any): T { - if (__DEV__ && options) die("toJS no longer supports options") + if (__DEV__ && options) { + die("toJS no longer supports options") + } return toJSHelper(source, new Map()) } diff --git a/packages/mobx/src/api/trace.ts b/packages/mobx/src/api/trace.ts index ba35c5867..297014f54 100644 --- a/packages/mobx/src/api/trace.ts +++ b/packages/mobx/src/api/trace.ts @@ -4,9 +4,13 @@ export function trace(thing?: any, prop?: string, enterBreakPoint?: boolean): vo export function trace(thing?: any, enterBreakPoint?: boolean): void export function trace(enterBreakPoint?: boolean): void export function trace(...args: any[]): void { - if (!__DEV__) die(`trace() is not available in production builds`) + if (!__DEV__) { + die(`trace() is not available in production builds`) + } let enterBreakPoint = false - if (typeof args[args.length - 1] === "boolean") enterBreakPoint = args.pop() + if (typeof args[args.length - 1] === "boolean") { + enterBreakPoint = args.pop() + } const derivation = getAtomFromArgs(args) if (!derivation) { return die( diff --git a/packages/mobx/src/api/when.ts b/packages/mobx/src/api/when.ts index 9e75b456c..4c0439635 100644 --- a/packages/mobx/src/api/when.ts +++ b/packages/mobx/src/api/when.ts @@ -25,8 +25,9 @@ export function when( opts?: IWhenOptions ): IReactionDisposer export function when(predicate: any, arg1?: any, arg2?: any): any { - if (arguments.length === 1 || (arg1 && typeof arg1 === "object")) + if (arguments.length === 1 || (arg1 && typeof arg1 === "object")) { return whenPromise(predicate, arg1) + } return _when(predicate, arg1, arg2 || {}) } @@ -37,8 +38,11 @@ function _when(predicate: () => boolean, effect: Lambda, opts: IWhenOptions): IR timeoutHandle = setTimeout(() => { if (!disposer[$mobx].isDisposed_) { disposer() - if (opts.onError) opts.onError(error) - else throw error + if (opts.onError) { + opts.onError(error) + } else { + throw error + } } }, opts.timeout) } @@ -54,7 +58,9 @@ function _when(predicate: () => boolean, effect: Lambda, opts: IWhenOptions): IR let cond = allowStateChanges(false, predicate) if (cond) { r.dispose() - if (timeoutHandle) clearTimeout(timeoutHandle) + if (timeoutHandle) { + clearTimeout(timeoutHandle) + } effectAction() } }, opts) @@ -65,8 +71,9 @@ function whenPromise( predicate: () => boolean, opts?: IWhenOptions ): Promise & { cancel(): void } { - if (__DEV__ && opts && opts.onError) + if (__DEV__ && opts && opts.onError) { return die(`the options 'onError' and 'promise' cannot be combined`) + } let cancel const res = new Promise((resolve, reject) => { let disposer = _when(predicate, resolve as Lambda, { ...opts, onError: reject }) diff --git a/packages/mobx/src/core/action.ts b/packages/mobx/src/core/action.ts index efb9c19fb..22fde33de 100644 --- a/packages/mobx/src/core/action.ts +++ b/packages/mobx/src/core/action.ts @@ -38,9 +38,12 @@ export function createAction( ref?: Object ): Function { if (__DEV__) { - if (!isFunction(fn)) die("`action` can only be invoked on functions") - if (typeof actionName !== "string" || !actionName) + if (!isFunction(fn)) { + die("`action` can only be invoked on functions") + } + if (typeof actionName !== "string" || !actionName) { die(`actions should have valid names, got: '${actionName}'`) + } } function res() { return executeAction(actionName, autoAction, fn, ref || this, arguments) @@ -136,7 +139,9 @@ export function _endAction(runInfo: IActionRunInfo) { allowStateChangesEnd(runInfo.prevAllowStateChanges_) allowStateReadsEnd(runInfo.prevAllowStateReads_) endBatch() - if (runInfo.runAsAction_) untrackedEnd(runInfo.prevDerivation_) + if (runInfo.runAsAction_) { + untrackedEnd(runInfo.prevDerivation_) + } if (__DEV__ && runInfo.notifySpy_) { spyReportEnd({ time: Date.now() - runInfo.startTime_ }) } diff --git a/packages/mobx/src/core/computedvalue.ts b/packages/mobx/src/core/computedvalue.ts index c3a4b247d..264a1918d 100644 --- a/packages/mobx/src/core/computedvalue.ts +++ b/packages/mobx/src/core/computedvalue.ts @@ -114,7 +114,9 @@ export class ComputedValue implements IObservable, IComputedValue, IDeriva * This is useful for working with vectors, mouse coordinates etc. */ constructor(options: IComputedValueOptions) { - if (!options.get) die(31) + if (!options.get) { + die(31) + } this.derivation = options.get! this.name_ = options.name || (__DEV__ ? "ComputedValue@" + getNextId() : "ComputedValue") if (options.set) { @@ -157,7 +159,9 @@ export class ComputedValue implements IObservable, IComputedValue, IDeriva * Will evaluate its computation first if needed. */ public get(): T { - if (this.isComputing_) die(32, this.name_, this.derivation) + if (this.isComputing_) { + die(32, this.name_, this.derivation) + } if ( globalState.inBatch === 0 && // !globalState.trackingDerivatpion && @@ -174,27 +178,37 @@ export class ComputedValue implements IObservable, IComputedValue, IDeriva reportObserved(this) if (shouldCompute(this)) { let prevTrackingContext = globalState.trackingContext - if (this.keepAlive_ && !prevTrackingContext) globalState.trackingContext = this - if (this.trackAndCompute()) propagateChangeConfirmed(this) + if (this.keepAlive_ && !prevTrackingContext) { + globalState.trackingContext = this + } + if (this.trackAndCompute()) { + propagateChangeConfirmed(this) + } globalState.trackingContext = prevTrackingContext } } const result = this.value_! - if (isCaughtException(result)) throw result.cause + if (isCaughtException(result)) { + throw result.cause + } return result } public set(value: T) { if (this.setter_) { - if (this.isRunningSetter_) die(33, this.name_) + if (this.isRunningSetter_) { + die(33, this.name_) + } this.isRunningSetter_ = true try { this.setter_.call(this.scope_, value) } finally { this.isRunningSetter_ = false } - } else die(34, this.name_) + } else { + die(34, this.name_) + } } trackAndCompute(): boolean { @@ -287,13 +301,19 @@ export class ComputedValue implements IObservable, IComputedValue, IDeriva } warnAboutUntrackedRead_() { - if (!__DEV__) return + if (!__DEV__) { + return + } if (this.isTracing_ !== TraceMode.NONE) { console.log( `[mobx.trace] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.` ) } - if (typeof this.requiresReaction_ === "boolean" ? this.requiresReaction_ : globalState.computedRequiresReaction) { + if ( + typeof this.requiresReaction_ === "boolean" + ? this.requiresReaction_ + : globalState.computedRequiresReaction + ) { console.warn( `[mobx] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.` ) diff --git a/packages/mobx/src/core/derivation.ts b/packages/mobx/src/core/derivation.ts index 20bb4d1b2..7f97bc23f 100644 --- a/packages/mobx/src/core/derivation.ts +++ b/packages/mobx/src/core/derivation.ts @@ -137,7 +137,10 @@ export function checkIfStateModificationsAreAllowed(atom: IAtom) { } const hasObservers = atom.observers_.size > 0 // Should not be possible to change observed state outside strict mode, except during initialization, see #563 - if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === "always")) + if ( + !globalState.allowStateChanges && + (hasObservers || globalState.enforceActions === "always") + ) { console.warn( "[MobX] " + (globalState.enforceActions @@ -145,6 +148,7 @@ export function checkIfStateModificationsAreAllowed(atom: IAtom) { : "Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: ") + atom.name_ ) + } } export function checkIfStateReadsAreAllowed(observable: IObservable) { @@ -191,9 +195,13 @@ export function trackDerivedFunction(derivation: IDerivation, f: () => T, con } function warnAboutDerivationWithoutDependencies(derivation: IDerivation) { - if (!__DEV__) return + if (!__DEV__) { + return + } - if (derivation.observing_.length !== 0) return + if (derivation.observing_.length !== 0) { + return + } if (globalState.reactionRequiresObservable || derivation.requiresObservable_) { console.warn( @@ -222,14 +230,16 @@ function bindDependencies(derivation: IDerivation) { const dep = observing[i] if (dep.diffValue_ === 0) { dep.diffValue_ = 1 - if (i0 !== i) observing[i0] = dep + if (i0 !== i) { + observing[i0] = dep + } i0++ } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined, // not hitting the condition - if (((dep as any) as IDerivation).dependenciesState_ > lowestNewObservingDerivationState) { - lowestNewObservingDerivationState = ((dep as any) as IDerivation).dependenciesState_ + if ((dep as any as IDerivation).dependenciesState_ > lowestNewObservingDerivationState) { + lowestNewObservingDerivationState = (dep as any as IDerivation).dependenciesState_ } } observing.length = i0 @@ -272,7 +282,9 @@ export function clearObserving(derivation: IDerivation) { const obs = derivation.observing_ derivation.observing_ = [] let i = obs.length - while (i--) removeObserver(obs[i], derivation) + while (i--) { + removeObserver(obs[i], derivation) + } derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_ } @@ -311,10 +323,14 @@ export function allowStateReadsEnd(prev: boolean) { * */ export function changeDependenciesStateTo0(derivation: IDerivation) { - if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) return + if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { + return + } derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_ const obs = derivation.observing_ let i = obs.length - while (i--) obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_ + while (i--) { + obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_ + } } diff --git a/packages/mobx/src/core/globalstate.ts b/packages/mobx/src/core/globalstate.ts index e80de5510..35de9dfea 100644 --- a/packages/mobx/src/core/globalstate.ts +++ b/packages/mobx/src/core/globalstate.ts @@ -157,9 +157,12 @@ let isolateCalled = false export let globalState: MobXGlobals = (function () { let global = getGlobal() - if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) canMergeGlobalState = false - if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) + if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) { canMergeGlobalState = false + } + if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) { + canMergeGlobalState = false + } if (!canMergeGlobalState) { // Because this is a IIFE we need to let isolateCalled a chance to change @@ -172,7 +175,9 @@ export let globalState: MobXGlobals = (function () { return new MobXGlobals() } else if (global.__mobxGlobals) { global.__mobxInstanceCount += 1 - if (!global.__mobxGlobals.UNCHANGED) global.__mobxGlobals.UNCHANGED = {} // make merge backward compatible + if (!global.__mobxGlobals.UNCHANGED) { + global.__mobxGlobals.UNCHANGED = {} + } // make merge backward compatible return global.__mobxGlobals } else { global.__mobxInstanceCount = 1 @@ -185,12 +190,15 @@ export function isolateGlobalState() { globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions - ) + ) { die(36) + } isolateCalled = true if (canMergeGlobalState) { let global = getGlobal() - if (--global.__mobxInstanceCount === 0) global.__mobxGlobals = undefined + if (--global.__mobxInstanceCount === 0) { + global.__mobxGlobals = undefined + } globalState = new MobXGlobals() } } @@ -205,7 +213,10 @@ export function getGlobalState(): any { */ export function resetGlobalState() { const defaultGlobals = new MobXGlobals() - for (let key in defaultGlobals) - if (persistentKeys.indexOf(key as any) === -1) globalState[key] = defaultGlobals[key] + for (let key in defaultGlobals) { + if (persistentKeys.indexOf(key as any) === -1) { + globalState[key] = defaultGlobals[key] + } + } globalState.allowStateChanges = !globalState.enforceActions } diff --git a/packages/mobx/src/core/observable.ts b/packages/mobx/src/core/observable.ts index 88a77df85..af6741e04 100644 --- a/packages/mobx/src/core/observable.ts +++ b/packages/mobx/src/core/observable.ts @@ -69,8 +69,9 @@ export function addObserver(observable: IObservable, node: IDerivation) { // invariantObservers(observable); observable.observers_.add(node) - if (observable.lowestObserverState_ > node.dependenciesState_) + if (observable.lowestObserverState_ > node.dependenciesState_) { observable.lowestObserverState_ = node.dependenciesState_ + } // invariantObservers(observable); // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR didn't add node"); @@ -183,7 +184,9 @@ export function reportObserved(observable: IObservable): boolean { // Called by Atom when its value changes export function propagateChanged(observable: IObservable) { // invariantLOS(observable, "changed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return + if (observable.lowestObserverState_ === IDerivationState_.STALE_) { + return + } observable.lowestObserverState_ = IDerivationState_.STALE_ // Ideally we use for..of here, but the downcompiled version is really slow... @@ -202,7 +205,9 @@ export function propagateChanged(observable: IObservable) { // Called by ComputedValue when it recalculate and its value changed export function propagateChangeConfirmed(observable: IObservable) { // invariantLOS(observable, "confirmed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return + if (observable.lowestObserverState_ === IDerivationState_.STALE_) { + return + } observable.lowestObserverState_ = IDerivationState_.STALE_ observable.observers_.forEach(d => { @@ -223,7 +228,9 @@ export function propagateChangeConfirmed(observable: IObservable) { // Used by computed when its dependency changed, but we don't wan't to immediately recompute. export function propagateMaybeChanged(observable: IObservable) { // invariantLOS(observable, "maybe start"); - if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) return + if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) { + return + } observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_ observable.observers_.forEach(d => { @@ -269,5 +276,7 @@ function printDepTree(tree: IDependencyTree, lines: string[], depth: number) { return } lines.push(`${"\t".repeat(depth - 1)}${tree.name}`) - if (tree.dependencies) tree.dependencies.forEach(child => printDepTree(child, lines, depth + 1)) + if (tree.dependencies) { + tree.dependencies.forEach(child => printDepTree(child, lines, depth + 1)) + } } diff --git a/packages/mobx/src/core/reaction.ts b/packages/mobx/src/core/reaction.ts index 1af0db8ed..113a408b5 100644 --- a/packages/mobx/src/core/reaction.ts +++ b/packages/mobx/src/core/reaction.ts @@ -142,7 +142,9 @@ export class Reaction implements IDerivation, IReactionPublic { // disposed during last run. Clean up everything that was bound after the dispose call. clearObserving(this) } - if (isCaughtException(result)) this.reportExceptionInDerivation_(result.cause) + if (isCaughtException(result)) { + this.reportExceptionInDerivation_(result.cause) + } if (__DEV__ && notify) { spyReportEnd({ time: Date.now() - startTime @@ -157,7 +159,9 @@ export class Reaction implements IDerivation, IReactionPublic { return } - if (globalState.disableErrorBoundaries) throw error + if (globalState.disableErrorBoundaries) { + throw error + } const message = __DEV__ ? `[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'` @@ -165,7 +169,7 @@ export class Reaction implements IDerivation, IReactionPublic { if (!globalState.suppressReactionErrors) { console.error(message, error) /** If debugging brought you here, please, read the above message :-). Tnx! */ - } else if (__DEV__) console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`) // prettier-ignore + } else if (__DEV__) {console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`)} // prettier-ignore if (__DEV__ && isSpyEnabled()) { spyReport({ @@ -210,7 +214,9 @@ export function onReactionError(handler: (error: any, derivation: IDerivation) = globalState.globalReactionErrorHandlers.push(handler) return () => { const idx = globalState.globalReactionErrorHandlers.indexOf(handler) - if (idx >= 0) globalState.globalReactionErrorHandlers.splice(idx, 1) + if (idx >= 0) { + globalState.globalReactionErrorHandlers.splice(idx, 1) + } } } @@ -225,7 +231,9 @@ let reactionScheduler: (fn: () => void) => void = f => f() export function runReactions() { // Trampolining, if runReactions are already running, new reactions will be picked up - if (globalState.inBatch > 0 || globalState.isRunningReactions) return + if (globalState.inBatch > 0 || globalState.isRunningReactions) { + return + } reactionScheduler(runReactionsHelper) } @@ -248,8 +256,9 @@ function runReactionsHelper() { allReactions.splice(0) // clear reactions } let remainingReactions = allReactions.splice(0) - for (let i = 0, l = remainingReactions.length; i < l; i++) + for (let i = 0, l = remainingReactions.length; i < l; i++) { remainingReactions[i].runReaction_() + } } globalState.isRunningReactions = false } diff --git a/packages/mobx/src/core/spy.ts b/packages/mobx/src/core/spy.ts index 6e6dd8e5d..2267c5cf0 100644 --- a/packages/mobx/src/core/spy.ts +++ b/packages/mobx/src/core/spy.ts @@ -25,14 +25,22 @@ export type PureSpyEvent = type SpyEvent = PureSpyEvent & { spyReportStart?: true } export function spyReport(event: SpyEvent) { - if (!__DEV__) return // dead code elimination can do the rest - if (!globalState.spyListeners.length) return + if (!__DEV__) { + return + } // dead code elimination can do the rest + if (!globalState.spyListeners.length) { + return + } const listeners = globalState.spyListeners - for (let i = 0, l = listeners.length; i < l; i++) listeners[i](event) + for (let i = 0, l = listeners.length; i < l; i++) { + listeners[i](event) + } } export function spyReportStart(event: PureSpyEvent) { - if (!__DEV__) return + if (!__DEV__) { + return + } const change = { ...event, spyReportStart: true as const } spyReport(change) } @@ -40,9 +48,14 @@ export function spyReportStart(event: PureSpyEvent) { const END_EVENT: SpyEvent = { type: "report-end", spyReportEnd: true } export function spyReportEnd(change?: { time?: number }) { - if (!__DEV__) return - if (change) spyReport({ ...change, type: "report-end", spyReportEnd: true }) - else spyReport(END_EVENT) + if (!__DEV__) { + return + } + if (change) { + spyReport({ ...change, type: "report-end", spyReportEnd: true }) + } else { + spyReport(END_EVENT) + } } export function spy(listener: (change: SpyEvent) => void): Lambda { diff --git a/packages/mobx/src/types/actionannotation.ts b/packages/mobx/src/types/actionannotation.ts index 6ed5bad66..7385c108b 100644 --- a/packages/mobx/src/types/actionannotation.ts +++ b/packages/mobx/src/types/actionannotation.ts @@ -67,7 +67,7 @@ function assertActionDescriptor( if (__DEV__ && !isFunction(value)) { die( `Cannot apply '${annotationType_}' to '${adm.name_}.${key.toString()}':` + - `\n'${annotationType_}' can only be used on properties with a function value.` + `\n'${annotationType_}' can only be used on properties with a function value.` ) } } @@ -91,7 +91,7 @@ export function createActionDescriptor( value, annotation.options_?.autoAction ?? false, // https://github.com/mobxjs/mobx/discussions/3140 - annotation.options_?.bound ? (adm.proxy_ ?? adm.target_) : undefined, + annotation.options_?.bound ? adm.proxy_ ?? adm.target_ : undefined ), // Non-configurable for classes // prevents accidental field redefinition in subclass diff --git a/packages/mobx/src/types/dynamicobject.ts b/packages/mobx/src/types/dynamicobject.ts index 737eacaee..71598879b 100644 --- a/packages/mobx/src/types/dynamicobject.ts +++ b/packages/mobx/src/types/dynamicobject.ts @@ -19,17 +19,20 @@ function getAdm(target): ObservableObjectAdministration { // and skip either the internal values map, or the base object with its property descriptors! const objectProxyTraps: ProxyHandler = { has(target: IIsObservableObject, name: PropertyKey): boolean { - if (__DEV__ && globalState.trackingDerivation) + if (__DEV__ && globalState.trackingDerivation) { warnAboutProxyRequirement( "detect new properties using the 'in' operator. Use 'has' from 'mobx' instead." ) + } return getAdm(target).has_(name) }, get(target: IIsObservableObject, name: PropertyKey): any { return getAdm(target).get_(name) }, set(target: IIsObservableObject, name: PropertyKey, value: any): boolean { - if (!isStringish(name)) return false + if (!isStringish(name)) { + return false + } if (__DEV__ && !getAdm(target).values_.has(name)) { warnAboutProxyRequirement( "add a new observable property through direct assignment. Use 'set' from 'mobx' instead." @@ -44,7 +47,9 @@ const objectProxyTraps: ProxyHandler = { "delete properties from an observable object. Use 'remove' from 'mobx' instead." ) } - if (!isStringish(name)) return false + if (!isStringish(name)) { + return false + } // null (intercepted) -> true (success) return getAdm(target).delete_(name, true) ?? true }, @@ -62,10 +67,11 @@ const objectProxyTraps: ProxyHandler = { return getAdm(target).defineProperty_(name, descriptor) ?? true }, ownKeys(target: IIsObservableObject): ArrayLike { - if (__DEV__ && globalState.trackingDerivation) + if (__DEV__ && globalState.trackingDerivation) { warnAboutProxyRequirement( "iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead." ) + } return getAdm(target).ownKeys_() }, preventExtensions(target) { diff --git a/packages/mobx/src/types/flowannotation.ts b/packages/mobx/src/types/flowannotation.ts index 65f80b29d..42d6f3e10 100644 --- a/packages/mobx/src/types/flowannotation.ts +++ b/packages/mobx/src/types/flowannotation.ts @@ -35,7 +35,9 @@ function make_( // prototype // bound - must annotate protos to support super.flow() if (this.options_?.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) { - if (this.extend_(adm, key, descriptor, false) === null) return MakeResult.Cancel + if (this.extend_(adm, key, descriptor, false) === null) { + return MakeResult.Cancel + } } if (isFlow(descriptor.value)) { // A prototype could have been annotated already by other constructor, diff --git a/packages/mobx/src/types/intercept-utils.ts b/packages/mobx/src/types/intercept-utils.ts index daf0fde85..f7619e2ad 100644 --- a/packages/mobx/src/types/intercept-utils.ts +++ b/packages/mobx/src/types/intercept-utils.ts @@ -18,7 +18,9 @@ export function registerInterceptor( interceptors.push(handler) return once(() => { const idx = interceptors.indexOf(handler) - if (idx !== -1) interceptors.splice(idx, 1) + if (idx !== -1) { + interceptors.splice(idx, 1) + } }) } @@ -32,8 +34,12 @@ export function interceptChange( const interceptors = [...(interceptable.interceptors_ || [])] for (let i = 0, l = interceptors.length; i < l; i++) { change = interceptors[i](change) - if (change && !(change as any).type) die(14) - if (!change) break + if (change && !(change as any).type) { + die(14) + } + if (!change) { + break + } } return change } finally { diff --git a/packages/mobx/src/types/legacyobservablearray.ts b/packages/mobx/src/types/legacyobservablearray.ts index ed9f85d73..253f0c177 100644 --- a/packages/mobx/src/types/legacyobservablearray.ts +++ b/packages/mobx/src/types/legacyobservablearray.ts @@ -94,7 +94,9 @@ class LegacyObservableArray extends StubArray { } Object.entries(arrayExtensions).forEach(([prop, fn]) => { - if (prop !== "concat") addHiddenProp(LegacyObservableArray.prototype, prop, fn) + if (prop !== "concat") { + addHiddenProp(LegacyObservableArray.prototype, prop, fn) + } }) function createArrayEntryDescriptor(index: number) { @@ -116,8 +118,9 @@ function createArrayBufferItem(index: number) { export function reserveArrayBuffer(max: number) { if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) { - for (let index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) + for (let index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) { createArrayBufferItem(index) + } OBSERVABLE_ARRAY_BUFFER_SIZE = max } } diff --git a/packages/mobx/src/types/listen-utils.ts b/packages/mobx/src/types/listen-utils.ts index 241311616..453390aea 100644 --- a/packages/mobx/src/types/listen-utils.ts +++ b/packages/mobx/src/types/listen-utils.ts @@ -13,14 +13,18 @@ export function registerListener(listenable: IListenable, handler: Function): La listeners.push(handler) return once(() => { const idx = listeners.indexOf(handler) - if (idx !== -1) listeners.splice(idx, 1) + if (idx !== -1) { + listeners.splice(idx, 1) + } }) } export function notifyListeners(listenable: IListenable, change: T) { const prevU = untrackedStart() let listeners = listenable.changeListeners_ - if (!listeners) return + if (!listeners) { + return + } listeners = listeners.slice() for (let i = 0, l = listeners.length; i < l; i++) { listeners[i](change) diff --git a/packages/mobx/src/types/modifiers.ts b/packages/mobx/src/types/modifiers.ts index 627da4815..d566113ef 100644 --- a/packages/mobx/src/types/modifiers.ts +++ b/packages/mobx/src/types/modifiers.ts @@ -23,13 +23,23 @@ export interface IEnhancer { export function deepEnhancer(v, _, name) { // it is an observable already, done - if (isObservable(v)) return v + if (isObservable(v)) { + return v + } // something that can be converted and mutated? - if (Array.isArray(v)) return observable.array(v, { name }) - if (isPlainObject(v)) return observable.object(v, undefined, { name }) - if (isES6Map(v)) return observable.map(v, { name }) - if (isES6Set(v)) return observable.set(v, { name }) + if (Array.isArray(v)) { + return observable.array(v, { name }) + } + if (isPlainObject(v)) { + return observable.object(v, undefined, { name }) + } + if (isES6Map(v)) { + return observable.map(v, { name }) + } + if (isES6Set(v)) { + return observable.set(v, { name }) + } if (typeof v === "function" && !isAction(v) && !isFlow(v)) { if (isGenerator(v)) { return flow(v) @@ -41,18 +51,30 @@ export function deepEnhancer(v, _, name) { } export function shallowEnhancer(v, _, name): any { - if (v === undefined || v === null) return v - if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) + 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, deep: false }) - if (isPlainObject(v)) return observable.object(v, undefined, { name, deep: false }) - if (isES6Map(v)) return observable.map(v, { name, deep: false }) - if (isES6Set(v)) return observable.set(v, { name, deep: false }) + } + if (Array.isArray(v)) { + return observable.array(v, { name, deep: false }) + } + if (isPlainObject(v)) { + return observable.object(v, undefined, { name, deep: false }) + } + if (isES6Map(v)) { + return observable.map(v, { name, deep: false }) + } + if (isES6Set(v)) { + return observable.set(v, { name, deep: false }) + } - if (__DEV__) + if (__DEV__) { die( "The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets" ) + } } export function referenceEnhancer(newValue?) { @@ -61,8 +83,11 @@ export function referenceEnhancer(newValue?) { } export function refStructEnhancer(v, oldValue): any { - if (__DEV__ && isObservable(v)) + if (__DEV__ && isObservable(v)) { die(`observable.struct should not be used with observable values`) - if (deepEqual(v, oldValue)) return oldValue + } + if (deepEqual(v, oldValue)) { + return oldValue + } return v } diff --git a/packages/mobx/src/types/observablearray.ts b/packages/mobx/src/types/observablearray.ts index f3cccc24b..6c720f2dd 100644 --- a/packages/mobx/src/types/observablearray.ts +++ b/packages/mobx/src/types/observablearray.ts @@ -84,8 +84,12 @@ export interface IArrayWillSplice { const arrayTraps = { get(target, name) { const adm: ObservableArrayAdministration = target[$mobx] - if (name === $mobx) return adm - if (name === "length") return adm.getArrayLength_() + if (name === $mobx) { + return adm + } + if (name === "length") { + return adm.getArrayLength_() + } if (typeof name === "string" && !isNaN(name as any)) { return adm.get_(parseInt(name)) } @@ -113,7 +117,8 @@ const arrayTraps = { } export class ObservableArrayAdministration - implements IInterceptable | IArrayWillSplice>, IListenable { + implements IInterceptable | IArrayWillSplice>, IListenable +{ atom_: IAtom readonly values_: any[] = [] // this is the prop that gets proxied, so can't replace it! interceptors_ @@ -135,13 +140,16 @@ export class ObservableArrayAdministration } dehanceValue_(value: any): any { - if (this.dehancer !== undefined) return this.dehancer(value) + if (this.dehancer !== undefined) { + return this.dehancer(value) + } return value } dehanceValues_(values: any[]): any[] { - if (this.dehancer !== undefined && values.length > 0) + if (this.dehancer !== undefined && values.length > 0) { return values.map(this.dehancer) as any + } return values } @@ -175,36 +183,56 @@ export class ObservableArrayAdministration } setArrayLength_(newLength: number) { - if (typeof newLength !== "number" || isNaN(newLength) || newLength < 0) + if (typeof newLength !== "number" || isNaN(newLength) || newLength < 0) { die("Out of range: " + newLength) + } let currentLength = this.values_.length - if (newLength === currentLength) return - else if (newLength > currentLength) { + if (newLength === currentLength) { + return + } else if (newLength > currentLength) { const newItems = new Array(newLength - currentLength) - for (let i = 0; i < newLength - currentLength; i++) newItems[i] = undefined // No Array.fill everywhere... + for (let i = 0; i < newLength - currentLength; i++) { + newItems[i] = undefined + } // No Array.fill everywhere... this.spliceWithArray_(currentLength, 0, newItems) - } else this.spliceWithArray_(newLength, currentLength - newLength) + } else { + this.spliceWithArray_(newLength, currentLength - newLength) + } } updateArrayLength_(oldLength: number, delta: number) { - if (oldLength !== this.lastKnownLength_) die(16) + if (oldLength !== this.lastKnownLength_) { + die(16) + } this.lastKnownLength_ += delta - if (this.legacyMode_ && delta > 0) reserveArrayBuffer(oldLength + delta + 1) + if (this.legacyMode_ && delta > 0) { + reserveArrayBuffer(oldLength + delta + 1) + } } spliceWithArray_(index: number, deleteCount?: number, newItems?: any[]): any[] { checkIfStateModificationsAreAllowed(this.atom_) const 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 (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 (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 (newItems === undefined) { + newItems = EMPTY_ARRAY + } if (hasInterceptors(this)) { const change = interceptChange>(this as any, { @@ -214,7 +242,9 @@ export class ObservableArrayAdministration removedCount: deleteCount, added: newItems }) - if (!change) return EMPTY_ARRAY + if (!change) { + return EMPTY_ARRAY + } deleteCount = change.removedCount newItems = change.added } @@ -227,8 +257,9 @@ export class ObservableArrayAdministration } const res = this.spliceItemsIntoValues_(index, deleteCount, newItems) - if (deleteCount !== 0 || newItems.length !== 0) + if (deleteCount !== 0 || newItems.length !== 0) { this.notifyArraySplice_(index, newItems, res) + } return this.dehanceValues_(res) } @@ -242,9 +273,12 @@ export class ObservableArrayAdministration let oldItems = this.values_.slice(index + deleteCount) // New length is the previous length + addition count - deletion count this.values_.length += newItems.length - deleteCount - for (let i = 0; i < newItems.length; i++) this.values_[index + i] = newItems[i] - for (let i = 0; i < oldItems.length; i++) + for (let i = 0; i < newItems.length; i++) { + this.values_[index + i] = newItems[i] + } + for (let i = 0; i < oldItems.length; i++) { this.values_[index + newItems.length + i] = oldItems[i] + } return res } } @@ -267,10 +301,16 @@ export class ObservableArrayAdministration // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled - if (__DEV__ && notifySpy) spyReportStart(change!) + if (__DEV__ && notifySpy) { + spyReportStart(change!) + } this.atom_.reportChanged() - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } } notifyArraySplice_(index: number, added: any[], removed: any[]) { @@ -291,11 +331,17 @@ export class ObservableArrayAdministration } as const) : null - if (__DEV__ && notifySpy) spyReportStart(change!) + if (__DEV__ && notifySpy) { + spyReportStart(change!) + } this.atom_.reportChanged() // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } } get_(index: number): any | undefined { @@ -323,7 +369,9 @@ export class ObservableArrayAdministration index, newValue }) - if (!change) return + if (!change) { + return + } newValue = change.newValue } newValue = this.enhancer_(newValue, oldValue) diff --git a/packages/mobx/src/types/observablemap.ts b/packages/mobx/src/types/observablemap.ts index 2899e5406..9b30433e0 100644 --- a/packages/mobx/src/types/observablemap.ts +++ b/packages/mobx/src/types/observablemap.ts @@ -118,7 +118,9 @@ export class ObservableMap } has(key: K): boolean { - if (!globalState.trackingDerivation) return this.has_(key) + if (!globalState.trackingDerivation) { + return this.has_(key) + } let entry = this.hasMap_.get(key) if (!entry) { @@ -144,7 +146,9 @@ export class ObservableMap newValue: value, name: key }) - if (!change) return this + if (!change) { + return this + } value = change.newValue! } if (hasKey) { @@ -163,7 +167,9 @@ export class ObservableMap object: this, name: key }) - if (!change) return false + if (!change) { + return false + } } if (this.has_(key)) { const notifySpy = isSpyEnabled() @@ -180,7 +186,9 @@ export class ObservableMap } : null - if (__DEV__ && notifySpy) spyReportStart(change! as PureSpyEvent) // TODO fix type + if (__DEV__ && notifySpy) { + spyReportStart(change! as PureSpyEvent) + } // TODO fix type transaction(() => { this.keysAtom_.reportChanged() this.hasMap_.get(key)?.setNewValue_(false) @@ -188,8 +196,12 @@ export class ObservableMap observable.setNewValue_(undefined as any) this.data_.delete(key) }) - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } return true } return false @@ -213,10 +225,16 @@ export class ObservableMap newValue } : null - if (__DEV__ && notifySpy) spyReportStart(change! as PureSpyEvent) // TODO fix type + if (__DEV__ && notifySpy) { + spyReportStart(change! as PureSpyEvent) + } // TODO fix type observable.setNewValue_(newValue as V) - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } } } @@ -247,13 +265,21 @@ export class ObservableMap newValue } : null - if (__DEV__ && notifySpy) spyReportStart(change! as PureSpyEvent) // TODO fix type - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (__DEV__ && notifySpy) { + spyReportStart(change! as PureSpyEvent) + } // TODO fix type + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } } get(key: K): V | undefined { - if (this.has(key)) return this.dehanceValue_(this.data_.get(key)!.get()) + if (this.has(key)) { + return this.dehanceValue_(this.data_.get(key)!.get()) + } return this.dehanceValue_(undefined) } @@ -302,7 +328,9 @@ export class ObservableMap } forEach(callback: (value: V, key: K, object: Map) => void, thisArg?) { - for (const [key, value] of this) callback.call(thisArg, value, key, this) + for (const [key, value] of this) { + callback.call(thisArg, value, key, this) + } } /** Merge another object into this object, returns this. */ @@ -311,15 +339,20 @@ export class ObservableMap other = new Map(other) } transaction(() => { - if (isPlainObject(other)) + if (isPlainObject(other)) { getPlainObjectKeys(other).forEach((key: any) => this.set(key as K, (other as IKeyValueMap)[key]) ) - else if (Array.isArray(other)) other.forEach(([key, value]) => this.set(key, value)) - else if (isES6Map(other)) { - if (other.constructor !== Map) die(19, other) + } else if (Array.isArray(other)) { + other.forEach(([key, value]) => this.set(key, value)) + } else if (isES6Map(other)) { + if (other.constructor !== Map) { + die(19, other) + } other.forEach((value, key) => this.set(key, value)) - } else if (other !== null && other !== undefined) die(20, other) + } else if (other !== null && other !== undefined) { + die(20, other) + } }) return this } @@ -327,7 +360,9 @@ export class ObservableMap clear() { transaction(() => { untracked(() => { - for (const key of this.keys()) this.delete(key) + for (const key of this.keys()) { + this.delete(key) + } }) }) } @@ -433,8 +468,9 @@ export class ObservableMap * for callback details */ observe_(listener: (changes: IMapDidChange) => void, fireImmediately?: boolean): Lambda { - if (__DEV__ && fireImmediately === true) + if (__DEV__ && fireImmediately === true) { die("`observe` doesn't support fireImmediately=true in combination with maps.") + } return registerListener(this, listener) } diff --git a/packages/mobx/src/types/observableobject.ts b/packages/mobx/src/types/observableobject.ts index 390bf2f71..1545bc54c 100644 --- a/packages/mobx/src/types/observableobject.ts +++ b/packages/mobx/src/types/observableobject.ts @@ -136,7 +136,9 @@ export class ObservableObjectAdministration name: key, newValue }) - if (!change) return null + if (!change) { + return null + } newValue = (change as any).newValue } newValue = (observable as any).prepareNewValue_(newValue) @@ -158,10 +160,16 @@ export class ObservableObjectAdministration } : null - if (__DEV__ && notifySpy) spyReportStart(change!) + if (__DEV__ && notifySpy) { + spyReportStart(change!) + } ;(observable as ObservableValue).setNewValue_(newValue) - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } } return true } @@ -256,8 +264,12 @@ export class ObservableObjectAdministration const descriptor = getDescriptor(source, key) if (descriptor) { const outcome = annotation.make_(this, key, descriptor, source) - if (outcome === MakeResult.Cancel) return - if (outcome === MakeResult.Break) break + if (outcome === MakeResult.Cancel) { + return + } + if (outcome === MakeResult.Break) { + break + } } source = Object.getPrototypeOf(source) } @@ -320,7 +332,9 @@ export class ObservableObjectAdministration type: ADD, newValue: descriptor.value }) - if (!change) return null + if (!change) { + return null + } const { newValue } = change as any if (descriptor.value !== newValue) { descriptor = { @@ -372,7 +386,9 @@ export class ObservableObjectAdministration type: ADD, newValue: value }) - if (!change) return null + if (!change) { + return null + } value = (change as any).newValue } @@ -434,7 +450,9 @@ export class ObservableObjectAdministration type: ADD, newValue: undefined }) - if (!change) return null + if (!change) { + return null + } } options.name ||= __DEV__ ? `${this.name_}.${key.toString()}` : "ObservableObject.key" options.context = this.proxy_ || this.target_ @@ -485,7 +503,9 @@ export class ObservableObjectAdministration type: REMOVE }) // Cancelled - if (!change) return null + if (!change) { + return null + } } // Delete @@ -539,9 +559,15 @@ export class ObservableObjectAdministration oldValue: value, name: key } - if (__DEV__ && notifySpy) spyReportStart(change!) - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (__DEV__ && notifySpy) { + spyReportStart(change!) + } + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } } } finally { endBatch() @@ -555,8 +581,9 @@ export class ObservableObjectAdministration * for callback details */ observe_(callback: (changes: IObjectDidChange) => void, fireImmediately?: boolean): Lambda { - if (__DEV__ && fireImmediately === true) + if (__DEV__ && fireImmediately === true) { die("`observe` doesn't support the fire immediately property for observable objects.") + } return registerListener(this, callback) } @@ -580,9 +607,15 @@ export class ObservableObjectAdministration } as const) : null - if (__DEV__ && notifySpy) spyReportStart(change!) - if (notify) notifyListeners(this, change) - if (__DEV__ && notifySpy) spyReportEnd() + if (__DEV__ && notifySpy) { + spyReportStart(change!) + } + if (notify) { + notifyListeners(this, change) + } + if (__DEV__ && notifySpy) { + spyReportEnd() + } } this.pendingKeys_?.get(key)?.set(true) @@ -631,8 +664,9 @@ export function asObservableObject( return target } - if (__DEV__ && !Object.isExtensible(target)) + if (__DEV__ && !Object.isExtensible(target)) { die("Cannot make the designated object observable; it is not extensible") + } const name = options?.name ?? diff --git a/packages/mobx/src/types/observableset.ts b/packages/mobx/src/types/observableset.ts index fd6c08863..062829acb 100644 --- a/packages/mobx/src/types/observableset.ts +++ b/packages/mobx/src/types/observableset.ts @@ -96,7 +96,9 @@ export class ObservableSet implements Set, IInterceptable { untracked(() => { - for (const value of this.data_.values()) this.delete(value) + for (const value of this.data_.values()) { + this.delete(value) + } }) }) } @@ -120,7 +122,9 @@ export class ObservableSet implements Set, IInterceptable implements Set, IInterceptable implements Set, IInterceptable implements Set, IInterceptable { this.atom_.reportChanged() this.data_.delete(value) }) - if (notify) notifyListeners(this, change) - if (notifySpy && __DEV__) spyReportEnd() + if (notify) { + notifyListeners(this, change) + } + if (notifySpy && __DEV__) { + spyReportEnd() + } return true } return false @@ -243,8 +261,9 @@ export class ObservableSet implements Set, IInterceptable) => void, fireImmediately?: boolean): Lambda { // ... 'fireImmediately' could also be true? - if (__DEV__ && fireImmediately === true) + if (__DEV__ && fireImmediately === true) { die("`observe` doesn't support fireImmediately=true in combination with sets.") + } return registerListener(this, listener) } diff --git a/packages/mobx/src/types/observablevalue.ts b/packages/mobx/src/types/observablevalue.ts index 12aada6a6..9af56797f 100644 --- a/packages/mobx/src/types/observablevalue.ts +++ b/packages/mobx/src/types/observablevalue.ts @@ -61,7 +61,8 @@ const CREATE = "create" export class ObservableValue extends Atom - implements IObservableValue, IInterceptable>, IListenable { + implements IObservableValue, IInterceptable>, IListenable +{ hasUnreportedChange_ = false interceptors_ changeListeners_ @@ -90,7 +91,9 @@ export class ObservableValue } private dehanceValue(value: T): T { - if (this.dehancer !== undefined) return this.dehancer(value) + if (this.dehancer !== undefined) { + return this.dehancer(value) + } return value } @@ -110,7 +113,9 @@ export class ObservableValue }) } this.setNewValue_(newValue) - if (__DEV__ && notifySpy) spyReportEnd() + if (__DEV__ && notifySpy) { + spyReportEnd() + } } } @@ -122,7 +127,9 @@ export class ObservableValue type: UPDATE, newValue }) - if (!change) return globalState.UNCHANGED + if (!change) { + return globalState.UNCHANGED + } newValue = change.newValue } // apply modifier @@ -154,7 +161,7 @@ export class ObservableValue } observe_(listener: (change: IValueDidChange) => void, fireImmediately?: boolean): Lambda { - if (fireImmediately) + if (fireImmediately) { listener({ observableKind: "value", debugObjectName: this.name_, @@ -163,6 +170,7 @@ export class ObservableValue newValue: this.value_, oldValue: undefined }) + } return registerListener(this, listener) } diff --git a/packages/mobx/src/types/type-utils.ts b/packages/mobx/src/types/type-utils.ts index 039cb9f7a..a85dd327d 100644 --- a/packages/mobx/src/types/type-utils.ts +++ b/packages/mobx/src/types/type-utils.ts @@ -16,23 +16,35 @@ import { export function getAtom(thing: any, property?: PropertyKey): IDepTreeNode { if (typeof thing === "object" && thing !== null) { if (isObservableArray(thing)) { - if (property !== undefined) die(23) + if (property !== undefined) { + die(23) + } return (thing as any)[$mobx].atom_ } if (isObservableSet(thing)) { return (thing as any)[$mobx] } if (isObservableMap(thing)) { - if (property === undefined) return thing.keysAtom_ + if (property === undefined) { + return thing.keysAtom_ + } const observable = thing.data_.get(property) || thing.hasMap_.get(property) - if (!observable) die(25, property, getDebugName(thing)) + if (!observable) { + die(25, property, getDebugName(thing)) + } return observable } - if (property && !thing[$mobx]) thing[property] // See #1072 + if (property && !thing[$mobx]) { + thing[property] + } // See #1072 if (isObservableObject(thing)) { - if (!property) return die(26) + if (!property) { + return die(26) + } const observable = (thing as any)[$mobx].values_.get(property) - if (!observable) die(27, property, getDebugName(thing)) + if (!observable) { + die(27, property, getDebugName(thing)) + } return observable } if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { @@ -48,11 +60,21 @@ export function getAtom(thing: any, property?: PropertyKey): IDepTreeNode { } export function getAdministration(thing: any, property?: string) { - if (!thing) die(29) - if (property !== undefined) return getAdministration(getAtom(thing, property)) - if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) return thing - if (isObservableMap(thing) || isObservableSet(thing)) return thing - if (thing[$mobx]) return thing[$mobx] + if (!thing) { + die(29) + } + if (property !== undefined) { + return getAdministration(getAtom(thing, property)) + } + if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { + return thing + } + if (isObservableMap(thing) || isObservableSet(thing)) { + return thing + } + if (thing[$mobx]) { + return thing[$mobx] + } die(24, thing) } diff --git a/packages/mobx/src/utils/comparer.ts b/packages/mobx/src/utils/comparer.ts index 07928a652..7f560a650 100644 --- a/packages/mobx/src/utils/comparer.ts +++ b/packages/mobx/src/utils/comparer.ts @@ -17,11 +17,11 @@ function shallowComparer(a: any, b: any): boolean { } function defaultComparer(a: any, b: any): boolean { - if (Object.is) return Object.is(a, b) + if (Object.is) { + return Object.is(a, b) + } - return a === b - ? a !== 0 || 1 / a === 1 / b - : a !== a && b !== b + return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b } export const comparer = { diff --git a/packages/mobx/src/utils/eq.ts b/packages/mobx/src/utils/eq.ts index ef16f7c39..46067877a 100644 --- a/packages/mobx/src/utils/eq.ts +++ b/packages/mobx/src/utils/eq.ts @@ -21,18 +21,28 @@ export function deepEqual(a: any, b: any, depth: number = -1): boolean { function eq(a: any, b: any, depth: number, aStack?: any[], bStack?: any[]) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) return a !== 0 || 1 / a === 1 / b + if (a === b) { + return a !== 0 || 1 / a === 1 / b + } // `null` or `undefined` only equal to itself (strict comparison). - if (a == null || b == null) return false + if (a == null || b == null) { + return false + } // `NaN`s are equivalent, but non-reflexive. - if (a !== a) return b !== b + if (a !== a) { + return b !== b + } // Exhaust primitive checks const type = typeof a - if (type !== "function" && type !== "object" && typeof b != "object") return false + if (type !== "function" && type !== "object" && typeof b != "object") { + return false + } // Compare `[[Class]]` names. const className = toString.call(a) - if (className !== toString.call(b)) return false + if (className !== toString.call(b)) { + return false + } switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case "[object RegExp]": @@ -44,7 +54,9 @@ function eq(a: any, b: any, depth: number, aStack?: any[], bStack?: any[]) { case "[object Number]": // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN. - if (+a !== +a) return +b !== +b + if (+a !== +a) { + return +b !== +b + } // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b case "[object Date]": @@ -72,7 +84,9 @@ function eq(a: any, b: any, depth: number, aStack?: any[], bStack?: any[]) { const areArrays = className === "[object Array]" if (!areArrays) { - if (typeof a != "object" || typeof b != "object") return false + if (typeof a != "object" || typeof b != "object") { + return false + } // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. @@ -110,7 +124,9 @@ function eq(a: any, b: any, depth: number, aStack?: any[], bStack?: any[]) { while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. - if (aStack[length] === a) return bStack[length] === b + if (aStack[length] === a) { + return bStack[length] === b + } } // Add the first object to the stack of traversed objects. @@ -121,10 +137,14 @@ function eq(a: any, b: any, depth: number, aStack?: any[], bStack?: any[]) { if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length - if (length !== b.length) return false + if (length !== b.length) { + return false + } // Deep compare the contents, ignoring non-numeric properties. while (length--) { - if (!eq(a[length], b[length], depth - 1, aStack, bStack)) return false + if (!eq(a[length], b[length], depth - 1, aStack, bStack)) { + return false + } } } else { // Deep compare objects. @@ -132,11 +152,15 @@ function eq(a: any, b: any, depth: number, aStack?: any[], bStack?: any[]) { let key length = keys.length // Ensure that both objects contain the same number of properties before comparing deep equality. - if (Object.keys(b).length !== length) return false + if (Object.keys(b).length !== length) { + return false + } while (length--) { // Deep compare each member key = keys[length] - if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) return false + if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) { + return false + } } } // Remove the first object from the stack of traversed objects. @@ -146,8 +170,14 @@ function eq(a: any, b: any, depth: number, aStack?: any[], bStack?: any[]) { } function unwrap(a: any) { - if (isObservableArray(a)) return a.slice() - if (isES6Map(a) || isObservableMap(a)) return Array.from(a.entries()) - if (isES6Set(a) || isObservableSet(a)) return Array.from(a.entries()) + if (isObservableArray(a)) { + return a.slice() + } + if (isES6Map(a) || isObservableMap(a)) { + return Array.from(a.entries()) + } + if (isES6Set(a) || isObservableSet(a)) { + return Array.from(a.entries()) + } return a } diff --git a/packages/mobx/src/utils/utils.ts b/packages/mobx/src/utils/utils.ts index 4f67df2d3..fc2760b04 100644 --- a/packages/mobx/src/utils/utils.ts +++ b/packages/mobx/src/utils/utils.ts @@ -49,7 +49,9 @@ export function getNextId() { export function once(func: Lambda): Lambda { let invoked = false return function () { - if (invoked) return + if (invoked) { + return + } invoked = true return (func as any).apply(this, arguments) } @@ -81,9 +83,13 @@ export function isObject(value: any): value is Object { } export function isPlainObject(value: any) { - if (!isObject(value)) return false + if (!isObject(value)) { + return false + } const proto = Object.getPrototypeOf(value) - if (proto == null) return true + if (proto == null) { + return true + } const protoConstructor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor return ( typeof protoConstructor === "function" && protoConstructor.toString() === plainObjectString @@ -93,9 +99,15 @@ export function isPlainObject(value: any) { // https://stackoverflow.com/a/37865170 export function isGenerator(obj: any): boolean { const constructor = obj?.constructor - if (!constructor) return false - if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) + if (!constructor) { + return false + } + if ( + "GeneratorFunction" === constructor.name || + "GeneratorFunction" === constructor.displayName + ) { return true + } return false } @@ -144,9 +156,13 @@ const hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefi export function getPlainObjectKeys(object: any) { const keys = Object.keys(object) // Not supported in IE, so there are not going to be symbol props anyway... - if (!hasGetOwnPropertySymbols) return keys + if (!hasGetOwnPropertySymbols) { + return keys + } const symbols = Object.getOwnPropertySymbols(object) - if (!symbols.length) return keys + if (!symbols.length) { + return keys + } return [...keys, ...symbols.filter(s => objectPrototype.propertyIsEnumerable.call(object, s))] } @@ -160,8 +176,12 @@ export const ownKeys: (target: any) => Array = : /* istanbul ignore next */ Object.getOwnPropertyNames export function stringifyKey(key: any): string { - if (typeof key === "string") return key - if (typeof key === "symbol") return key.toString() + if (typeof key === "string") { + return key + } + if (typeof key === "symbol") { + return key.toString() + } return new String(key).toString() }