-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathreactor.js
309 lines (269 loc) · 8.4 KB
/
reactor.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
import Immutable from 'immutable'
import createReactMixin from './create-react-mixin'
import * as fns from './reactor/fns'
import { isKeyPath } from './key-path'
import { isGetter } from './getter'
import { toJS } from './immutable-helpers'
import { toFactory } from './utils'
import {
ReactorState,
ObserverState,
DEBUG_OPTIONS,
PROD_OPTIONS,
} from './reactor/records'
export const DEFAULT_MAX_ITEMS_TO_CACHE = 1000
/**
* State is stored in NuclearJS Reactors. Reactors
* contain a 'state' object which is an Immutable.Map
*
* The only way Reactors can change state is by reacting to
* messages. To update state, Reactor's dispatch messages to
* all registered cores, and the core returns it's new
* state based on the message
*/
class Reactor {
constructor(config = {}) {
const debug = !!config.debug
const useCache = config.useCache === undefined ? true : !!config.useCache
// use default # of items in cache
let maxItemsToCache = DEFAULT_MAX_ITEMS_TO_CACHE
// if user has defined maxItemsToCache, use the number provide or set to null (ie no max)
if (config.maxItemsToCache !== undefined) {
maxItemsToCache = Number(config.maxItemsToCache)
maxItemsToCache = maxItemsToCache > 0 ? maxItemsToCache : null
}
const baseOptions = debug ? DEBUG_OPTIONS : PROD_OPTIONS
const initialReactorState = new ReactorState({
debug: debug,
maxItemsToCache: maxItemsToCache,
// merge config options with the defaults
options: baseOptions.merge(config.options || {}),
useCache: useCache,
})
this.prevReactorState = initialReactorState
this.reactorState = initialReactorState
this.observerState = new ObserverState()
this.ReactMixin = createReactMixin(this)
// keep track of the depth of batch nesting
this.__batchDepth = 0
// keep track if we are currently dispatching
this.__isDispatching = false
}
/**
* Evaluates a KeyPath or Getter in context of the reactor state
* @param {KeyPath|Getter} keyPathOrGetter
* @return {*}
*/
evaluate(keyPathOrGetter) {
let { result, reactorState } = fns.evaluate(this.reactorState, keyPathOrGetter)
this.reactorState = reactorState
return result
}
/**
* Gets the coerced state (to JS object) of the reactor.evaluate
* @param {KeyPath|Getter} keyPathOrGetter
* @return {*}
*/
evaluateToJS(keyPathOrGetter) {
return toJS(this.evaluate(keyPathOrGetter))
}
/**
* Adds a change observer whenever a certain part of the reactor state changes
*
* 1. observe(handlerFn) - 1 argument, called anytime reactor.state changes
* 2. observe(keyPath, handlerFn) same as above
* 3. observe(getter, handlerFn) called whenever any getter dependencies change with
* the value of the getter
*
* Adds a change handler whenever certain deps change
* If only one argument is passed invoked the handler whenever
* the reactor state changes
*
* @param {KeyPath|Getter} getter
* @param {function} handler
* @return {function} unwatch function
*/
observe(getter, handler) {
if (arguments.length === 1) {
handler = getter
getter = []
}
let { observerState, entry } = fns.addObserver(this.observerState, getter, handler)
this.observerState = observerState
return () => {
let { observerState, reactorState } = fns.removeObserverByEntry(this.observerState, this.reactorState, entry)
this.observerState = observerState
this.reactorState = reactorState
}
}
unobserve(getter, handler) {
if (arguments.length === 0) {
throw new Error('Must call unobserve with a Getter')
}
if (!isGetter(getter) && !isKeyPath(getter)) {
throw new Error('Must call unobserve with a Getter')
}
const { observerState, reactorState } = fns.removeObserver(this.observerState, this.reactorState, getter, handler)
this.observerState = observerState
this.reactorState = reactorState
}
/**
* Dispatches a single message
* @param {string} actionType
* @param {object|undefined} payload
*/
dispatch(actionType, payload) {
if (this.__batchDepth === 0) {
if (fns.getOption(this.reactorState, 'throwOnDispatchInDispatch')) {
if (this.__isDispatching) {
this.__isDispatching = false
throw new Error('Dispatch may not be called while a dispatch is in progress')
}
}
this.__isDispatching = true
}
try {
this.reactorState = fns.dispatch(this.reactorState, actionType, payload)
} catch (e) {
this.__isDispatching = false
throw e
}
try {
this.__notify()
} finally {
this.__isDispatching = false
}
}
/**
* Allows batching of dispatches before notifying change observers
* @param {Function} fn
*/
batch(fn) {
this.batchStart()
fn()
this.batchEnd()
}
/**
* @deprecated
* @param {String} id
* @param {Store} store
*/
registerStore(id, store) {
/* eslint-disable no-console */
console.warn('Deprecation warning: `registerStore` will no longer be supported in 1.1, use `registerStores` instead')
/* eslint-enable no-console */
this.registerStores({
[id]: store,
})
}
/**
* @param {Object} stores
*/
registerStores(stores) {
this.reactorState = fns.registerStores(this.reactorState, stores)
this.__notify()
}
/**
* Replace store implementation (handlers) without modifying the app state or calling getInitialState
* Useful for hot reloading
* @param {Object} stores
*/
replaceStores(stores) {
this.reactorState = fns.replaceStores(this.reactorState, stores)
}
/**
* Returns a plain object representing the application state
* @return {Object}
*/
serialize() {
return fns.serialize(this.reactorState)
}
/**
* @param {Object} state
*/
loadState(state) {
this.reactorState = fns.loadState(this.reactorState, state)
this.__notify()
}
/**
* Resets the state of a reactor and returns back to initial state
*/
reset() {
const newState = fns.reset(this.reactorState)
this.reactorState = newState
this.prevReactorState = newState
this.observerState = new ObserverState()
}
/**
* Notifies all change observers with the current state
* @private
*/
__notify() {
if (this.__batchDepth > 0) {
// in the middle of batch, dont notify
return
}
const dirtyStores = this.reactorState.get('dirtyStores')
if (dirtyStores.size === 0) {
return
}
let observerIdsToNotify = Immutable.Set().withMutations(set => {
// notify all observers
set.union(this.observerState.get('any'))
dirtyStores.forEach(id => {
const entries = this.observerState.getIn(['stores', id])
if (!entries) {
return
}
set.union(entries)
})
})
observerIdsToNotify.forEach((observerId) => {
const entry = this.observerState.getIn(['observersMap', observerId])
if (!entry) {
// don't notify here in the case a handler called unobserve on another observer
return
}
const getter = entry.get('getter')
const handler = entry.get('handler')
const prevEvaluateResult = fns.evaluate(this.prevReactorState, getter)
const currEvaluateResult = fns.evaluate(this.reactorState, getter)
this.prevReactorState = prevEvaluateResult.reactorState
this.reactorState = currEvaluateResult.reactorState
const prevValue = prevEvaluateResult.result
const currValue = currEvaluateResult.result
if (!Immutable.is(prevValue, currValue)) {
handler.call(null, currValue)
}
})
const nextReactorState = fns.resetDirtyStores(this.reactorState)
this.prevReactorState = nextReactorState
this.reactorState = nextReactorState
}
/**
* Starts batching, ie pausing notifies and batching up changes
* to be notified when batchEnd() is called
*/
batchStart() {
this.__batchDepth++
}
/**
* Ends a batch cycle and will notify obsevers of all changes if
* the batch depth is back to 0 (outer most batch completed)
*/
batchEnd() {
this.__batchDepth--
if (this.__batchDepth <= 0) {
// set to true to catch if dispatch called from observer
this.__isDispatching = true
try {
this.__notify()
} catch (e) {
this.__isDispatching = false
throw e
}
this.__isDispatching = false
}
}
}
export default toFactory(Reactor)