-
-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
createTransitionManager.js
286 lines (245 loc) · 8.28 KB
/
createTransitionManager.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
import warning from './warning'
import { REPLACE } from 'history/lib/Actions'
import computeChangedRoutes from './computeChangedRoutes'
import { runEnterHooks, runLeaveHooks } from './TransitionUtils'
import { default as _isActive } from './isActive'
import getComponents from './getComponents'
import matchRoutes from './matchRoutes'
function hasAnyProperties(object) {
for (const p in object)
if (object.hasOwnProperty(p))
return true
return false
}
export default function createTransitionManager(history, routes) {
let state = {}
// Signature should be (location, indexOnly), but needs to support (path,
// query, indexOnly)
function isActive(
location, indexOnlyOrDeprecatedQuery=false, deprecatedIndexOnly=null
) {
let indexOnly
if (
(indexOnlyOrDeprecatedQuery && indexOnlyOrDeprecatedQuery !== true) ||
deprecatedIndexOnly !== null
) {
warning(
false,
'`isActive(pathname, query, indexOnly) is deprecated; use `isActive(location, indexOnly)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated'
)
location = { pathname: location, query: indexOnlyOrDeprecatedQuery }
indexOnly = deprecatedIndexOnly || false
} else {
if (typeof location === 'string') {
location = { pathname: location }
}
indexOnly = indexOnlyOrDeprecatedQuery
}
return _isActive(
location, indexOnly, state.location, state.routes, state.params
)
}
function createLocationFromRedirectInfo({ pathname, query, state }) {
return history.createLocation(
history.createPath(pathname, query), state, REPLACE
)
}
let partialNextState
function match(location, callback) {
if (partialNextState && partialNextState.location === location) {
// Continue from where we left off.
finishMatch(partialNextState, callback)
} else {
matchRoutes(routes, location, function (error, nextState) {
if (error) {
callback(error)
} else if (nextState) {
finishMatch({ ...nextState, location }, callback)
} else {
callback()
}
})
}
}
function finishMatch(nextState, callback) {
const { leaveRoutes, enterRoutes } = computeChangedRoutes(state, nextState)
runLeaveHooks(leaveRoutes)
// Tear down confirmation hooks for left routes
leaveRoutes.forEach(removeListenBeforeHooksForRoute)
runEnterHooks(enterRoutes, nextState, function (error, redirectInfo) {
if (error) {
callback(error)
} else if (redirectInfo) {
callback(null, createLocationFromRedirectInfo(redirectInfo))
} else {
// TODO: Fetch components after state is updated.
getComponents(nextState, function (error, components) {
if (error) {
callback(error)
} else {
// TODO: Make match a pure function and have some other API
// for "match and update state".
callback(null, null, (
state = { ...nextState, components })
)
}
})
}
})
}
let RouteGuid = 1
function getRouteID(route, create = true) {
return route.__id__ || create && (route.__id__ = RouteGuid++)
}
const RouteHooks = {}
function getRouteHooksForRoutes(routes) {
return routes.reduce(function (hooks, route) {
hooks.push.apply(hooks, RouteHooks[getRouteID(route)])
return hooks
}, [])
}
function transitionHook(location, callback) {
matchRoutes(routes, location, function (error, nextState) {
if (nextState == null) {
// TODO: We didn't actually match anything, but hang
// onto error/nextState so we don't have to matchRoutes
// again in the listen callback.
callback()
return
}
// Cache some state here so we don't have to
// matchRoutes() again in the listen callback.
partialNextState = { ...nextState, location }
const hooks = getRouteHooksForRoutes(
computeChangedRoutes(state, partialNextState).leaveRoutes
)
let result
for (let i = 0, len = hooks.length; result == null && i < len; ++i) {
// Passing the location arg here indicates to
// the user that this is a transition hook.
result = hooks[i](location)
}
callback(result)
})
}
/* istanbul ignore next: untestable with Karma */
function beforeUnloadHook() {
// Synchronously check to see if any route hooks want
// to prevent the current window/tab from closing.
if (state.routes) {
const hooks = getRouteHooksForRoutes(state.routes)
let message
for (let i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) {
// Passing no args indicates to the user that this is a
// beforeunload hook. We don't know the next location.
message = hooks[i]()
}
return message
}
}
let unlistenBefore, unlistenBeforeUnload
function removeListenBeforeHooksForRoute(route) {
const routeID = getRouteID(route, false)
if (!routeID) {
return
}
delete RouteHooks[routeID]
if (!hasAnyProperties(RouteHooks)) {
// teardown transition & beforeunload hooks
if (unlistenBefore) {
unlistenBefore()
unlistenBefore = null
}
if (unlistenBeforeUnload) {
unlistenBeforeUnload()
unlistenBeforeUnload = null
}
}
}
/**
* Registers the given hook function to run before leaving the given route.
*
* During a normal transition, the hook function receives the next location
* as its only argument and must return either a) a prompt message to show
* the user, to make sure they want to leave the page or b) false, to prevent
* the transition.
*
* During the beforeunload event (in browsers) the hook receives no arguments.
* In this case it must return a prompt message to prevent the transition.
*
* Returns a function that may be used to unbind the listener.
*/
function listenBeforeLeavingRoute(route, hook) {
// TODO: Warn if they register for a route that isn't currently
// active. They're probably doing something wrong, like re-creating
// route objects on every location change.
const routeID = getRouteID(route)
let hooks = RouteHooks[routeID]
if (!hooks) {
let thereWereNoRouteHooks = !hasAnyProperties(RouteHooks)
RouteHooks[routeID] = [ hook ]
if (thereWereNoRouteHooks) {
// setup transition & beforeunload hooks
unlistenBefore = history.listenBefore(transitionHook)
if (history.listenBeforeUnload)
unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook)
}
} else {
warning(
false,
'adding multiple leave hooks for the same route is deprecated; manage multiple confirmations in your own code instead'
)
if (hooks.indexOf(hook) === -1) {
hooks.push(hook)
}
}
return function () {
const hooks = RouteHooks[routeID]
if (hooks) {
const newHooks = hooks.filter(item => item !== hook)
if (newHooks.length === 0) {
removeListenBeforeHooksForRoute(route)
} else {
RouteHooks[routeID] = newHooks
}
}
}
}
/**
* This is the API for stateful environments. As the location
* changes, we update state and call the listener. We can also
* gracefully handle errors and redirects.
*/
function listen(listener) {
// TODO: Only use a single history listener. Otherwise we'll
// end up with multiple concurrent calls to match.
return history.listen(function (location) {
if (state.location === location) {
listener(null, state)
} else {
match(location, function (error, redirectLocation, nextState) {
if (error) {
listener(error)
} else if (redirectLocation) {
history.transitionTo(redirectLocation)
} else if (nextState) {
listener(null, nextState)
} else {
warning(
false,
'Location "%s" did not match any routes',
location.pathname + location.search + location.hash
)
}
})
}
})
}
return {
isActive,
match,
listenBeforeLeavingRoute,
listen
}
}
//export default useRoutes