-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
RouterLink.ts
397 lines (366 loc) · 10.3 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import {
defineComponent,
h,
PropType,
inject,
computed,
reactive,
unref,
VNode,
UnwrapRef,
VNodeProps,
AllowedComponentProps,
ComponentCustomProps,
getCurrentInstance,
watchEffect,
// this is a workaround for https://github.com/microsoft/rushstack/issues/1050
// this file is meant to be prepended to the generated dist/src/RouterLink.d.ts
// @ts-ignore
ComputedRef,
// @ts-ignore
DefineComponent,
// @ts-ignore
RendererElement,
// @ts-ignore
RendererNode,
// @ts-ignore
ComponentOptionsMixin,
} from 'vue'
import {
isRouteLocation,
RouteLocationRaw,
VueUseOptions,
RouteLocation,
RouteLocationNormalized,
} from './types'
import { isSameRouteLocationParams, isSameRouteRecord } from './location'
import { routerKey, routeLocationKey } from './injectionSymbols'
import { RouteRecord } from './matcher/types'
import { NavigationFailure } from './errors'
import { isArray, isBrowser, noop } from './utils'
import { warn } from './warning'
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.
*
* @defaultValue `'page'`
*/
ariaCurrentValue?:
| 'page'
| 'step'
| 'location'
| 'date'
| 'time'
| 'true'
| 'false'
}
export interface UseLinkDevtoolsContext {
route: RouteLocationNormalized & { href: string }
isActive: boolean
isExactActive: boolean
error: string | null
}
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)!
let hasPrevious = false
let previousTo: unknown = null
const route = computed(() => {
const to = unref(props.to)
if (__DEV__ && (!hasPrevious || to !== previousTo)) {
if (!isRouteLocation(to)) {
if (hasPrevious) {
warn(
`Invalid value for prop "to" in useLink()\n- to:`,
to,
`\n- previous to:`,
previousTo,
`\n- props:`,
props
)
} else {
warn(
`Invalid value for prop "to" in useLink()\n- to:`,
to,
`\n- props:`,
props
)
}
}
previousTo = to
hasPrevious = true
}
return router.resolve(to)
})
const activeRecordIndex = computed<number>(() => {
const { matched } = route.value
const { length } = matched
const routeMatched: RouteRecord | undefined = matched[length - 1]
const currentMatched = currentRoute.matched
if (!routeMatched || !currentMatched.length) return -1
const index = currentMatched.findIndex(
isSameRouteRecord.bind(null, routeMatched)
)
if (index > -1) return index
// possible parent record
const 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)
// avoid uncaught errors are they are logged anyway
).catch(noop)
}
return Promise.resolve()
}
// devtools only
if ((__DEV__ || __FEATURE_PROD_DEVTOOLS__) && isBrowser) {
const instance = getCurrentInstance()
if (instance) {
const linkContextDevtools: UseLinkDevtoolsContext = {
route: route.value,
isActive: isActive.value,
isExactActive: isExactActive.value,
error: null,
}
// @ts-expect-error: this is internal
instance.__vrl_devtools = instance.__vrl_devtools || []
// @ts-expect-error: this is internal
instance.__vrl_devtools.push(linkContextDevtools)
watchEffect(
() => {
linkContextDevtools.route = route.value
linkContextDevtools.isActive = isActive.value
linkContextDevtools.isExactActive = isExactActive.value
linkContextDevtools.error = isRouteLocation(unref(props.to))
? null
: 'Invalid "to" value'
},
{ flush: 'post' }
)
}
}
/**
* NOTE: update {@link _RouterLinkI}'s `$slots` type when updating this
*/
return {
route,
href: computed(() => route.value.href),
isActive,
isExactActive,
navigate,
}
}
export const RouterLinkImpl = /*#__PURE__*/ defineComponent({
name: 'RouterLink',
compatConfig: { MODE: 3 },
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',
},
},
useLink,
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,
}))
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: _RouterLinkI = RouterLinkImpl as any
/**
* Typed version of the `RouterLink` component. Its generic defaults to the typed router, so it can be inferred
* automatically for JSX.
*
* @internal
*/
export interface _RouterLinkI {
new (): {
$props: AllowedComponentProps &
ComponentCustomProps &
VNodeProps &
RouterLinkProps
$slots: {
default?: ({
route,
href,
isActive,
isExactActive,
navigate,
}: UnwrapRef<ReturnType<typeof useLink>>) => VNode[]
}
}
/**
* Access to `useLink()` without depending on using vue-router
*
* @internal
*/
useLink: typeof useLink
}
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-expect-error getAttribute does exist
if (e.currentTarget && e.currentTarget.getAttribute) {
// @ts-expect-error 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 (const key in inner) {
const innerValue = inner[key]
const outerValue = outer[key]
if (typeof innerValue === 'string') {
if (innerValue !== outerValue) return false
} else {
if (
!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