/
RouterLink.ts
289 lines (268 loc) · 7.88 KB
/
RouterLink.ts
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
import {
defineComponent,
h,
PropType,
inject,
computed,
reactive,
unref,
VNodeProps,
AllowedComponentProps,
ComponentCustomProps,
getCurrentInstance,
watchEffect,
} from 'vue'
import { RouteLocationRaw, VueUseOptions, RouteLocation } from './types'
import { isSameRouteLocationParams, isSameRouteRecord } from './location'
import { routerKey, routeLocationKey } from './injectionSymbols'
import { RouteRecord } from './matcher/types'
import { NavigationFailure } from './errors'
export interface RouterLinkOptions {
/**
* Route Location the link should navigate to when clicked on.
*/
to: RouteLocationRaw
/**
* Calls `router.replace` instead of `router.push`.
*/
replace?: boolean
// TODO: refactor using extra options allowed in router.push. Needs RFC
}
export interface RouterLinkProps extends RouterLinkOptions {
/**
* Whether RouterLink should not wrap its content in an `a` tag. Useful when
* using `v-slot` to create a custom RouterLink
*/
custom?: boolean
/**
* Class to apply when the link is active
*/
activeClass?: string
/**
* Class to apply when the link is exact active
*/
exactActiveClass?: string
/**
* Value passed to the attribute `aria-current` when the link is exact active. Defaults to "page"
*/
ariaCurrentValue?:
| 'page'
| 'step'
| 'location'
| 'date'
| 'time'
| 'true'
| 'false'
}
export type UseLinkOptions = VueUseOptions<RouterLinkOptions>
// TODO: we could allow currentRoute as a prop to expose `isActive` and
// `isExactActive` behavior should go through an RFC
export function useLink(props: UseLinkOptions) {
const router = inject(routerKey)!
const currentRoute = inject(routeLocationKey)!
const route = computed(() => router.resolve(unref(props.to)))
const activeRecordIndex = computed<number>(() => {
let { matched } = route.value
let { length } = matched
const routeMatched: RouteRecord | undefined = matched[length - 1]
let currentMatched = currentRoute.matched
if (!routeMatched || !currentMatched.length) return -1
let index = currentMatched.findIndex(
isSameRouteRecord.bind(null, routeMatched)
)
if (index > -1) return index
// possible parent record
let parentRecordPath = getOriginalPath(
matched[length - 2] as RouteRecord | undefined
)
return (
// we are dealing with nested routes
length > 1 &&
// if the parent and matched route have the same path, this link is
// referring to the empty child. Or we currently are on a different
// child of the same parent
getOriginalPath(routeMatched) === parentRecordPath &&
// avoid comparing the child with its parent
currentMatched[currentMatched.length - 1].path !== parentRecordPath
? currentMatched.findIndex(
isSameRouteRecord.bind(null, matched[length - 2])
)
: index
)
})
const isActive = computed<boolean>(
() =>
activeRecordIndex.value > -1 &&
includesParams(currentRoute.params, route.value.params)
)
const isExactActive = computed<boolean>(
() =>
activeRecordIndex.value > -1 &&
activeRecordIndex.value === currentRoute.matched.length - 1 &&
isSameRouteLocationParams(currentRoute.params, route.value.params)
)
function navigate(
e: MouseEvent = {} as MouseEvent
): Promise<void | NavigationFailure> {
if (guardEvent(e))
return router[unref(props.replace) ? 'replace' : 'push'](unref(props.to))
return Promise.resolve()
}
return {
route,
href: computed(() => route.value.href),
isActive,
isExactActive,
navigate,
}
}
export const RouterLinkImpl = /*#__PURE__*/ defineComponent({
name: 'RouterLink',
props: {
to: {
type: [String, Object] as PropType<RouteLocationRaw>,
required: true,
},
replace: Boolean,
activeClass: String,
// inactiveClass: String,
exactActiveClass: String,
custom: Boolean,
ariaCurrentValue: {
type: String as PropType<RouterLinkProps['ariaCurrentValue']>,
default: 'page',
},
},
setup(props, { slots }) {
const link = reactive(useLink(props))
const { options } = inject(routerKey)!
const elClass = computed(() => ({
[getLinkClass(
props.activeClass,
options.linkActiveClass,
'router-link-active'
)]: link.isActive,
// [getLinkClass(
// props.inactiveClass,
// options.linkInactiveClass,
// 'router-link-inactive'
// )]: !link.isExactActive,
[getLinkClass(
props.exactActiveClass,
options.linkExactActiveClass,
'router-link-exact-active'
)]: link.isExactActive,
}))
if ((__DEV__ || __FEATURE_PROD_DEVTOOLS__) && __BROWSER__) {
const instance = getCurrentInstance()
watchEffect(
() => {
if (!instance) return
;(instance as any).__vrl_route = link.route
},
{ flush: 'post' }
)
watchEffect(
() => {
if (!instance) return
;(instance as any).__vrl_active = link.isActive
;(instance as any).__vrl_exactActive = link.isExactActive
},
{ flush: 'post' }
)
}
return () => {
const children = slots.default && slots.default(link)
return props.custom
? children
: h(
'a',
{
'aria-current': link.isExactActive
? props.ariaCurrentValue
: null,
href: link.href,
// this would override user added attrs but Vue will still add
// the listener so we end up triggering both
onClick: link.navigate,
class: elClass.value,
},
children
)
}
},
})
// export the public type for h/tsx inference
// also to avoid inline import() in generated d.ts files
/**
* Component to render a link that triggers a navigation on click.
*/
export const RouterLink = (RouterLinkImpl as any) as {
new (): {
$props: AllowedComponentProps &
ComponentCustomProps &
VNodeProps &
RouterLinkProps
}
}
function guardEvent(e: MouseEvent) {
// don't redirect with control keys
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return
// don't redirect when preventDefault called
if (e.defaultPrevented) return
// don't redirect on right click
if (e.button !== undefined && e.button !== 0) return
// don't redirect if `target="_blank"`
// @ts-ignore getAttribute does exist
if (e.currentTarget && e.currentTarget.getAttribute) {
// @ts-ignore getAttribute exists
const target = e.currentTarget.getAttribute('target')
if (/\b_blank\b/i.test(target)) return
}
// this may be a Weex event which doesn't have this method
if (e.preventDefault) e.preventDefault()
return true
}
function includesParams(
outer: RouteLocation['params'],
inner: RouteLocation['params']
): boolean {
for (let key in inner) {
let innerValue = inner[key]
let outerValue = outer[key]
if (typeof innerValue === 'string') {
if (innerValue !== outerValue) return false
} else {
if (
!Array.isArray(outerValue) ||
outerValue.length !== innerValue.length ||
innerValue.some((value, i) => value !== outerValue[i])
)
return false
}
}
return true
}
/**
* Get the original path value of a record by following its aliasOf
* @param record
*/
function getOriginalPath(record: RouteRecord | undefined): string {
return record ? (record.aliasOf ? record.aliasOf.path : record.path) : ''
}
/**
* Utility class to get the active class based on defaults.
* @param propClass
* @param globalClass
* @param defaultClass
*/
const getLinkClass = (
propClass: string | undefined,
globalClass: string | undefined,
defaultClass: string
): string =>
propClass != null
? propClass
: globalClass != null
? globalClass
: defaultClass