-
Notifications
You must be signed in to change notification settings - Fork 171
/
VLink.vue
102 lines (96 loc) · 2.65 KB
/
VLink.vue
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
<!-- eslint-disable vue/no-restricted-syntax -->
<template>
<NuxtLink
v-if="isNuxtLink"
:class="{ 'inline-flex w-max items-center gap-x-2': showExternalIcon }"
:to="linkTo"
v-on="$listeners"
@click.native="$emit('click', $event)"
>
<slot />
</NuxtLink>
<a
v-else
:href="href"
target="_blank"
rel="noopener noreferrer"
:role="href ? undefined : 'link'"
:aria-disabled="!href"
:class="{ 'inline-flex w-max items-center gap-x-2': showExternalIcon }"
v-on="$listeners"
>
<slot /><VIcon
v-if="showExternalIcon && !isInternal"
name="external-link"
class="inline-block"
:size="externalIconSize"
rtl-flip
/>
</a>
</template>
<script lang="ts">
/**
* This is a wrapper component for all links. If `href` prop is undefined,
* the link will be rendered as a disabled: an `<a>` element without `href`
* attribute and with `role="link"` and `aria-disabled="true"` attributes.
* Links with `href` starting with `/` are treated as internal links.
*
* Internal links use `NuxtLink` component with `to` attribute set to `localePath(href)`
* External links use `a` element set to open in a new tab and not raise an error with the current iframe setup.
*/
import { computed, defineComponent } from "vue"
import { useContext } from "@nuxtjs/composition-api"
import VIcon from "~/components/VIcon/VIcon.vue"
export default defineComponent({
name: "VLink",
components: { VIcon },
props: {
href: {
type: String,
required: false,
validator: (v: string | undefined) =>
(typeof v === "string" && v.length > 0) || typeof v === "undefined",
},
/**
* whether to render the external link icon next to links that point away
* from Openverse
*/
showExternalIcon: {
type: Boolean,
default: false,
},
/**
* The size of external link icon.
*/
externalIconSize: {
type: Number,
default: 4,
},
},
setup(props) {
const { app } = useContext()
function checkHref(p: typeof props): p is {
href: string
showExternalIcon: boolean
externalIconSize: number
} {
return typeof p.href === "string" && !["", "#"].includes(p.href)
}
const hasHref = computed(() => checkHref(props))
const isInternal = computed(
() => hasHref.value && props.href?.startsWith("/")
)
const isNuxtLink = computed(() => hasHref.value && isInternal.value)
let linkTo = computed(() =>
checkHref(props) && isInternal.value
? app?.localePath(props.href) ?? props.href
: null
)
return {
linkTo,
isNuxtLink,
isInternal,
}
},
})
</script>