forked from TehShrike/abstract-state-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
460 lines (395 loc) · 15.5 KB
/
index.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
const StateState = require(`./lib/state-state`)
const StateComparison = require(`./lib/state-comparison`)
const CurrentState = require(`./lib/current-state`)
const stateChangeLogic = require(`./lib/state-change-logic`)
const parse = require(`./lib/state-string-parser`)
const StateTransitionManager = require(`./lib/state-transition-manager`)
const defaultRouterOptions = require(`./default-router-options.js`)
const series = require(`./lib/promise-map-series`)
const denodeify = require(`then-denodeify`)
const EventEmitter = require(`eventemitter3`)
const newHashBrownRouter = require(`hash-brown-router`)
const combine = require(`combine-arrays`)
const buildPath = require(`page-path-builder`)
const nextTick = require(`iso-next-tick`)
const getProperty = name => obj => obj[name]
const reverse = ary => ary.slice().reverse()
const isFunction = property => obj => typeof obj[property] === `function`
const isThenable = object => object && (typeof object === `object` || typeof object === `function`) && typeof object.then === `function`
const expectedPropertiesOfAddState = [ `name`, `route`, `defaultChild`, `data`, `template`, `resolve`, `activate`, `querystringParameters`, `defaultQuerystringParameters`, `defaultParameters`, `canLeaveState` ]
module.exports = function StateProvider(makeRenderer, rootElement, stateRouterOptions = {}) {
const prototypalStateHolder = StateState()
const lastCompletelyLoadedState = CurrentState()
const lastStateStartedActivating = CurrentState()
const stateProviderEmitter = new EventEmitter()
const compareStartAndEndStates = StateComparison(prototypalStateHolder)
const stateNameToArrayofStates = stateName => parse(stateName).map(prototypalStateHolder.get)
StateTransitionManager(stateProviderEmitter)
const { throwOnError, pathPrefix } = {
throwOnError: true,
pathPrefix: `#`,
...stateRouterOptions,
}
const router = stateRouterOptions.router || newHashBrownRouter(defaultRouterOptions)
router.on(`not found`, (route, parameters) => {
stateProviderEmitter.emit(`routeNotFound`, route, parameters)
})
let destroyDom = null
let getDomChild = null
let renderDom = null
let activeStateResolveContent = {}
const activeDomApis = {}
const activeEmitters = {}
function handleError(event, err) {
nextTick(() => {
stateProviderEmitter.emit(event, err)
console.error(`${ event } - ${ err.message }`)
if (throwOnError) {
throw err
}
})
}
function destroyStateName(stateName) {
const state = prototypalStateHolder.get(stateName)
stateProviderEmitter.emit(`beforeDestroyState`, {
state,
domApi: activeDomApis[stateName],
})
activeEmitters[stateName].emit(`destroy`)
activeEmitters[stateName].removeAllListeners()
delete activeEmitters[stateName]
delete activeStateResolveContent[stateName]
return destroyDom(activeDomApis[stateName]).then(() => {
delete activeDomApis[stateName]
stateProviderEmitter.emit(`afterDestroyState`, {
state,
})
})
}
function getChildElementForStateName(stateName) {
return new Promise(resolve => {
const parent = prototypalStateHolder.getParent(stateName)
if (parent) {
resolve(getDomChild(activeDomApis[parent.name]).then(childDomApi => {
if (!childDomApi) {
return Promise.reject(new Error(`getDomChild returned a falsey element, did you forget to add a place for a child state to go?`))
}
return childDomApi
}))
} else {
resolve(rootElement)
}
})
}
function renderStateName(parameters, stateName) {
return getChildElementForStateName(stateName).then(element => {
const state = prototypalStateHolder.get(stateName)
const content = getContentObject(activeStateResolveContent, stateName)
stateProviderEmitter.emit(`beforeCreateState`, {
state,
content,
parameters,
})
return renderDom({
template: state.template,
element,
content,
parameters,
}).then(domApi => {
activeDomApis[stateName] = domApi
stateProviderEmitter.emit(`afterCreateState`, {
state,
domApi,
content,
parameters,
})
return domApi
})
})
}
function renderAll(stateNames, parameters) {
return series(stateNames, stateName => renderStateName(parameters, stateName))
}
function statesAreEquivalent(stateA, stateB) {
const { create, destroy } = stateChangeLogic(
compareStartAndEndStates({
original: stateA,
destination: stateB,
}),
)
return create.length === 0 && destroy.length === 0
}
function allowStateChangeOrRevert(newStateName, newParameters) {
const lastState = lastCompletelyLoadedState.get()
if (lastState.name && statesAreEquivalent(lastState, lastStateStartedActivating.get())) {
const { destroy } = stateChangeLogic(
compareStartAndEndStates({
original: lastState,
destination: {
name: newStateName,
parameters: newParameters,
},
}),
)
const canLeaveStates = destroy.every(stateName => {
const state = prototypalStateHolder.get(stateName)
if (state.canLeaveState && typeof state.canLeaveState === 'function') {
const stateChangeAllowed = state.canLeaveState(activeDomApis[stateName], {
name: newStateName,
parameters: newParameters,
})
if (!stateChangeAllowed) {
stateProviderEmitter.emit('stateChangePrevented', {
name: stateName,
parameters: lastState.parameters,
}, {
name: newStateName,
parameters: newParameters,
})
}
return stateChangeAllowed
}
return true
})
if (!canLeaveStates) {
stateProviderEmitter.go(lastState.name, lastState.parameters, { replace: true })
}
return canLeaveStates
}
return true
}
function onRouteChange(state, parameters) {
try {
const finalDestinationStateName = prototypalStateHolder.applyDefaultChildStates(state.name)
if (finalDestinationStateName === state.name && allowStateChangeOrRevert(state.name, parameters)) {
emitEventAndAttemptStateChange(finalDestinationStateName, parameters)
} else if (finalDestinationStateName !== state.name) {
// There are default child states that need to be applied
const theRouteWeNeedToEndUpAt = makePath(finalDestinationStateName, parameters)
const currentRoute = router.location.get()
if (theRouteWeNeedToEndUpAt !== currentRoute) {
// change the url to match the full default child state route
stateProviderEmitter.go(finalDestinationStateName, parameters, { replace: true })
} else if (allowStateChangeOrRevert(finalDestinationStateName, parameters)) {
// the child state has the same route as the current one, just start navigating there
emitEventAndAttemptStateChange(finalDestinationStateName, parameters)
}
}
} catch (err) {
handleError(`stateError`, err)
}
}
function addState(state) {
if (typeof state === `undefined`) {
throw new Error(`Expected 'state' to be passed in.`)
} else if (typeof state.name === `undefined`) {
throw new Error(`Expected the 'name' option to be passed in.`)
} else if (typeof state.template === `undefined`) {
throw new Error(`Expected the 'template' option to be passed in.`)
}
Object.keys(state).filter(key => expectedPropertiesOfAddState.indexOf(key) === -1).forEach(key => {
console.warn(`Unexpected property passed to addState:`, key)
})
prototypalStateHolder.add(state.name, state)
const route = prototypalStateHolder.buildFullStateRoute(state.name)
router.add(route, parameters => onRouteChange(state, parameters))
}
function computeDefaultParams(defaultParams) {
const computedDefaultParams = {}
Object.keys(defaultParams).forEach(key => {
computedDefaultParams[key] = typeof defaultParams[key] === `function` ? defaultParams[key]() : defaultParams[key]
})
return computedDefaultParams
}
function getStatesToResolve(stateChanges) {
return stateChanges.create.map(prototypalStateHolder.get)
}
function emitEventAndAttemptStateChange(newStateName, parameters) {
stateProviderEmitter.emit(`stateChangeAttempt`, function stateGo(transition) {
attemptStateChange(newStateName, parameters, transition)
})
}
function attemptStateChange(newStateName, parameters, transition) {
function ifNotCancelled(fn) {
return (...args) => {
if (transition.cancelled) {
const err = new Error(`The transition to ${ newStateName } was cancelled`)
err.wasCancelledBySomeoneElse = true
throw err
} else {
return fn(...args)
}
}
}
return Promise.resolve(prototypalStateHolder.guaranteeAllStatesExist(newStateName))
.then(function applyDefaultParameters() {
const state = prototypalStateHolder.get(newStateName)
const defaultParams = state.defaultParameters || state.defaultQuerystringParameters || {}
const needToApplyDefaults = Object.keys(defaultParams).some(function missingParameterValue(param) {
return typeof parameters[param] === `undefined`
})
if (needToApplyDefaults) {
throw redirector(newStateName, { ...computeDefaultParams(defaultParams), ...parameters })
}
return state
}).then(ifNotCancelled(state => {
stateProviderEmitter.emit(`stateChangeStart`, state, parameters, stateNameToArrayofStates(state.name))
lastStateStartedActivating.set(state.name, parameters)
})).then(function getStateChanges() {
const stateComparisonResults = compareStartAndEndStates({
original: lastCompletelyLoadedState.get(),
destination: {
name: newStateName,
parameters,
},
})
return stateChangeLogic(stateComparisonResults) // { destroy, change, create }
}).then(ifNotCancelled(function resolveDestroyAndActivateStates(stateChanges) {
return resolveStates(getStatesToResolve(stateChanges), { ...parameters }).catch(function onResolveError(e) {
e.stateChangeError = true
throw e
}).then(ifNotCancelled(function destroyAndActivate(stateResolveResultsObject) {
transition.cancellable = false
const activateAll = () => activateStates(
stateChanges.create,
)
return series(reverse(stateChanges.destroy), destroyStateName).then(
() => {
activeStateResolveContent = { ...activeStateResolveContent, ...stateResolveResultsObject }
return renderAll(stateChanges.create, { ...parameters }).then(activateAll)
},
)
}))
function activateStates(stateNames) {
return stateNames.map(prototypalStateHolder.get).forEach(state => {
const emitter = new EventEmitter()
const context = Object.create(emitter)
context.domApi = activeDomApis[state.name]
context.data = state.data
context.parameters = parameters
context.content = getContentObject(activeStateResolveContent, state.name)
activeEmitters[state.name] = emitter
try {
state.activate && state.activate(context)
} catch (e) {
nextTick(() => {
throw e
})
}
})
}
})).then(function stateChangeComplete() {
lastCompletelyLoadedState.set(newStateName, parameters)
try {
stateProviderEmitter.emit(`stateChangeEnd`, prototypalStateHolder.get(newStateName), parameters, stateNameToArrayofStates(newStateName))
} catch (e) {
handleError(`stateError`, e)
}
}).catch(ifNotCancelled(function handleStateChangeError(err) {
if (err && err.redirectTo) {
stateProviderEmitter.emit(`stateChangeCancelled`, err)
return stateProviderEmitter.go(err.redirectTo.name, err.redirectTo.params, { replace: true })
} else if (err) {
handleError(`stateChangeError`, err)
}
})).catch(function handleCancellation(err) {
if (err && err.wasCancelledBySomeoneElse) {
// we don't care, the state transition manager has already emitted the stateChangeCancelled for us
} else {
throw new Error(`This probably shouldn't happen, maybe file an issue or something ${ err }`)
}
})
}
function makePath(stateName, parameters, options) {
function getGuaranteedPreviousState() {
if (!lastStateStartedActivating.get().name) {
throw new Error(`makePath required a previous state to exist, and none was found`)
}
return lastStateStartedActivating.get()
}
if (options && options.inherit) {
parameters = { ...(getGuaranteedPreviousState().parameters), ...parameters }
}
const destinationStateName = stateName === null ? getGuaranteedPreviousState().name : stateName
const destinationState = prototypalStateHolder.get(destinationStateName) || {}
const defaultParams = destinationState.defaultParameters || destinationState.defaultQuerystringParameters || {}
parameters = { ...computeDefaultParams(defaultParams), ...parameters }
prototypalStateHolder.guaranteeAllStatesExist(destinationStateName)
const route = prototypalStateHolder.buildFullStateRoute(destinationStateName)
return buildPath(route, parameters || {})
}
const defaultOptions = {
replace: false,
}
stateProviderEmitter.addState = addState
stateProviderEmitter.go = (newStateName, parameters, options) => {
options = { ...defaultOptions, ...options }
const goFunction = options.replace ? router.replace : router.go
return new Promise((resolve, reject) => {
try {
resolve(makePath(newStateName, parameters, options))
} catch (err) {
reject(err)
}
}).then(goFunction, err => handleError(`stateChangeError`, err))
}
stateProviderEmitter.evaluateCurrentRoute = (defaultState, defaultParams) => Promise.resolve(makePath(defaultState, defaultParams)).then(defaultPath => {
router.evaluateCurrent(defaultPath)
}).catch(err => handleError(`stateError`, err))
stateProviderEmitter.makePath = (stateName, parameters, options) => pathPrefix + makePath(stateName, parameters, options)
stateProviderEmitter.getActiveState = () => lastCompletelyLoadedState.get()
stateProviderEmitter.stateIsActive = (stateName = null, parameters = null) => {
const currentState = lastCompletelyLoadedState.get()
const stateNameMatches = currentState.name === stateName
|| currentState.name.indexOf(`${stateName }.`) === 0
|| stateName === null
const parametersWereNotPassedIn = !parameters
return stateNameMatches
&& (parametersWereNotPassedIn || Object.keys(parameters).every(key => `${ parameters[key] }` === currentState.parameters[key]))
}
const renderer = makeRenderer(stateProviderEmitter)
destroyDom = denodeify(renderer.destroy)
getDomChild = denodeify(renderer.getChildElement)
renderDom = denodeify(renderer.render)
return stateProviderEmitter
}
function getContentObject(stateResolveResultsObject, stateName) {
const allPossibleResolvedStateNames = parse(stateName)
return allPossibleResolvedStateNames
.filter(stateName => stateResolveResultsObject[stateName])
.reduce((obj, stateName) => {
return { ...obj, ...stateResolveResultsObject[stateName] }
}, {})
}
function redirector(newStateName, parameters) {
return {
redirectTo: {
name: newStateName,
params: parameters,
},
}
}
// { [stateName]: resolveResult }
function resolveStates(states, parameters) {
const statesWithResolveFunctions = states.filter(isFunction(`resolve`))
const stateNamesWithResolveFunctions = statesWithResolveFunctions.map(getProperty(`name`))
const resolves = Promise.all(statesWithResolveFunctions.map(state => new Promise((resolve, reject) => {
const resolveCb = (err, content) => err ? reject(err) : resolve(content)
resolveCb.redirect = (newStateName, parameters) => {
reject(redirector(newStateName, parameters))
}
const res = state.resolve(state.data, parameters, resolveCb)
if (isThenable(res)) {
resolve(res)
}
})))
return resolves.then(resolveResults =>
combine({
stateName: stateNamesWithResolveFunctions,
resolveResult: resolveResults,
}).reduce((obj, result) => {
obj[result.stateName] = result.resolveResult
return obj
}, {}),
)
}