forked from nuxt/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nuxt-link.ts
332 lines (288 loc) · 9.89 KB
/
nuxt-link.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
import { defineComponent, h, ref, resolveComponent, PropType, computed, DefineComponent, ComputedRef, onMounted, onBeforeUnmount } from 'vue'
import type { RouteLocationRaw } from 'vue-router'
import { hasProtocol } from 'ufo'
import { preloadRouteComponents } from '../composables/preload'
import { navigateTo, useRouter } from '../composables/router'
import { useNuxtApp } from '../nuxt'
const firstNonUndefined = <T> (...args: (T | undefined)[]) => args.find(arg => arg !== undefined)
const DEFAULT_EXTERNAL_REL_ATTRIBUTE = 'noopener noreferrer'
export type NuxtLinkOptions = {
componentName?: string
externalRelAttribute?: string | null
activeClass?: string
exactActiveClass?: string
prefetchedClass?: string
}
export type NuxtLinkProps = {
// Routing
to?: string | RouteLocationRaw
href?: string | RouteLocationRaw
external?: boolean
replace?: boolean
custom?: boolean
// Attributes
target?: '_blank' | '_parent' | '_self' | '_top' | (string & {}) | null
rel?: string | null
noRel?: boolean
prefetch?: boolean
noPrefetch?: boolean
// Styling
activeClass?: string
exactActiveClass?: string
// Vue Router's `<RouterLink>` additional props
ariaCurrentValue?: string
}
// Polyfills for Safari support
// https://caniuse.com/requestidlecallback
const requestIdleCallback: Window['requestIdleCallback'] = process.server
? undefined as any
: (globalThis.requestIdleCallback || ((cb) => {
const start = Date.now()
const idleDeadline = {
didTimeout: false,
timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
}
return setTimeout(() => { cb(idleDeadline) }, 1)
}))
const cancelIdleCallback: Window['cancelIdleCallback'] = process.server
? null as any
: (globalThis.cancelIdleCallback || ((id) => { clearTimeout(id) }))
export function defineNuxtLink (options: NuxtLinkOptions) {
const componentName = options.componentName || 'NuxtLink'
const checkPropConflicts = (props: NuxtLinkProps, main: keyof NuxtLinkProps, sub: keyof NuxtLinkProps): void => {
if (process.dev && props[main] !== undefined && props[sub] !== undefined) {
console.warn(`[${componentName}] \`${main}\` and \`${sub}\` cannot be used together. \`${sub}\` will be ignored.`)
}
}
return defineComponent({
name: componentName,
props: {
// Routing
to: {
type: [String, Object] as PropType<string | RouteLocationRaw>,
default: undefined,
required: false
},
href: {
type: [String, Object] as PropType<string | RouteLocationRaw>,
default: undefined,
required: false
},
// Attributes
target: {
type: String as PropType<string>,
default: undefined,
required: false
},
rel: {
type: String as PropType<string>,
default: undefined,
required: false
},
noRel: {
type: Boolean as PropType<boolean>,
default: undefined,
required: false
},
// Prefetching
prefetch: {
type: Boolean as PropType<boolean>,
default: undefined,
required: false
},
noPrefetch: {
type: Boolean as PropType<boolean>,
default: undefined,
required: false
},
// Styling
activeClass: {
type: String as PropType<string>,
default: undefined,
required: false
},
exactActiveClass: {
type: String as PropType<string>,
default: undefined,
required: false
},
prefetchedClass: {
type: String as PropType<string>,
default: undefined,
required: false
},
// Vue Router's `<RouterLink>` additional props
replace: {
type: Boolean as PropType<boolean>,
default: undefined,
required: false
},
ariaCurrentValue: {
type: String as PropType<string>,
default: undefined,
required: false
},
// Edge cases handling
external: {
type: Boolean as PropType<boolean>,
default: undefined,
required: false
},
// Slot API
custom: {
type: Boolean as PropType<boolean>,
default: undefined,
required: false
}
},
setup (props, { slots }) {
const router = useRouter()
// Resolving `to` value from `to` and `href` props
const to: ComputedRef<string | RouteLocationRaw> = computed(() => {
checkPropConflicts(props, 'to', 'href')
return props.to || props.href || '' // Defaults to empty string (won't render any `href` attribute)
})
// Resolving link type
const isExternal = computed<boolean>(() => {
// External prop is explicitly set
if (props.external) {
return true
}
// When `target` prop is set, link is external
if (props.target && props.target !== '_self') {
return true
}
// When `to` is a route object then it's an internal link
if (typeof to.value === 'object') {
return false
}
return to.value === '' || hasProtocol(to.value, true)
})
// Prefetching
const prefetched = ref(false)
const el = process.server ? undefined : ref<HTMLElement | null>(null)
if (process.client) {
checkPropConflicts(props, 'prefetch', 'noPrefetch')
const shouldPrefetch = props.prefetch !== false && props.noPrefetch !== true && typeof to.value === 'string' && props.target !== '_blank' && !isSlowConnection()
if (shouldPrefetch) {
const nuxtApp = useNuxtApp()
const observer = useObserver()
let idleId: number
let unobserve: Function | null = null
onMounted(() => {
idleId = requestIdleCallback(() => {
if (el?.value?.tagName) {
unobserve = observer!.observe(el.value, async () => {
unobserve?.()
unobserve = null
await Promise.all([
nuxtApp.hooks.callHook('link:prefetch', to.value as string).catch(() => {}),
!isExternal.value && preloadRouteComponents(to.value as string, router).catch(() => {})
])
prefetched.value = true
})
}
})
})
onBeforeUnmount(() => {
if (idleId) { cancelIdleCallback(idleId) }
unobserve?.()
unobserve = null
})
}
}
return () => {
if (!isExternal.value) {
// Internal link
return h(
resolveComponent('RouterLink'),
{
ref: process.server ? undefined : (ref: any) => { el!.value = ref?.$el },
to: to.value,
...((prefetched.value && !props.custom) ? { class: props.prefetchedClass || options.prefetchedClass } : {}),
activeClass: props.activeClass || options.activeClass,
exactActiveClass: props.exactActiveClass || options.exactActiveClass,
replace: props.replace,
ariaCurrentValue: props.ariaCurrentValue,
custom: props.custom
},
slots.default
)
}
// Resolves `to` value if it's a route location object
// converts `'''` to `null` to prevent the attribute from being added as empty (`href=""`)
const href = typeof to.value === 'object' ? router.resolve(to.value)?.href ?? null : to.value || null
// Resolves `target` value
const target = props.target || null
// Resolves `rel`
checkPropConflicts(props, 'noRel', 'rel')
const rel = (props.noRel)
? null
// converts `""` to `null` to prevent the attribute from being added as empty (`rel=""`)
: firstNonUndefined<string | null>(props.rel, options.externalRelAttribute, href ? DEFAULT_EXTERNAL_REL_ATTRIBUTE : '') || null
const navigate = () => navigateTo(href, { replace: props.replace })
// https://router.vuejs.org/api/#custom
if (props.custom) {
if (!slots.default) {
return null
}
return slots.default({
href,
navigate,
route: router.resolve(href!),
rel,
target,
isExternal: isExternal.value,
isActive: false,
isExactActive: false
})
}
return h('a', { ref: el, href, rel, target }, slots.default?.())
}
}
}) as unknown as DefineComponent<NuxtLinkProps>
}
export default defineNuxtLink({ componentName: 'NuxtLink' })
// --- Prefetching utils ---
function useObserver () {
if (process.server) { return }
const nuxtApp = useNuxtApp()
if (nuxtApp._observer) {
return nuxtApp._observer
}
let observer: IntersectionObserver | null = null
type CallbackFn = () => void
const callbacks = new Map<Element, CallbackFn>()
const observe = (element: Element, callback: CallbackFn) => {
if (!observer) {
observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const callback = callbacks.get(entry.target)
const isVisible = entry.isIntersecting || entry.intersectionRatio > 0
if (isVisible && callback) { callback() }
}
})
}
callbacks.set(element, callback)
observer.observe(element)
return () => {
callbacks.delete(element)
observer!.unobserve(element)
if (callbacks.size === 0) {
observer!.disconnect()
observer = null
}
}
}
const _observer = nuxtApp._observer = {
observe
}
return _observer
}
function isSlowConnection () {
if (process.server) { return }
// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection
const cn = (navigator as any).connection as { saveData: boolean, effectiveType: string } | null
if (cn && (cn.saveData || /2g/.test(cn.effectiveType))) { return true }
return false
}