1 | module.exports = emitter => {
|
2 | let currentTransitionAttempt = null
|
3 | let nextTransition = null
|
4 |
|
5 | function doneTransitioning() {
|
6 | currentTransitionAttempt = null
|
7 | if (nextTransition) {
|
8 | beginNextTransitionAttempt()
|
9 | }
|
10 | }
|
11 |
|
12 | const isTransitioning = () => !!currentTransitionAttempt
|
13 |
|
14 | function beginNextTransitionAttempt() {
|
15 | currentTransitionAttempt = nextTransition
|
16 | nextTransition = null
|
17 | currentTransitionAttempt.beginStateChange()
|
18 | }
|
19 |
|
20 | function cancelCurrentTransition() {
|
21 | currentTransitionAttempt.transition.cancelled = true
|
22 | const err = new Error('State transition cancelled by the state transition manager')
|
23 | err.wasCancelledBySomeoneElse = true
|
24 | emitter.emit('stateChangeCancelled', err)
|
25 | }
|
26 |
|
27 | emitter.on('stateChangeAttempt', beginStateChange => {
|
28 | nextTransition = createStateTransitionAttempt(beginStateChange)
|
29 |
|
30 | if (isTransitioning() && currentTransitionAttempt.transition.cancellable) {
|
31 | cancelCurrentTransition()
|
32 | } else if (!isTransitioning()) {
|
33 | beginNextTransitionAttempt()
|
34 | }
|
35 | })
|
36 |
|
37 | emitter.on('stateChangeError', doneTransitioning)
|
38 | emitter.on('stateChangeCancelled', doneTransitioning)
|
39 | emitter.on('stateChangeEnd', doneTransitioning)
|
40 |
|
41 | function createStateTransitionAttempt(beginStateChange) {
|
42 | const transition = {
|
43 | cancelled: false,
|
44 | cancellable: true,
|
45 | }
|
46 | return {
|
47 | transition,
|
48 | beginStateChange: (...args) => beginStateChange(transition, ...args),
|
49 | }
|
50 | }
|
51 | }
|