This repository has been archived by the owner on Dec 31, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 350
/
observer.js
444 lines (402 loc) · 15.2 KB
/
observer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import React, { Component, PureComponent, forwardRef } from "react"
import hoistStatics from "hoist-non-react-statics"
import { createAtom, Reaction, _allowStateChanges, $mobx } from "mobx"
import { findDOMNode as baseFindDOMNode } from "react-dom"
import EventEmitter from "./utils/EventEmitter"
import inject from "./inject"
import { patch as newPatch, newSymbol } from "./utils/utils"
const mobxAdminProperty = $mobx || "$mobx"
const mobxIsUnmounted = newSymbol("isUnmounted")
/**
* dev tool support
*/
let isDevtoolsEnabled = false
let isUsingStaticRendering = false
let warnedAboutObserverInjectDeprecation = false
// WeakMap<Node, Object>;
export const componentByNodeRegistry = typeof WeakMap !== "undefined" ? new WeakMap() : undefined
export const renderReporter = new EventEmitter()
const skipRenderKey = newSymbol("skipRender")
const isForcingUpdateKey = newSymbol("isForcingUpdate")
// Using react-is had some issues (and operates on elements, not on types), see #608 / #609
const ReactForwardRefSymbol =
typeof forwardRef === "function" && forwardRef((_props, _ref) => {})["$$typeof"]
/**
* Helper to set `prop` to `this` as non-enumerable (hidden prop)
* @param target
* @param prop
* @param value
*/
function setHiddenProp(target, prop, value) {
if (!Object.hasOwnProperty.call(target, prop)) {
Object.defineProperty(target, prop, {
enumerable: false,
configurable: true,
writable: true,
value
})
} else {
target[prop] = value
}
}
function findDOMNode(component) {
if (baseFindDOMNode) {
try {
return baseFindDOMNode(component)
} catch (e) {
// findDOMNode will throw in react-test-renderer, see:
// See https://github.com/mobxjs/mobx-react/issues/216
// Is there a better heuristic?
return null
}
}
return null
}
function reportRendering(component) {
const node = findDOMNode(component)
if (node && componentByNodeRegistry) componentByNodeRegistry.set(node, component)
renderReporter.emit({
event: "render",
renderTime: component.__$mobRenderEnd - component.__$mobRenderStart,
totalTime: Date.now() - component.__$mobRenderStart,
component: component,
node: node
})
}
export function trackComponents() {
if (typeof WeakMap === "undefined")
throw new Error("[mobx-react] tracking components is not supported in this browser.")
if (!isDevtoolsEnabled) isDevtoolsEnabled = true
}
export function useStaticRendering(useStaticRendering) {
isUsingStaticRendering = useStaticRendering
}
/**
* Errors reporter
*/
export const errorsReporter = new EventEmitter()
/**
* Utilities
*/
function patch(target, funcName) {
newPatch(target, funcName, reactiveMixin[funcName])
}
function shallowEqual(objA, objB) {
//From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
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
for (let i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false
}
}
return true
}
function is(x, y) {
// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
if (x === y) {
return x !== 0 || 1 / x === 1 / y
} else {
return x !== x && y !== y
}
}
function makeComponentReactive(render) {
if (isUsingStaticRendering === true) return render.call(this)
function reactiveRender() {
isRenderingPending = false
let exception = undefined
let rendering = undefined
reaction.track(() => {
if (isDevtoolsEnabled) {
this.__$mobRenderStart = Date.now()
}
try {
rendering = _allowStateChanges(false, baseRender)
} catch (e) {
exception = e
}
if (isDevtoolsEnabled) {
this.__$mobRenderEnd = Date.now()
}
})
if (exception) {
errorsReporter.emit(exception)
throw exception
}
return rendering
}
// Generate friendly name for debugging
const initialName =
this.displayName ||
this.name ||
(this.constructor && (this.constructor.displayName || this.constructor.name)) ||
"<component>"
const rootNodeID =
(this._reactInternalInstance && this._reactInternalInstance._rootNodeID) ||
(this._reactInternalInstance && this._reactInternalInstance._debugID) ||
(this._reactInternalFiber && this._reactInternalFiber._debugID)
/**
* If props are shallowly modified, react will render anyway,
* so atom.reportChanged() should not result in yet another re-render
*/
setHiddenProp(this, skipRenderKey, false)
/**
* forceUpdate will re-assign this.props. We don't want that to cause a loop,
* so detect these changes
*/
setHiddenProp(this, isForcingUpdateKey, false)
// wire up reactive render
const baseRender = render.bind(this)
let isRenderingPending = false
const reaction = new Reaction(`${initialName}#${rootNodeID}.render()`, () => {
if (!isRenderingPending) {
// N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js)
// This unidiomatic React usage but React will correctly warn about this so we continue as usual
// See #85 / Pull #44
isRenderingPending = true
if (typeof this.componentWillReact === "function") this.componentWillReact() // TODO: wrap in action?
if (this[mobxIsUnmounted] !== true) {
// If we are unmounted at this point, componentWillReact() had a side effect causing the component to unmounted
// TODO: remove this check? Then react will properly warn about the fact that this should not happen? See #73
// However, people also claim this might happen during unit tests..
let hasError = true
try {
setHiddenProp(this, isForcingUpdateKey, true)
if (!this[skipRenderKey]) Component.prototype.forceUpdate.call(this)
hasError = false
} finally {
setHiddenProp(this, isForcingUpdateKey, false)
if (hasError) reaction.dispose()
}
}
}
})
reaction.reactComponent = this
reactiveRender[mobxAdminProperty] = reaction
this.render = reactiveRender
return reactiveRender.call(this)
}
/**
* ReactiveMixin
*/
const reactiveMixin = {
componentWillUnmount: function() {
if (isUsingStaticRendering === true) return
this.render[mobxAdminProperty] && this.render[mobxAdminProperty].dispose()
this[mobxIsUnmounted] = true
if (isDevtoolsEnabled) {
const node = findDOMNode(this)
if (node && componentByNodeRegistry) {
componentByNodeRegistry.delete(node)
}
renderReporter.emit({
event: "destroy",
component: this,
node: node
})
}
},
componentDidMount: function() {
if (isDevtoolsEnabled) {
reportRendering(this)
}
},
componentDidUpdate: function() {
if (isDevtoolsEnabled) {
reportRendering(this)
}
},
shouldComponentUpdate: function(nextProps, nextState) {
if (isUsingStaticRendering) {
console.warn(
"[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side."
)
}
// update on any state changes (as is the default)
if (this.state !== nextState) {
return true
}
// update if props are shallowly not equal, inspired by PureRenderMixin
// we could return just 'false' here, and avoid the `skipRender` checks etc
// however, it is nicer if lifecycle events are triggered like usually,
// so we return true here if props are shallowly modified.
return !shallowEqual(this.props, nextProps)
}
}
function makeObservableProp(target, propName) {
const valueHolderKey = newSymbol(`reactProp_${propName}_valueHolder`)
const atomHolderKey = newSymbol(`reactProp_${propName}_atomHolder`)
function getAtom() {
if (!this[atomHolderKey]) {
setHiddenProp(this, atomHolderKey, createAtom("reactive " + propName))
}
return this[atomHolderKey]
}
Object.defineProperty(target, propName, {
configurable: true,
enumerable: true,
get: function() {
getAtom.call(this).reportObserved()
return this[valueHolderKey]
},
set: function set(v) {
if (!this[isForcingUpdateKey] && !shallowEqual(this[valueHolderKey], v)) {
setHiddenProp(this, valueHolderKey, v)
setHiddenProp(this, skipRenderKey, true)
getAtom.call(this).reportChanged()
setHiddenProp(this, skipRenderKey, false)
} else {
setHiddenProp(this, valueHolderKey, v)
}
}
})
}
/**
* Observer function / decorator
*/
export function observer(arg1, arg2) {
if (typeof arg1 === "string") {
throw new Error("Store names should be provided as array")
}
if (Array.isArray(arg1)) {
// TODO: remove in next major
// component needs stores
if (!warnedAboutObserverInjectDeprecation) {
warnedAboutObserverInjectDeprecation = true
console.warn(
'Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`'
)
}
if (!arg2) {
// invoked as decorator
return componentClass => observer(arg1, componentClass)
} else {
return inject.apply(null, arg1)(observer(arg2))
}
}
const componentClass = arg1
if (componentClass.isMobxInjector === true) {
console.warn(
"Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'"
)
}
if (componentClass.__proto__ === PureComponent) {
console.warn(
"Mobx observer: You are using 'observer' on React.PureComponent. These two achieve two opposite goals and should not be used together"
)
}
// Unwrap forward refs into `<Observer>` component
// we need to unwrap the render, because it is the inner render that needs to be tracked,
// not the ForwardRef HoC
if (ReactForwardRefSymbol && componentClass["$$typeof"] === ReactForwardRefSymbol) {
const baseRender = componentClass.render
if (typeof baseRender !== "function")
throw new Error("render property of ForwardRef was not a function")
return {
...componentClass,
render() {
const args = arguments
return <Observer>{() => baseRender.apply(undefined, arguments)}</Observer>
}
}
}
// Stateless function component:
// If it is function but doesn't seem to be a react class constructor,
// wrap it to a react class automatically
if (
typeof componentClass === "function" &&
(!componentClass.prototype || !componentClass.prototype.render) &&
!componentClass.isReactClass &&
!Component.isPrototypeOf(componentClass)
) {
const observerComponent = observer(
class extends Component {
static displayName = componentClass.displayName || componentClass.name
static contextTypes = componentClass.contextTypes
static propTypes = componentClass.propTypes
static defaultProps = componentClass.defaultProps
render() {
return componentClass.call(this, this.props, this.context)
}
}
)
hoistStatics(observerComponent, componentClass)
return observerComponent
}
if (!componentClass) {
throw new Error("Please pass a valid component to 'observer'")
}
const target = componentClass.prototype || componentClass
mixinLifecycleEvents(target)
componentClass.isMobXReactObserver = true
makeObservableProp(target, "props")
makeObservableProp(target, "state")
const baseRender = target.render
target.render = function() {
return makeComponentReactive.call(this, baseRender)
}
return componentClass
}
function mixinLifecycleEvents(target) {
;["componentDidMount", "componentWillUnmount", "componentDidUpdate"].forEach(function(
funcName
) {
patch(target, funcName)
})
if (!target.shouldComponentUpdate) {
target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate
} else {
if (target.shouldComponentUpdate !== reactiveMixin.shouldComponentUpdate) {
// TODO: make throw in next major
console.warn(
"Use `shouldComponentUpdate` in an `observer` based component breaks the behavior of `observer` and might lead to unexpected results. Manually implementing `sCU` should not be needed when using mobx-react."
)
}
}
}
export const Observer = observer(({ children, inject: observerInject, render }) => {
const component = children || render
if (typeof component === "undefined") {
return null
}
if (!observerInject) {
return component()
}
// TODO: remove in next major
console.warn(
"<Observer inject=.../> is no longer supported. Please use inject on the enclosing component instead"
)
const InjectComponent = inject(observerInject)(component)
return <InjectComponent />
})
Observer.displayName = "Observer"
const ObserverPropsCheck = (props, key, componentName, location, propFullName) => {
const extraKey = key === "children" ? "render" : "children"
if (typeof props[key] === "function" && typeof props[extraKey] === "function") {
return new Error(
"Invalid prop,do not use children and render in the same time in`" + componentName
)
}
if (typeof props[key] === "function" || typeof props[extraKey] === "function") {
return
}
return new Error(
"Invalid prop `" +
propFullName +
"` of type `" +
typeof props[key] +
"` supplied to" +
" `" +
componentName +
"`, expected `function`."
)
}
Observer.propTypes = {
render: ObserverPropsCheck,
children: ObserverPropsCheck
}