Skip to content

Commit

Permalink
Apply 'curly' ESLint rule + run Prettier on changed files
Browse files Browse the repository at this point in the history
  • Loading branch information
kubk committed Feb 12, 2022
1 parent fb599da commit b37c7ae
Show file tree
Hide file tree
Showing 47 changed files with 754 additions and 293 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion docs/api.md
Expand Up @@ -284,7 +284,7 @@ Hook for when something stops being observed.
### `toJS`

[**Usage**](observable-state.md#converting-observables-back-to-vanilla-javascript-collections): `toJS(value)`

Recursively converts an observable object to a JavaScript _object_. Supports observable arrays, objects, Maps and primitives.

It does NOT recurse into non-observables, these are left as they are, even if they contain observables.
Expand Down
30 changes: 18 additions & 12 deletions docs/installation.md
Expand Up @@ -24,21 +24,27 @@ There are two types of React bindings, `mobx-react-lite` supports only functiona

- **TypeScript**: Set the compiler option `"useDefineForClassFields": true`.
- **Babel**: Make sure to use at least version 7.12, with the following configuration:
```json
````json
{
// Babel < 7.13.0
"plugins": [["@babel/plugin-proposal-class-properties", { "loose": false }]],

// Babel >= 7.13.0 (https://babeljs.io/docs/en/assumptions)
"plugins": [["@babel/plugin-proposal-class-properties"]],
"assumptions": {
"setPublicClassFields": false
// Babel < 7.13.0
"plugins": [["@babel/plugin-proposal-class-properties", { "loose": false }]],
// Babel >= 7.13.0 (https://babeljs.io/docs/en/assumptions)
"plugins": [["@babel/plugin-proposal-class-properties"]],
"assumptions": {
"setPublicClassFields": false
}
}
}
```
For verification insert this piece of code at the beginning of your sources (eg. `index.js`)
```
For verification insert this piece of code at the beginning of your sources (eg. `index.js`)
````

```javascript
if (!new class { x }().hasOwnProperty('x')) throw new Error('Transpiler is not configured correctly');
if (
!new (class {
x
})().hasOwnProperty("x")
)
throw new Error("Transpiler is not configured correctly")
```

## MobX on older JavaScript environments
Expand Down
4 changes: 2 additions & 2 deletions docs/react-optimizations.md
Expand Up @@ -95,9 +95,9 @@ const PersonNameDisplayer = observer(({ person }) => <DisplayName name={person.n

const CarNameDisplayer = observer(({ car }) => <DisplayName name={car.model} />)

const ManufacturerNameDisplayer = observer(({ car }) =>
const ManufacturerNameDisplayer = observer(({ car }) => (
<DisplayName name={car.manufacturer.name} />
)
))
```

This quickly becomes tedious if you have lots of data of different shape. An alternative is to use a function that returns the data that you want your `*Displayer` to render:
Expand Down
8 changes: 6 additions & 2 deletions packages/mobx-react/src/utils/utils.ts
Expand Up @@ -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
Expand Down
11 changes: 8 additions & 3 deletions packages/mobx/src/api/action.ts
Expand Up @@ -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)
Expand All @@ -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
}
Expand Down
3 changes: 1 addition & 2 deletions packages/mobx/src/api/annotation.ts
Expand Up @@ -32,8 +32,7 @@ export type AnnotationMapEntry =
// declare annotations for private/ protected members, see #2339
export type AnnotationsMap<T, AdditionalFields extends PropertyKey> = {
[P in Exclude<keyof T, "toString">]?: AnnotationMapEntry
} &
Record<AdditionalFields, AnnotationMapEntry>
} & Record<AdditionalFields, AnnotationMapEntry>

export function isAnnotation(thing: any) {
return (
Expand Down
30 changes: 22 additions & 8 deletions packages/mobx/src/api/autorun.ts
Expand Up @@ -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 =
Expand Down Expand Up @@ -69,7 +73,9 @@ export function autorun(
isScheduled = true
scheduler(() => {
isScheduled = false
if (!reaction.isDisposed_) reaction.track(reactionRunner)
if (!reaction.isDisposed_) {
reaction.track(reactionRunner)
}
})
}
},
Expand Down Expand Up @@ -111,9 +117,12 @@ export function reaction<T, FireImmediately extends boolean = false>(
opts: IReactionOptions<T, FireImmediately> = 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(
Expand Down Expand Up @@ -148,7 +157,9 @@ export function reaction<T, FireImmediately extends boolean = false>(

function reactionRunner() {
isScheduled = false
if (r.isDisposed_) return
if (r.isDisposed_) {
return
}
let changed: boolean = false
r.track(() => {
const nextValue = allowStateChanges(false, () => expression(r))
Expand All @@ -159,8 +170,11 @@ export function reaction<T, FireImmediately extends boolean = false>(

// 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
}

Expand Down
7 changes: 5 additions & 2 deletions packages/mobx/src/api/computed.ts
Expand Up @@ -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<any> = isPlainObject(arg2) ? arg2 : {}
opts.get = arg1
Expand Down
8 changes: 6 additions & 2 deletions packages/mobx/src/api/configure.ts
Expand Up @@ -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
Expand All @@ -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) {
Expand Down
16 changes: 11 additions & 5 deletions packages/mobx/src/api/extendobservable.ts
Expand Up @@ -21,15 +21,21 @@ export function extendObservable<A extends Object, B extends Object>(
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)
Expand Down
6 changes: 4 additions & 2 deletions packages/mobx/src/api/extras.ts
Expand Up @@ -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
}

Expand All @@ -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(<any>getObservers(node as any)).map(<any>nodeToObserverTree)
}
return result
}

Expand Down
15 changes: 11 additions & 4 deletions packages/mobx/src/api/flow.ts
Expand Up @@ -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 || "<unnamed flow>"

Expand Down Expand Up @@ -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)
}
Expand All @@ -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!
Expand All @@ -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<T>(
Expand Down
6 changes: 4 additions & 2 deletions packages/mobx/src/api/intercept-read.ts
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions packages/mobx/src/api/intercept.ts
Expand Up @@ -43,8 +43,11 @@ export function intercept<T extends object, K extends keyof T>(
handler: IInterceptor<IValueWillChange<T[K]>>
): 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) {
Expand Down
14 changes: 10 additions & 4 deletions packages/mobx/src/api/iscomputed.ts
Expand Up @@ -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)
}

0 comments on commit b37c7ae

Please sign in to comment.