fix: keep translation links in the current tab

pull/5158/head
lilianakatrina684-a11y 4 days ago
parent 4fc1db83d7
commit cf6b280ede

@ -1,4 +1,7 @@
import { ensureStartingSlash } from 'client/theme-default/support/utils'
import {
ensureStartingSlash,
isLinkExternal
} from 'client/theme-default/support/utils'
describe('client/theme-default/utils', () => {
describe('ensureStartingSlash', () => {
@ -9,4 +12,22 @@ describe('client/theme-default/utils', () => {
expect(ensureStartingSlash('/path/nested')).toBe('/path/nested')
})
})
describe('isLinkExternal', () => {
test('it detects external links by default', () => {
expect(isLinkExternal('https://vite.dev')).toBe(true)
expect(isLinkExternal('/guide/')).toBe(false)
})
test('it treats _blank targets as external by default', () => {
expect(isLinkExternal('/guide/', '_blank')).toBe(true)
})
test('it allows callers to override external detection', () => {
expect(isLinkExternal('https://cn.vite.dev', undefined, false)).toBe(
false
)
expect(isLinkExternal('/guide/', undefined, true)).toBe(true)
})
})
})

@ -1,21 +1,19 @@
<script lang="ts" setup>
import { computed } from 'vue'
import { normalizeLink } from '../support/utils'
import { EXTERNAL_URL_RE } from '../../shared'
import { isLinkExternal, normalizeLink } from '../support/utils'
const props = defineProps<{
tag?: string
href?: string
noIcon?: boolean
external?: boolean
target?: string
rel?: string
}>()
const tag = computed(() => props.tag ?? (props.href ? 'a' : 'span'))
const isExternal = computed(
() =>
(props.href && EXTERNAL_URL_RE.test(props.href)) ||
props.target === '_blank'
const isExternal = computed(() =>
isLinkExternal(props.href, props.target, props.external)
)
</script>

@ -21,6 +21,7 @@ const { localeLinks, currentLang } = useLangs({ correspondingLink: true })
<template v-for="locale in localeLinks" :key="locale.link">
<VPMenuLink
:item="locale"
:external="false"
:lang="locale.lang"
:hreflang="locale.lang"
rel="alternate"

@ -28,7 +28,10 @@ function toggle() {
<VPLink
class="link"
:href="locale.link"
:external="false"
:lang="locale.lang"
:hreflang="locale.lang"
rel="alternate"
:dir="locale.dir"
>
{{ locale.text }}

@ -20,6 +20,18 @@ export function ensureStartingSlash(path: string): string {
return path.startsWith('/') ? path : `/${path}`
}
export function isLinkExternal(
href?: string,
target?: string,
external?: boolean
): boolean {
if (external !== undefined) {
return external
}
return (!!href && isExternal(href)) || target === '_blank'
}
export function normalizeLink(url: string): string {
const { pathname, search, hash, protocol } = new URL(url, 'http://a.com')

Loading…
Cancel
Save