kdu-router 3.1.3 → 3.4.0-beta.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.
@@ -0,0 +1,165 @@
1
+ /* @flow */
2
+
3
+ import type Router from '../index'
4
+ import { assert } from './warn'
5
+ import { getStateKey, setStateKey } from './state-key'
6
+ import { extend } from './misc'
7
+
8
+ const positionStore = Object.create(null)
9
+
10
+ export function setupScroll () {
11
+ // Prevent browser scroll behavior on History popstate
12
+ if ('scrollRestoration' in window.history) {
13
+ window.history.scrollRestoration = 'manual'
14
+ }
15
+ // Fix for #1585 for Firefox
16
+ // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
17
+ // Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
18
+ // window.location.protocol + '//' + window.location.host
19
+ // location.host contains the port and location.hostname doesn't
20
+ const protocolAndPath = window.location.protocol + '//' + window.location.host
21
+ const absolutePath = window.location.href.replace(protocolAndPath, '')
22
+ // preserve existing history state as it could be overriden by the user
23
+ const stateCopy = extend({}, window.history.state)
24
+ stateCopy.key = getStateKey()
25
+ window.history.replaceState(stateCopy, '', absolutePath)
26
+ window.addEventListener('popstate', handlePopState)
27
+ return () => {
28
+ window.removeEventListener('popstate', handlePopState)
29
+ }
30
+ }
31
+
32
+ export function handleScroll (
33
+ router: Router,
34
+ to: Route,
35
+ from: Route,
36
+ isPop: boolean
37
+ ) {
38
+ if (!router.app) {
39
+ return
40
+ }
41
+
42
+ const behavior = router.options.scrollBehavior
43
+ if (!behavior) {
44
+ return
45
+ }
46
+
47
+ if (process.env.NODE_ENV !== 'production') {
48
+ assert(typeof behavior === 'function', `scrollBehavior must be a function`)
49
+ }
50
+
51
+ // wait until re-render finishes before scrolling
52
+ router.app.$nextTick(() => {
53
+ const position = getScrollPosition()
54
+ const shouldScroll = behavior.call(
55
+ router,
56
+ to,
57
+ from,
58
+ isPop ? position : null
59
+ )
60
+
61
+ if (!shouldScroll) {
62
+ return
63
+ }
64
+
65
+ if (typeof shouldScroll.then === 'function') {
66
+ shouldScroll
67
+ .then(shouldScroll => {
68
+ scrollToPosition((shouldScroll: any), position)
69
+ })
70
+ .catch(err => {
71
+ if (process.env.NODE_ENV !== 'production') {
72
+ assert(false, err.toString())
73
+ }
74
+ })
75
+ } else {
76
+ scrollToPosition(shouldScroll, position)
77
+ }
78
+ })
79
+ }
80
+
81
+ export function saveScrollPosition () {
82
+ const key = getStateKey()
83
+ if (key) {
84
+ positionStore[key] = {
85
+ x: window.pageXOffset,
86
+ y: window.pageYOffset
87
+ }
88
+ }
89
+ }
90
+
91
+ function handlePopState (e) {
92
+ saveScrollPosition()
93
+ if (e.state && e.state.key) {
94
+ setStateKey(e.state.key)
95
+ }
96
+ }
97
+
98
+ function getScrollPosition (): ?Object {
99
+ const key = getStateKey()
100
+ if (key) {
101
+ return positionStore[key]
102
+ }
103
+ }
104
+
105
+ function getElementPosition (el: Element, offset: Object): Object {
106
+ const docEl: any = document.documentElement
107
+ const docRect = docEl.getBoundingClientRect()
108
+ const elRect = el.getBoundingClientRect()
109
+ return {
110
+ x: elRect.left - docRect.left - offset.x,
111
+ y: elRect.top - docRect.top - offset.y
112
+ }
113
+ }
114
+
115
+ function isValidPosition (obj: Object): boolean {
116
+ return isNumber(obj.x) || isNumber(obj.y)
117
+ }
118
+
119
+ function normalizePosition (obj: Object): Object {
120
+ return {
121
+ x: isNumber(obj.x) ? obj.x : window.pageXOffset,
122
+ y: isNumber(obj.y) ? obj.y : window.pageYOffset
123
+ }
124
+ }
125
+
126
+ function normalizeOffset (obj: Object): Object {
127
+ return {
128
+ x: isNumber(obj.x) ? obj.x : 0,
129
+ y: isNumber(obj.y) ? obj.y : 0
130
+ }
131
+ }
132
+
133
+ function isNumber (v: any): boolean {
134
+ return typeof v === 'number'
135
+ }
136
+
137
+ const hashStartsWithNumberRE = /^#\d/
138
+
139
+ function scrollToPosition (shouldScroll, position) {
140
+ const isObject = typeof shouldScroll === 'object'
141
+ if (isObject && typeof shouldScroll.selector === 'string') {
142
+ // getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
143
+ // but at the same time, it doesn't make much sense to select an element with an id and an extra selector
144
+ const el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
145
+ ? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
146
+ : document.querySelector(shouldScroll.selector)
147
+
148
+ if (el) {
149
+ let offset =
150
+ shouldScroll.offset && typeof shouldScroll.offset === 'object'
151
+ ? shouldScroll.offset
152
+ : {}
153
+ offset = normalizeOffset(offset)
154
+ position = getElementPosition(el, offset)
155
+ } else if (isValidPosition(shouldScroll)) {
156
+ position = normalizePosition(shouldScroll)
157
+ }
158
+ } else if (isObject && isValidPosition(shouldScroll)) {
159
+ position = normalizePosition(shouldScroll)
160
+ }
161
+
162
+ if (position) {
163
+ window.scrollTo(position.x, position.y)
164
+ }
165
+ }
@@ -0,0 +1,22 @@
1
+ /* @flow */
2
+ import { inBrowser } from './dom'
3
+
4
+ // use User Timing api (if present) for more accurate key precision
5
+ const Time =
6
+ inBrowser && window.performance && window.performance.now
7
+ ? window.performance
8
+ : Date
9
+
10
+ export function genStateKey (): string {
11
+ return Time.now().toFixed(3)
12
+ }
13
+
14
+ let _key: string = genStateKey()
15
+
16
+ export function getStateKey () {
17
+ return _key
18
+ }
19
+
20
+ export function setStateKey (key: string) {
21
+ return (_key = key)
22
+ }
@@ -0,0 +1,14 @@
1
+ /* @flow */
2
+
3
+ export function assert (condition: any, message: string) {
4
+ if (!condition) {
5
+ throw new Error(`[kdu-router] ${message}`)
6
+ }
7
+ }
8
+
9
+ export function warn (condition: any, message: string) {
10
+ if (process.env.NODE_ENV !== 'production' && !condition) {
11
+ typeof console !== 'undefined' && console.warn(`[kdu-router] ${message}`)
12
+ }
13
+ }
14
+
package/types/index.d.ts CHANGED
@@ -1,16 +1,17 @@
1
- import './kdu'
2
- import { KduRouter } from './router'
3
-
4
- export default KduRouter
5
-
6
- export {
7
- RouterMode,
8
- RawLocation,
9
- RedirectOption,
10
- RouterOptions,
11
- RouteConfig,
12
- RouteRecord,
13
- Location,
14
- Route,
15
- NavigationGuard
16
- } from './router'
1
+ import './kdu'
2
+ import { KduRouter } from './router'
3
+
4
+ export default KduRouter
5
+
6
+ export {
7
+ RouterMode,
8
+ RawLocation,
9
+ RedirectOption,
10
+ RouterOptions,
11
+ RouteConfig,
12
+ RouteRecord,
13
+ Location,
14
+ Route,
15
+ NavigationGuard,
16
+ NavigationGuardNext
17
+ } from './router'
package/types/kdu.d.ts CHANGED
@@ -1,22 +1,22 @@
1
- /**
2
- * Augment the typings of Kdu.js
3
- */
4
-
5
- import Kdu from 'kdu'
6
- import KduRouter, { Route, RawLocation, NavigationGuard } from './index'
7
-
8
- declare module 'kdu/types/kdu' {
9
- interface Kdu {
10
- $router: KduRouter
11
- $route: Route
12
- }
13
- }
14
-
15
- declare module 'kdu/types/options' {
16
- interface ComponentOptions<V extends Kdu> {
17
- router?: KduRouter
18
- beforeRouteEnter?: NavigationGuard<V>
19
- beforeRouteLeave?: NavigationGuard<V>
20
- beforeRouteUpdate?: NavigationGuard<V>
21
- }
22
- }
1
+ /**
2
+ * Augment the typings of Kdu.js
3
+ */
4
+
5
+ import Kdu from 'kdu'
6
+ import KduRouter, { Route, RawLocation, NavigationGuard } from './index'
7
+
8
+ declare module 'kdu/types/kdu' {
9
+ interface Kdu {
10
+ $router: KduRouter
11
+ $route: Route
12
+ }
13
+ }
14
+
15
+ declare module 'kdu/types/options' {
16
+ interface ComponentOptions<V extends Kdu> {
17
+ router?: KduRouter
18
+ beforeRouteEnter?: NavigationGuard<V>
19
+ beforeRouteLeave?: NavigationGuard<V>
20
+ beforeRouteUpdate?: NavigationGuard<V>
21
+ }
22
+ }
package/types/router.d.ts CHANGED
@@ -1,145 +1,170 @@
1
- import Kdu, { ComponentOptions, PluginFunction, AsyncComponent } from 'kdu'
2
-
3
- type Component = ComponentOptions<Kdu> | typeof Kdu | AsyncComponent
4
- type Dictionary < T > = { [key: string]: T }
5
- type ErrorHandler = (err: Error) => void
6
-
7
- export type RouterMode = 'hash' | 'history' | 'abstract'
8
- export type RawLocation = string | Location
9
- export type RedirectOption = RawLocation | ((to: Route) => RawLocation)
10
- export type NavigationGuard < V extends Kdu = Kdu > = (
11
- to: Route,
12
- from: Route,
13
- next: (to?: RawLocation | false | ((vm: V) => any) | void) => void
14
- ) => any
15
-
16
- export declare class KduRouter {
17
- constructor(options?: RouterOptions)
18
-
19
- app: Kdu
20
- mode: RouterMode
21
- currentRoute: Route
22
-
23
- beforeEach(guard: NavigationGuard): Function
24
- beforeResolve(guard: NavigationGuard): Function
25
- afterEach(hook: (to: Route, from: Route) => any): Function
26
- push(location: RawLocation): Promise<Route>
27
- replace(location: RawLocation): Promise<Route>
28
- push(
29
- location: RawLocation,
30
- onComplete?: Function,
31
- onAbort?: ErrorHandler
32
- ): void
33
- replace(
34
- location: RawLocation,
35
- onComplete?: Function,
36
- onAbort?: ErrorHandler
37
- ): void
38
- go(n: number): void
39
- back(): void
40
- forward(): void
41
- getMatchedComponents(to?: RawLocation | Route): Component[]
42
- onReady(cb: Function, errorCb?: ErrorHandler): void
43
- onError(cb: ErrorHandler): void
44
- addRoutes(routes: RouteConfig[]): void
45
- resolve(
46
- to: RawLocation,
47
- current?: Route,
48
- append?: boolean
49
- ): {
50
- location: Location
51
- route: Route
52
- href: string
53
- // backwards compat
54
- normalizedTo: Location
55
- resolved: Route
56
- }
57
-
58
- static install: PluginFunction<never>
59
- }
60
-
61
- type Position = { x: number; y: number }
62
- type PositionResult = Position | { selector: string; offset?: Position } | void
63
-
64
- export interface RouterOptions {
65
- routes?: RouteConfig[]
66
- mode?: RouterMode
67
- fallback?: boolean
68
- base?: string
69
- linkActiveClass?: string
70
- linkExactActiveClass?: string
71
- parseQuery?: (query: string) => Object
72
- stringifyQuery?: (query: Object) => string
73
- scrollBehavior?: (
74
- to: Route,
75
- from: Route,
76
- savedPosition: Position | void
77
- ) => PositionResult | Promise<PositionResult>
78
- }
79
-
80
- type RoutePropsFunction = (route: Route) => Object
81
-
82
- export interface PathToRegexpOptions {
83
- sensitive?: boolean
84
- strict?: boolean
85
- end?: boolean
86
- }
87
-
88
- export interface RouteConfig {
89
- path: string
90
- name?: string
91
- component?: Component
92
- components?: Dictionary<Component>
93
- redirect?: RedirectOption
94
- alias?: string | string[]
95
- children?: RouteConfig[]
96
- meta?: any
97
- beforeEnter?: NavigationGuard
98
- props?: boolean | Object | RoutePropsFunction
99
- caseSensitive?: boolean
100
- pathToRegexpOptions?: PathToRegexpOptions
101
- }
102
-
103
- export interface RouteRecord {
104
- path: string
105
- regex: RegExp
106
- components: Dictionary<Component>
107
- instances: Dictionary<Kdu>
108
- name?: string
109
- parent?: RouteRecord
110
- redirect?: RedirectOption
111
- matchAs?: string
112
- meta: any
113
- beforeEnter?: (
114
- route: Route,
115
- redirect: (location: RawLocation) => void,
116
- next: () => void
117
- ) => any
118
- props:
119
- | boolean
120
- | Object
121
- | RoutePropsFunction
122
- | Dictionary<boolean | Object | RoutePropsFunction>
123
- }
124
-
125
- export interface Location {
126
- name?: string
127
- path?: string
128
- hash?: string
129
- query?: Dictionary<string | (string | null)[] | null | undefined>
130
- params?: Dictionary<string>
131
- append?: boolean
132
- replace?: boolean
133
- }
134
-
135
- export interface Route {
136
- path: string
137
- name?: string
138
- hash: string
139
- query: Dictionary<string | (string | null)[]>
140
- params: Dictionary<string>
141
- fullPath: string
142
- matched: RouteRecord[]
143
- redirectedFrom?: string
144
- meta?: any
145
- }
1
+ import Kdu, { ComponentOptions, PluginFunction, AsyncComponent } from 'kdu'
2
+
3
+ type Component = ComponentOptions<Kdu> | typeof Kdu | AsyncComponent
4
+ type Dictionary<T> = { [key: string]: T }
5
+ type ErrorHandler = (err: Error) => void
6
+
7
+ export type RouterMode = 'hash' | 'history' | 'abstract'
8
+ export type RawLocation = string | Location
9
+ export type RedirectOption = RawLocation | ((to: Route) => RawLocation)
10
+ export type NavigationGuardNext<V extends Kdu = Kdu> = (
11
+ to?: RawLocation | false | ((vm: V) => any) | void
12
+ ) => void
13
+
14
+ export type NavigationGuard<V extends Kdu = Kdu> = (
15
+ to: Route,
16
+ from: Route,
17
+ next: NavigationGuardNext<V>
18
+ ) => any
19
+
20
+ export declare class KduRouter {
21
+ constructor(options?: RouterOptions)
22
+
23
+ app: Kdu
24
+ options: RouterOptions;
25
+ mode: RouterMode
26
+ currentRoute: Route
27
+
28
+ beforeEach(guard: NavigationGuard): Function
29
+ beforeResolve(guard: NavigationGuard): Function
30
+ afterEach(hook: (to: Route, from: Route) => any): Function
31
+ push(location: RawLocation): Promise<Route>
32
+ replace(location: RawLocation): Promise<Route>
33
+ push(
34
+ location: RawLocation,
35
+ onComplete?: Function,
36
+ onAbort?: ErrorHandler
37
+ ): void
38
+ replace(
39
+ location: RawLocation,
40
+ onComplete?: Function,
41
+ onAbort?: ErrorHandler
42
+ ): void
43
+ go(n: number): void
44
+ back(): void
45
+ forward(): void
46
+ getMatchedComponents(to?: RawLocation | Route): Component[]
47
+ onReady(cb: Function, errorCb?: ErrorHandler): void
48
+ onError(cb: ErrorHandler): void
49
+ addRoutes(routes: RouteConfig[]): void
50
+ resolve(
51
+ to: RawLocation,
52
+ current?: Route,
53
+ append?: boolean
54
+ ): {
55
+ location: Location
56
+ route: Route
57
+ href: string
58
+ // backwards compat
59
+ normalizedTo: Location
60
+ resolved: Route
61
+ }
62
+
63
+ static install: PluginFunction<never>
64
+ static version: string
65
+
66
+ static isNavigationFailure: (error: any, type?: NavigationFailureTypeE) => error is Error
67
+ static NavigationFailureType: NavigationFailureTypeE
68
+ }
69
+
70
+ export enum NavigationFailureTypeE {
71
+ redirected = 1,
72
+ aborted = 2,
73
+ cancelled = 3,
74
+ duplicated = 4
75
+ }
76
+
77
+ type Position = { x: number; y: number }
78
+ type PositionResult = Position | { selector: string; offset?: Position } | void
79
+
80
+ export interface RouterOptions {
81
+ routes?: RouteConfig[]
82
+ mode?: RouterMode
83
+ fallback?: boolean
84
+ base?: string
85
+ linkActiveClass?: string
86
+ linkExactActiveClass?: string
87
+ parseQuery?: (query: string) => Object
88
+ stringifyQuery?: (query: Object) => string
89
+ scrollBehavior?: (
90
+ to: Route,
91
+ from: Route,
92
+ savedPosition: Position | void
93
+ ) => PositionResult | Promise<PositionResult> | undefined | null
94
+ }
95
+
96
+ type RoutePropsFunction = (route: Route) => Object
97
+
98
+ export interface PathToRegexpOptions {
99
+ sensitive?: boolean
100
+ strict?: boolean
101
+ end?: boolean
102
+ }
103
+
104
+ interface _RouteConfigBase {
105
+ path: string
106
+ name?: string
107
+ children?: RouteConfig[]
108
+ redirect?: RedirectOption
109
+ alias?: string | string[]
110
+ meta?: any
111
+ beforeEnter?: NavigationGuard
112
+ caseSensitive?: boolean
113
+ pathToRegexpOptions?: PathToRegexpOptions
114
+ }
115
+
116
+ interface RouteConfigSingleView extends _RouteConfigBase {
117
+ component?: Component
118
+ props?: boolean | Object | RoutePropsFunction
119
+ }
120
+
121
+ interface RouteConfigMultipleViews extends _RouteConfigBase {
122
+ components?: Dictionary<Component>
123
+ props?: Dictionary<boolean | Object | RoutePropsFunction>
124
+ }
125
+
126
+ export type RouteConfig = RouteConfigSingleView | RouteConfigMultipleViews
127
+
128
+ export interface RouteRecord {
129
+ path: string
130
+ regex: RegExp
131
+ components: Dictionary<Component>
132
+ instances: Dictionary<Kdu>
133
+ name?: string
134
+ parent?: RouteRecord
135
+ redirect?: RedirectOption
136
+ matchAs?: string
137
+ meta: any
138
+ beforeEnter?: (
139
+ route: Route,
140
+ redirect: (location: RawLocation) => void,
141
+ next: () => void
142
+ ) => any
143
+ props:
144
+ | boolean
145
+ | Object
146
+ | RoutePropsFunction
147
+ | Dictionary<boolean | Object | RoutePropsFunction>
148
+ }
149
+
150
+ export interface Location {
151
+ name?: string
152
+ path?: string
153
+ hash?: string
154
+ query?: Dictionary<string | (string | null)[] | null | undefined>
155
+ params?: Dictionary<string>
156
+ append?: boolean
157
+ replace?: boolean
158
+ }
159
+
160
+ export interface Route {
161
+ path: string
162
+ name?: string | null
163
+ hash: string
164
+ query: Dictionary<string | (string | null)[]>
165
+ params: Dictionary<string>
166
+ fullPath: string
167
+ matched: RouteRecord[]
168
+ redirectedFrom?: string
169
+ meta?: any
170
+ }