kdu-router 3.4.0-beta.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +8 -6
  3. package/dist/kdu-router.cjs.js +2848 -0
  4. package/dist/kdu-router.cjs.prod.js +2610 -0
  5. package/dist/kdu-router.d.ts +1255 -0
  6. package/dist/kdu-router.esm-browser.js +3332 -0
  7. package/dist/kdu-router.esm-bundler.js +3343 -0
  8. package/dist/kdu-router.global.js +3354 -0
  9. package/dist/kdu-router.global.prod.js +6 -0
  10. package/ketur/attributes.json +8 -14
  11. package/ketur/tags.json +2 -12
  12. package/package.json +64 -92
  13. package/dist/kdu-router.common.js +0 -3040
  14. package/dist/kdu-router.esm.browser.js +0 -3005
  15. package/dist/kdu-router.esm.browser.min.js +0 -11
  16. package/dist/kdu-router.esm.js +0 -3038
  17. package/dist/kdu-router.js +0 -3046
  18. package/dist/kdu-router.min.js +0 -11
  19. package/src/components/link.js +0 -197
  20. package/src/components/view.js +0 -149
  21. package/src/create-matcher.js +0 -200
  22. package/src/create-route-map.js +0 -205
  23. package/src/history/abstract.js +0 -68
  24. package/src/history/base.js +0 -400
  25. package/src/history/hash.js +0 -163
  26. package/src/history/html5.js +0 -94
  27. package/src/index.js +0 -277
  28. package/src/install.js +0 -52
  29. package/src/util/async.js +0 -18
  30. package/src/util/dom.js +0 -3
  31. package/src/util/errors.js +0 -85
  32. package/src/util/location.js +0 -69
  33. package/src/util/misc.js +0 -6
  34. package/src/util/params.js +0 -37
  35. package/src/util/path.js +0 -74
  36. package/src/util/push-state.js +0 -46
  37. package/src/util/query.js +0 -96
  38. package/src/util/resolve-components.js +0 -109
  39. package/src/util/route.js +0 -132
  40. package/src/util/scroll.js +0 -165
  41. package/src/util/state-key.js +0 -22
  42. package/src/util/warn.js +0 -14
  43. package/types/index.d.ts +0 -17
  44. package/types/kdu.d.ts +0 -22
  45. package/types/router.d.ts +0 -170
