Skip to content

Commit

Permalink
fix: types
Browse files Browse the repository at this point in the history
  • Loading branch information
s00d committed Sep 29, 2024
1 parent 594dc3c commit 7f62c66
Show file tree
Hide file tree
Showing 8 changed files with 408 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/runtime/plugins/01.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {
NavigationFailure,
RouteLocationNormalizedLoaded,
RouteLocationRaw,
RouteLocationRaw, RouteLocationResolved,
RouteLocationResolvedGeneric,
Router,
} from 'vue-router'
Expand Down Expand Up @@ -59,7 +59,6 @@ function switchLocaleRoute(fromLocale: string,
i18nConfig: ModuleOptionsExtend,
i18nRouteParams: I18nRouteParams,
): RouteLocationRaw {

const routeName = getRouteName(route, fromLocale)
if (router.hasRoute(`localized-${routeName}-${toLocale}`)) {
// const newParams = { ...route.params }
Expand Down Expand Up @@ -130,7 +129,7 @@ function getLocalizedRoute(
i18nConfig: ModuleOptionsExtend,
locale?: string,
hashLocale?: string | null,
): RouteLocationRaw {
): RouteLocationResolved {
const currentLocale = locale || getCurrentLocale(route, i18nConfig, hashLocale)
const selectRoute = router.resolve(to)
const routeName = getRouteName(selectRoute, currentLocale)
Expand Down Expand Up @@ -353,15 +352,15 @@ export default defineNuxtPlugin(async (nuxtApp) => {
}
switchLocale(fromLocale, toLocale, route, router, i18nConfig, i18nRouteParams.value)
},
localeRoute: (to: RouteLocationRaw, locale?: string): RouteLocationRaw => {
localeRoute: (to: RouteLocationRaw, locale?: string): RouteLocationResolved => {
const router = useRouter()
const route = useRoute()
return getLocalizedRoute(to, router, route, i18nConfig, locale, hashLocale)
},
localePath: (to: RouteLocationRaw, locale?: string): string => {
const router = useRouter()
const route = useRoute()
let localeRoute = getLocalizedRoute(to, router, route, i18nConfig, locale, hashLocale)
const localeRoute = getLocalizedRoute(to, router, route, i18nConfig, locale, hashLocale)
if (typeof localeRoute === 'string') {
return localeRoute
}
Expand Down Expand Up @@ -403,7 +402,7 @@ export interface PluginsInjections {
$switchLocaleRoute: (locale: string) => RouteLocationRaw
$switchLocalePath: (locale: string) => string
$switchLocale: (locale: string) => void
$localeRoute: (to: RouteLocationRaw, locale?: string) => RouteLocationRaw
$localeRoute: (to: RouteLocationRaw, locale?: string) => RouteLocationResolved
$localePath: (to: RouteLocationRaw, locale?: string) => string
$loadPageTranslations: (locale: string, routeName: string) => Promise<void>
$setI18nRouteParams: (value: I18nRouteParams) => I18nRouteParams
Expand Down
133 changes: 133 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ test.use({
nuxt: {
rootDir: fileURLToPath(new URL('./fixtures/basic', import.meta.url)),
},
// launchOptions: {
// headless: false, // Показывать браузер
// slowMo: 500, // Замедлить выполнение шагов (в миллисекундах) для лучшей видимости
// },
})

test('test index', async ({ page, goto }) => {
Expand Down Expand Up @@ -246,3 +250,132 @@ test('Test globalLocaleRoutes for page2 and unlocalized', async ({ page, goto })
const response = await page.goto('/de/unlocalized', { waitUntil: 'networkidle' })
expect(response?.status()).toBe(404)
})

test('test navigation and locale switching on news page', async ({ page, goto }) => {
// Переход на страницу /news/1
await goto('/news/1', { waitUntil: 'hydration' })

// Проверяем наличие id и данных news
await expect(page.locator('.news-id')).toHaveText('id: 1')
await expect(page.locator('.news-data')).toBeVisible()

// Проверяем переходы по ссылкам
await page.click('.link-article-1')
await expect(page).toHaveURL('/articles/1')

await goto('/news/1', { waitUntil: 'hydration' }) // Возвращаемся на страницу /news/1
await page.click('.link-news-4')
await expect(page).toHaveURL('/news/4')

// Проверяем переключение локалей
await page.click('.locale-en')
await expect(page).toHaveURL('/news/4')

await page.click('.locale-ru')
await expect(page).toHaveURL('/ru/news/4')

await page.click('.locale-de')
await expect(page).toHaveURL('/de/news/4')
})

test('test query parameters and hash on news page', async ({ page, goto }) => {
await goto('/news/2?a=b#tada', { waitUntil: 'hydration' })

// Проверяем, что id и query параметры корректно отображаются
await expect(page.locator('.news-id')).toHaveText('id: 2')
await expect(page).toHaveURL('/news/2?a=b#tada')

// Проверяем, что localeRoute корректно работает с query и hash
await page.click('.link-news-2')
await expect(page).toHaveURL('/news/2?a=b')
})

test('test navigation and locale switching on articles page', async ({ page, goto }) => {
// Navigate to the /articles/1 page
await goto('/articles/1', { waitUntil: 'hydration' })

// Check the presence of the id and article data
await expect(page.locator('.article-id')).toHaveText('id: 1')
await expect(page.locator('.article-data')).toBeVisible()

// Check the link transition to the news
await page.click('.link-news-1')
await expect(page).toHaveURL('/news/1')

// Check locale switching
await goto('/articles/1', { waitUntil: 'hydration' }) // Return to /articles/1
await page.click('.locale-en')
await expect(page).toHaveURL('/articles/1')

await page.click('.locale-ru')
await expect(page).toHaveURL('/ru/articles/1')

await page.click('.locale-de')
await expect(page).toHaveURL('/de/articles/1')
})

test('test locale switching and content on locale-conf page', async ({ page, goto }) => {
await goto('/', { waitUntil: 'hydration' })
await goto('/locale-conf', { waitUntil: 'hydration' })

await page.waitForTimeout(500)

// Check the page title in English
const titleEn = await page.locator('h1').textContent()
expect(titleEn).toBe('Locale Test Page')

// Check the page content in English
const contentEn = await page.locator('#content').textContent()
expect(contentEn).toBe('This is a content area.')

const greetingEn = await page.locator('#username').textContent()
expect(greetingEn).toBe('Hello, John!')

const pluralEn = await page.locator('#plural').textContent()
expect(pluralEn).toBe('You have 2 items.')

const htmlContentEn = await page.locator('#html-content').innerHTML()
expect(htmlContentEn).toContain('<strong>Bold Text</strong> with HTML content.')

const localeRouteEn = await page.locator('.locale-route-data:nth-of-type(1)').textContent()
expect(localeRouteEn).toContain('"fullPath": "/locale-conf"')
expect(localeRouteEn).toContain('"name": "locale-conf"')
expect(localeRouteEn).toContain('"href": "/locale-conf"')

// Check the first $switchLocaleRoute link in English
const switchLocaleRouteEn = await page.locator('#locale-en').getAttribute('href')
expect(switchLocaleRouteEn).toContain('/locale-conf')

// Check the second $switchLocaleRoute link in German
const switchLocaleRouteDe = await page.locator('#locale-de').getAttribute('href')
expect(switchLocaleRouteDe).toContain('/de/locale-conf-modif')

// Click on the element
await page.click('#locale-de')

await expect(page).toHaveURL('/de/locale-conf-modify')

// Check the page title in German
const titleDe = await page.locator('h1').textContent()
expect(titleDe).toBe('Sprachtestseite')

// Check the page content in German
const contentDe = await page.locator('#content').textContent()
expect(contentDe).toBe('Dies ist ein Inhaltsbereich.')

const greetingDe = await page.locator('#username').textContent()
expect(greetingDe).toBe('Hallo, John!')

const pluralDe = await page.locator('#plural').textContent()
expect(pluralDe).toBe('Sie haben 2 Artikel.')

const htmlContentDe = await page.locator('#html-content').innerHTML()
expect(htmlContentDe).toContain('<strong>Fetter Text</strong> mit HTML-Inhalt.')

const switchLocaleRouteEnN = await page.locator('#locale-en').getAttribute('href')
expect(switchLocaleRouteEnN).toContain('/locale-conf')

// Check the second $switchLocaleRoute link in German
const switchLocaleRouteDeN = await page.locator('#locale-de').getAttribute('href')
expect(switchLocaleRouteDeN).toContain('/de/locale-conf-modif')
})
56 changes: 56 additions & 0 deletions test/fixtures/basic/pages/articles/[id].vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<template>
<div>
<div class="article-id">
id: {{ params.id }}
</div>
<div class="article-data">
articles: {{ articles }}
</div>

<NuxtLink
class="link-news-1"
:to="$localeRoute({ name: 'news-id', params: { id: '1' } })"
>
news-1
</NuxtLink>

<div class="locale-switcher">
<NuxtLink
class="locale-en"
:to="$switchLocaleRoute('en')"
>
en
</NuxtLink>
<NuxtLink
class="locale-ru"
:to="$switchLocaleRoute('ru')"
>
ru
</NuxtLink>
<NuxtLink
class="locale-de"
:to="$switchLocaleRoute('de')"
>
de
</NuxtLink>
</div>
</div>
</template>

<script setup>
const { params } = useRoute()
const { $switchLocaleRoute } = useI18n()
const { data: articles } = await useAsyncData(
`articles-${params.id}`,
async () => {
return await $fetch('/api/getArticles', {
query: {
id: params.id,
},
})
},
)
</script>

<style></style>
83 changes: 83 additions & 0 deletions test/fixtures/basic/pages/locale-conf.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<template>
<div>
<h1>{{ $t('page.title') }}</h1>
<p id="content">
<i18n-t keypath="page.content" />
</p>
<p id="username">
<i18n-t
keypath="page.greeting"
:params="{ name: 'John' }"
/>
</p>
<p id="plural">
<i18n-t
keypath="page.items"
:plural="itemCount"
/>
</p>
<p id="html-content">
<i18n-t
keypath="page.htmlContent"
:html="true"
/>
</p>

<NuxtLink
id="locale-en"
:to="$switchLocaleRoute('en')"
>
Switch to en
</NuxtLink>
<NuxtLink
id="locale-de"
:to="$switchLocaleRoute('de')"
>
Switch to de
</NuxtLink>

<client-only>
<div class="locale-route-data">
{{ $localeRoute({ name: 'locale-conf' }, 'en') }}
</div>
<div class="locale-route-data">
{{ $localeRoute({ name: 'locale-conf' }, 'de') }}
</div>
</client-only>
</div>
</template>

<script setup>
import { useNuxtApp } from '#imports'
const { $defineI18nRoute } = useNuxtApp()
// Define translations directly on the page
$defineI18nRoute({
locales: {
en: {
page: {
title: 'Locale Test Page',
content: 'This is a content area.',
greeting: 'Hello, {name}!',
items: 'You have {count} items.',
htmlContent: '<strong>Bold Text</strong> with HTML content.',
},
},
de: {
page: {
title: 'Sprachtestseite',
content: 'Dies ist ein Inhaltsbereich.',
greeting: 'Hallo, {name}!',
items: 'Sie haben {count} Artikel.',
htmlContent: '<strong>Fetter Text</strong> mit HTML-Inhalt.',
},
},
},
localeRoutes: {
de: '/locale-conf-modify',
},
})
const itemCount = 2
</script>
Loading

0 comments on commit 7f62c66

Please sign in to comment.