Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: redirect to cookie locale if set #5

Merged
merged 7 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,4 @@ Temporary Items

*.tgz
.prettierrc
.vscode
2 changes: 1 addition & 1 deletion src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export function localizeRoutes(

// Get custom path if any
if (componentOptions.paths && componentOptions.paths[locale]) {
path = componentOptions.paths[locale]
path = componentOptions.paths[locale]!
}

const isChildWithRelativePath = isChild && !path.startsWith('/')
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/composables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function useLocale<T>(
function localizePath(path: string, targetLocale?: Lang) {
targetLocale = targetLocale || locale.value
const parts = path.replace(/^\//, '').split('/')
options.locales.includes(parts[0]) && parts.shift()
options.locales.includes(parts[0]!) && parts.shift()
parts.unshift(targetLocale === options.defaultLocale ? '' : targetLocale)
return parts.join('/').replace(/^\/?/, '/')
}
Expand Down
34 changes: 24 additions & 10 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import {
import { getLocaleFromRoute } from './utils'
import { options } from '#build/i18n'

const clean = (str: string) => str.split('-')[0].trim().toLowerCase()

export default defineNuxtPlugin({
name: 'nuxt-i18n-plugin',
enforce: 'pre',
Expand All @@ -19,14 +17,29 @@ export default defineNuxtPlugin({
addRouteMiddleware(
'nuxt-i18n-middleware',
async (to) => {
if (to.path === '/' && !useCookie('i18n_redirected').value) {
if (to.path === '/') {
const cookieLocale = useCookie('i18n_redirected').value

if (cookieLocale && options.locales.includes(cookieLocale)) {
if (cookieLocale !== options.defaultLocale) {
return navigateTo(`/${cookieLocale}`)
} else {
useState<string>('locale').value = options.defaultLocale
return
}
}

const headerLocale = (
useRequestHeaders(['accept-language'])['accept-language'] || ''
)
.split(',')
.map((l) => clean(l.split(';')[0]))
.map((l) => clean(l.split(';')[0]!))
.filter((l) => options.locales.includes(l))[0]

if (headerLocale && headerLocale !== options.defaultLocale) {
return navigateTo(`/${headerLocale}`)
}

const browserLocale
= typeof document !== 'undefined'
? navigator.languages
Expand All @@ -37,18 +50,19 @@ export default defineNuxtPlugin({
: '')
: ''

const locale = headerLocale || browserLocale
if (locale && locale !== options.defaultLocale) {
return navigateTo(`/${locale}`)
if (browserLocale && browserLocale !== options.defaultLocale) {
return navigateTo(`/${browserLocale}`)
}
}

const targetLocale = getLocaleFromRoute(to) || options.defaultLocale
if (targetLocale && options.locales.includes(targetLocale)) {
useState<string>('locale').value = targetLocale
}
useState<string>('locale').value = targetLocale
},
{ global: true }
)
}
})

function clean(str: string) {
return str.split('-')[0]!.trim().toLowerCase()
}
6 changes: 3 additions & 3 deletions src/runtime/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ export function getLocaleFromRoute(
if (route.name) {
const name = isString(route.name) ? route.name : route.name.toString()
const matches = name.match(regexpName)
if (matches && matches.length > 1) { return matches[1] }
if (matches && matches.length > 1) { return matches[1]! }
} else if (route.path) {
// Extract from path
const matches = route.path.match(regexpPath)
if (matches && matches.length > 1) { return matches[1] }
if (matches && matches.length > 1) { return matches[1]! }
}
} else if (isString(route)) {
const matches = route.match(regexpPath)
if (matches && matches.length > 1) { return matches[1] }
if (matches && matches.length > 1) { return matches[1]! }
}

return ''
Expand Down
2 changes: 1 addition & 1 deletion test/unit/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('localizeRoutes', () => {
]
}
]
const children = routes[0].children!
const children = routes[0]!.children!

const localeCodes = ['en', 'ja']
const localizedRoutes = localizeRoutes(routes, {
Expand Down
5 changes: 4 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"extends": "./.nuxt/tsconfig.json"
"extends": "./.nuxt/tsconfig.json",
"compilerOptions": {
"noUncheckedIndexedAccess": true
}
}
Loading