@@ -1,205 +0,0 @@
1
- /* @flow */
2
-
3
- import Regexp from 'path-to-regexp'
4
- import { cleanPath } from './util/path'
5
- import { assert, warn } from './util/warn'
6
-
7
- export function createRouteMap (
8
- routes: Array<RouteConfig>,
9
- oldPathList?: Array<string>,
10
- oldPathMap?: Dictionary<RouteRecord>,
11
- oldNameMap?: Dictionary<RouteRecord>
12
- ): {
13
- pathList: Array<string>,
14
- pathMap: Dictionary<RouteRecord>,
15
- nameMap: Dictionary<RouteRecord>
16
- } {
17
- // the path list is used to control path matching priority
18
- const pathList: Array<string> = oldPathList || []
19
- // $flow-disable-line
20
- const pathMap: Dictionary<RouteRecord> = oldPathMap || Object.create(null)
21
- // $flow-disable-line
22
- const nameMap: Dictionary<RouteRecord> = oldNameMap || Object.create(null)
23
-
24
- routes.forEach(route => {
25
- addRouteRecord(pathList, pathMap, nameMap, route)
26
- })
27
-
28
- // ensure wildcard routes are always at the end
29
- for (let i = 0, l = pathList.length; i < l; i++) {
30
- if (pathList[i] === '*') {
31
- pathList.push(pathList.splice(i, 1)[0])
32
- l--
33
- i--
34
- }
35
- }
36
-
37
- if (process.env.NODE_ENV === 'development') {
38
- // warn if routes do not include leading slashes
39
- const found = pathList
40
- // check for missing leading slash
41
- .filter(path => path && path.charAt(0) !== '*' && path.charAt(0) !== '/')
42
-
43
- if (found.length > 0) {
44
- const pathNames = found.map(path => `- ${path}`).join('\n')
45
- warn(false, `Non-nested routes must include a leading slash character. Fix the following routes: \n${pathNames}`)
46
- }
47
- }
48
-
49
- return {
50
- pathList,
51
- pathMap,
52
- nameMap
53
- }
54
- }
55
-
56
- function addRouteRecord (
57
- pathList: Array<string>,
58
- pathMap: Dictionary<RouteRecord>,
59
- nameMap: Dictionary<RouteRecord>,
60
- route: RouteConfig,
61
- parent?: RouteRecord,
62
- matchAs?: string
63
- ) {
64
- const { path, name } = route
65
- if (process.env.NODE_ENV !== 'production') {
66
- assert(path != null, `"path" is required in a route configuration.`)
67
- assert(
68
- typeof route.component !== 'string',
69
- `route config "component" for path: ${String(
70
- path || name
71
- )} cannot be a ` + `string id. Use an actual component instead.`
72
- )
73
- }
74
-
75
- const pathToRegexpOptions: PathToRegexpOptions =
76
- route.pathToRegexpOptions || {}
77
- const normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict)
78
-
79
- if (typeof route.caseSensitive === 'boolean') {
80
- pathToRegexpOptions.sensitive = route.caseSensitive
81
- }
82
-
83
- const record: RouteRecord = {
84
- path: normalizedPath,
85
- regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
86
- components: route.components || { default: route.component },
87
- instances: {},
88
- name,
89
- parent,
90
- matchAs,
91
- redirect: route.redirect,
92
- beforeEnter: route.beforeEnter,
93
- meta: route.meta || {},
94
- props:
95
- route.props == null
96
- ? {}
97
- : route.components
98
- ? route.props
99
- : { default: route.props }
100
- }
101
-
102
- if (route.children) {
103
- // Warn if route is named, does not redirect and has a default child route.
104
- // If users navigate to this route by name, the default child will
105
- // not be rendered (GH Issue #629)
106
- if (process.env.NODE_ENV !== 'production') {
107
- if (
108
- route.name &&
109
- !route.redirect &&
110
- route.children.some(child => /^\/?$/.test(child.path))
111
- ) {
112
- warn(
113
- false,
114
- `Named Route '${route.name}' has a default child route. ` +
115
- `When navigating to this named route (:to="{name: '${
116
- route.name
117
- }'"), ` +
118
- `the default child route will not be rendered. Remove the name from ` +
119
- `this route and use the name of the default child route for named ` +
120
- `links instead.`
121
- )
122
- }
123
- }
124
- route.children.forEach(child => {
125
- const childMatchAs = matchAs
126
- ? cleanPath(`${matchAs}/${child.path}`)
127
- : undefined
128
- addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs)
129
- })
130
- }
131
-
132
- if (!pathMap[record.path]) {
133
- pathList.push(record.path)
134
- pathMap[record.path] = record
135
- }
136
-
137
- if (route.alias !== undefined) {
138
- const aliases = Array.isArray(route.alias) ? route.alias : [route.alias]
139
- for (let i = 0; i < aliases.length; ++i) {
140
- const alias = aliases[i]
141
- if (process.env.NODE_ENV !== 'production' && alias === path) {
142
- warn(
143
- false,
144
- `Found an alias with the same value as the path: "${path}". You have to remove that alias. It will be ignored in development.`
145
- )
146
- // skip in dev to make it work
147
- continue
148
- }
149
-
150
- const aliasRoute = {
151
- path: alias,
152
- children: route.children
153
- }
154
- addRouteRecord(
155
- pathList,
156
- pathMap,
157
- nameMap,
158
- aliasRoute,
159
- parent,
160
- record.path || '/' // matchAs
161
- )
162
- }
163
- }
164
-
165
- if (name) {
166
- if (!nameMap[name]) {
167
- nameMap[name] = record
168
- } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
169
- warn(
170
- false,
171
- `Duplicate named routes definition: ` +
172
- `{ name: "${name}", path: "${record.path}" }`
173
- )
174
- }
175
- }
176
- }
177
-
178
- function compileRouteRegex (
179
- path: string,
180
- pathToRegexpOptions: PathToRegexpOptions
181
- ): RouteRegExp {
182
- const regex = Regexp(path, [], pathToRegexpOptions)
183
- if (process.env.NODE_ENV !== 'production') {
184
- const keys: any = Object.create(null)
185
- regex.keys.forEach(key => {
186
- warn(
187
- !keys[key.name],
188
- `Duplicate param keys in route with path: "${path}"`
189
- )
190
- keys[key.name] = true
191
- })
192
- }
193
- return regex
194
- }
195
-
196
- function normalizePath (
197
- path: string,
198
- parent?: RouteRecord,
199
- strict?: boolean
200
- ): string {
201
- if (!strict) path = path.replace(/\/$/, '')
202
- if (path[0] === '/') return path
203
- if (parent == null) return path
204
- return cleanPath(`${parent.path}/${path}`)
205
- }
@@ -1,68 +0,0 @@
1
- /* @flow */
2
-
3
- import type Router from '../index'
4
- import { History } from './base'
5
- import { NavigationFailureType, isNavigationFailure } from '../util/errors'
6
-
7
- export class AbstractHistory extends History {
8
- index: number
9
- stack: Array<Route>
10
-
11
- constructor (router: Router, base: ?string) {
12
- super(router, base)
13
- this.stack = []
14
- this.index = -1
15
- }
16
-
17
- push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
18
- this.transitionTo(
19
- location,
20
- route => {
21
- this.stack = this.stack.slice(0, this.index + 1).concat(route)
22
- this.index++
23
- onComplete && onComplete(route)
24
- },
25
- onAbort
26
- )
27
- }
28
-
29
- replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
30
- this.transitionTo(
31
- location,
32
- route => {
33
- this.stack = this.stack.slice(0, this.index).concat(route)
34
- onComplete && onComplete(route)
35
- },
36
- onAbort
37
- )
38
- }
39
-
40
- go (n: number) {
41
- const targetIndex = this.index + n
42
- if (targetIndex < 0 || targetIndex >= this.stack.length) {
43
- return
44
- }
45
- const route = this.stack[targetIndex]
46
- this.confirmTransition(
47
- route,
48
- () => {
49
- this.index = targetIndex
50
- this.updateRoute(route)
51
- },
52
- err => {
53
- if (isNavigationFailure(err, NavigationFailureType.duplicated)) {
54
- this.index = targetIndex
55
- }
56
- }
57
- )
58
- }
59
-
60
- getCurrentLocation () {
61
- const current = this.stack[this.stack.length - 1]
62
- return current ? current.fullPath : '/'
63
- }
64
-
65
- ensureURL () {
66
- // noop
67
- }
68
- }
@@ -1,400 +0,0 @@
1
- /* @flow */
2
-
3
- import { _Kdu } from '../install'
4
- import type Router from '../index'
5
- import { inBrowser } from '../util/dom'
6
- import { runQueue } from '../util/async'
7
- import { warn } from '../util/warn'
8
- import { START, isSameRoute } from '../util/route'
9
- import {
10
- flatten,
11
- flatMapComponents,
12
- resolveAsyncComponents
13
- } from '../util/resolve-components'
14
- import {
15
- createNavigationDuplicatedError,
16
- createNavigationCancelledError,
17
- createNavigationRedirectedError,
18
- createNavigationAbortedError,
19
- isError,
20
- isNavigationFailure,
21
- NavigationFailureType
22
- } from '../util/errors'
23
-
24
- export class History {
25
- router: Router
26
- base: string
27
- current: Route
28
- pending: ?Route
29
- cb: (r: Route) => void
30
- ready: boolean
31
- readyCbs: Array<Function>
32
- readyErrorCbs: Array<Function>
33
- errorCbs: Array<Function>
34
- listeners: Array<Function>
35
- cleanupListeners: Function
36
-
37
- // implemented by sub-classes
38
- +go: (n: number) => void
39
- +push: (loc: RawLocation, onComplete?: Function, onAbort?: Function) => void
40
- +replace: (
41
- loc: RawLocation,
42
- onComplete?: Function,
43
- onAbort?: Function
44
- ) => void
45
- +ensureURL: (push?: boolean) => void
46
- +getCurrentLocation: () => string
47
- +setupListeners: Function
48
-
49
- constructor (router: Router, base: ?string) {
50
- this.router = router
51
- this.base = normalizeBase(base)
52
- // start with a route object that stands for "nowhere"
53
- this.current = START
54
- this.pending = null
55
- this.ready = false
56
- this.readyCbs = []
57
- this.readyErrorCbs = []
58
- this.errorCbs = []
59
- this.listeners = []
60
- }
61
-
62
- listen (cb: Function) {
63
- this.cb = cb
64
- }
65
-
66
- onReady (cb: Function, errorCb: ?Function) {
67
- if (this.ready) {
68
- cb()
69
- } else {
70
- this.readyCbs.push(cb)
71
- if (errorCb) {
72
- this.readyErrorCbs.push(errorCb)
73
- }
74
- }
75
- }
76
-
77
- onError (errorCb: Function) {
78
- this.errorCbs.push(errorCb)
79
- }
80
-
81
- transitionTo (
82
- location: RawLocation,
83
- onComplete?: Function,
84
- onAbort?: Function
85
- ) {
86
- let route
87
- try {
88
- route = this.router.match(location, this.current)
89
- } catch (e) {
90
- this.errorCbs.forEach(cb => {
91
- cb(e)
92
- })
93
- // Exception should still be thrown
94
- throw e
95
- }
96
- this.confirmTransition(
97
- route,
98
- () => {
99
- const prev = this.current
100
- this.updateRoute(route)
101
- onComplete && onComplete(route)
102
- this.ensureURL()
103
- this.router.afterHooks.forEach(hook => {
104
- hook && hook(route, prev)
105
- })
106
-
107
- // fire ready cbs once
108
- if (!this.ready) {
109
- this.ready = true
110
- this.readyCbs.forEach(cb => {
111
- cb(route)
112
- })
113
- }
114
- },
115
- err => {
116
- if (onAbort) {
117
- onAbort(err)
118
- }
119
- if (err && !this.ready) {
120
- this.ready = true
121
- // Initial redirection should still trigger the onReady onSuccess
122
- if (!isNavigationFailure(err, NavigationFailureType.redirected)) {
123
- this.readyErrorCbs.forEach(cb => {
124
- cb(err)
125
- })
126
- } else {
127
- this.readyCbs.forEach(cb => {
128
- cb(route)
129
- })
130
- }
131
- }
132
- }
133
- )
134
- }
135
-
136
- confirmTransition (route: Route, onComplete: Function, onAbort?: Function) {
137
- const current = this.current
138
- const abort = err => {
139
- // changed after adding errors before that change,
140
- // redirect and aborted navigation would produce an err == null
141
- if (!isNavigationFailure(err) && isError(err)) {
142
- if (this.errorCbs.length) {
143
- this.errorCbs.forEach(cb => {
144
- cb(err)
145
- })
146
- } else {
147
- warn(false, 'uncaught error during route navigation:')
148
- console.error(err)
149
- }
150
- }
151
- onAbort && onAbort(err)
152
- }
153
- const lastRouteIndex = route.matched.length - 1
154
- const lastCurrentIndex = current.matched.length - 1
155
- if (
156
- isSameRoute(route, current) &&
157
- // in the case the route map has been dynamically appended to
158
- lastRouteIndex === lastCurrentIndex &&
159
- route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
160
- ) {
161
- this.ensureURL()
162
- return abort(createNavigationDuplicatedError(current, route))
163
- }
164
-
165
- const { updated, deactivated, activated } = resolveQueue(
166
- this.current.matched,
167
- route.matched
168
- )
169
-
170
- const queue: Array<?NavigationGuard> = [].concat(
171
- // in-component leave guards
172
- extractLeaveGuards(deactivated),
173
- // global before hooks
174
- this.router.beforeHooks,
175
- // in-component update hooks
176
- extractUpdateHooks(updated),
177
- // in-config enter guards
178
- activated.map(m => m.beforeEnter),
179
- // async components
180
- resolveAsyncComponents(activated)
181
- )
182
-
183
- this.pending = route
184
- const iterator = (hook: NavigationGuard, next) => {
185
- if (this.pending !== route) {
186
- return abort(createNavigationCancelledError(current, route))
187
- }
188
- try {
189
- hook(route, current, (to: any) => {
190
- if (to === false) {
191
- // next(false) -> abort navigation, ensure current URL
192
- this.ensureURL(true)
193
- abort(createNavigationAbortedError(current, route))
194
- } else if (isError(to)) {
195
- this.ensureURL(true)
196
- abort(to)
197
- } else if (
198
- typeof to === 'string' ||
199
- (typeof to === 'object' &&
200
- (typeof to.path === 'string' || typeof to.name === 'string'))
201
- ) {
202
- // next('/') or next({ path: '/' }) -> redirect
203
- abort(createNavigationRedirectedError(current, route))
204
- if (typeof to === 'object' && to.replace) {
205
- this.replace(to)
206
- } else {
207
- this.push(to)
208
- }
209
- } else {
210
- // confirm transition and pass on the value
211
- next(to)
212
- }
213
- })
214
- } catch (e) {
215
- abort(e)
216
- }
217
- }
218
-
219
- runQueue(queue, iterator, () => {
220
- const postEnterCbs = []
221
- const isValid = () => this.current === route
222
- // wait until async components are resolved before
223
- // extracting in-component enter guards
224
- const enterGuards = extractEnterGuards(activated, postEnterCbs, isValid)
225
- const queue = enterGuards.concat(this.router.resolveHooks)
226
- runQueue(queue, iterator, () => {
227
- if (this.pending !== route) {
228
- return abort(createNavigationCancelledError(current, route))
229
- }
230
- this.pending = null
231
- onComplete(route)
232
- if (this.router.app) {
233
- this.router.app.$nextTick(() => {
234
- postEnterCbs.forEach(cb => {
235
- cb()
236
- })
237
- })
238
- }
239
- })
240
- })
241
- }
242
-
243
- updateRoute (route: Route) {
244
- this.current = route
245
- this.cb && this.cb(route)
246
- }
247
-
248
- setupListeners () {
249
- // Default implementation is empty
250
- }
251
-
252
- teardownListeners () {
253
- this.listeners.forEach(cleanupListener => {
254
- cleanupListener()
255
- })
256
- this.listeners = []
257
- }
258
- }
259
-
260
- function normalizeBase (base: ?string): string {
261
- if (!base) {
262
- if (inBrowser) {
263
- // respect <base> tag
264
- const baseEl = document.querySelector('base')
265
- base = (baseEl && baseEl.getAttribute('href')) || '/'
266
- // strip full URL origin
267
- base = base.replace(/^https?:\/\/[^\/]+/, '')
268
- } else {
269
- base = '/'
270
- }
271
- }
272
- // make sure there's the starting slash
273
- if (base.charAt(0) !== '/') {
274
- base = '/' + base
275
- }
276
- // remove trailing slash
277
- return base.replace(/\/$/, '')
278
- }
279
-
280
- function resolveQueue (
281
- current: Array<RouteRecord>,
282
- next: Array<RouteRecord>
283
- ): {
284
- updated: Array<RouteRecord>,
285
- activated: Array<RouteRecord>,
286
- deactivated: Array<RouteRecord>
287
- } {
288
- let i
289
- const max = Math.max(current.length, next.length)
290
- for (i = 0; i < max; i++) {
291
- if (current[i] !== next[i]) {
292
- break
293
- }
294
- }
295
- return {
296
- updated: next.slice(0, i),
297
- activated: next.slice(i),
298
- deactivated: current.slice(i)
299
- }
300
- }
301
-
302
- function extractGuards (
303
- records: Array<RouteRecord>,
304
- name: string,
305
- bind: Function,
306
- reverse?: boolean
307
- ): Array<?Function> {
308
- const guards = flatMapComponents(records, (def, instance, match, key) => {
309
- const guard = extractGuard(def, name)
310
- if (guard) {
311
- return Array.isArray(guard)
312
- ? guard.map(guard => bind(guard, instance, match, key))
313
- : bind(guard, instance, match, key)
314
- }
315
- })
316
- return flatten(reverse ? guards.reverse() : guards)
317
- }
318
-
319
- function extractGuard (
320
- def: Object | Function,
321
- key: string
322
- ): NavigationGuard | Array<NavigationGuard> {
323
- if (typeof def !== 'function') {
324
- // extend now so that global mixins are applied.
325
- def = _Kdu.extend(def)
326
- }
327
- return def.options[key]
328
- }
329
-
330
- function extractLeaveGuards (deactivated: Array<RouteRecord>): Array<?Function> {
331
- return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
332
- }
333
-
334
- function extractUpdateHooks (updated: Array<RouteRecord>): Array<?Function> {
335
- return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
336
- }
337
-
338
- function bindGuard (guard: NavigationGuard, instance: ?_Kdu): ?NavigationGuard {
339
- if (instance) {
340
- return function boundRouteGuard () {
341
- return guard.apply(instance, arguments)
342
- }
343
- }
344
- }
345
-
346
- function extractEnterGuards (
347
- activated: Array<RouteRecord>,
348
- cbs: Array<Function>,
349
- isValid: () => boolean
350
- ): Array<?Function> {
351
- return extractGuards(
352
- activated,
353
- 'beforeRouteEnter',
354
- (guard, _, match, key) => {
355
- return bindEnterGuard(guard, match, key, cbs, isValid)
356
- }
357
- )
358
- }
359
-
360
- function bindEnterGuard (
361
- guard: NavigationGuard,
362
- match: RouteRecord,
363
- key: string,
364
- cbs: Array<Function>,
365
- isValid: () => boolean
366
- ): NavigationGuard {
367
- return function routeEnterGuard (to, from, next) {
368
- return guard(to, from, cb => {
369
- if (typeof cb === 'function') {
370
- cbs.push(() => {
371
- // #750
372
- // if a router-view is wrapped with an out-in transition,
373
- // the instance may not have been registered at this time.
374
- // we will need to poll for registration until current route
375
- // is no longer valid.
376
- poll(cb, match.instances, key, isValid)
377
- })
378
- }
379
- next(cb)
380
- })
381
- }
382
- }
383
-
384
- function poll (
385
- cb: any, // somehow flow cannot infer this is a function
386
- instances: Object,
387
- key: string,
388
- isValid: () => boolean
389
- ) {
390
- if (
391
- instances[key] &&
392
- !instances[key]._isBeingDestroyed // do not reuse being destroyed instance
393
- ) {
394
- cb(instances[key])
395
- } else if (isValid()) {
396
- setTimeout(() => {
397
- poll(cb, instances, key, isValid)
398
- }, 16)
399
- }
400
- }