feat(i18n): enhance language management by saving user preference and auto detect browser language (#487)

* feat(i18n): enhance language management by saving user preference and detecting browser language

- Added a watcher to save the selected language to localStorage on change.
- Implemented browser language detection to set the default language based on user settings or browser preferences.

* use ~/utils/localstorage, remove setting savedLang in mounted as this is already set in i18.ts.

* do not repeat fallbackLocale and remove console log.

---------

Co-authored-by: Miroslav Šedivý <sedivy.miro@gmail.com>
This commit is contained in:
Javier Pérez 2025-03-22 23:56:43 +01:00 committed by GitHub
parent 4e335efb1e
commit 212bf8a607
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 29 additions and 3 deletions

View file

@ -60,8 +60,9 @@
</style> </style>
<script lang="ts"> <script lang="ts">
import { Component, Vue } from 'vue-property-decorator' import { Component, Vue, Watch } from 'vue-property-decorator'
import { messages } from '~/locale' import { messages } from '~/locale'
import { set } from '~/utils/localstorage'
@Component({ name: 'neko-menu' }) @Component({ name: 'neko-menu' })
export default class extends Vue { export default class extends Vue {
@ -77,6 +78,11 @@
this.$accessor.client.toggleAbout() this.$accessor.client.toggleAbout()
} }
@Watch('$i18n.locale')
onLanguageChange(newLang: string) {
set('lang', newLang)
}
mounted() { mounted() {
const default_lang = new URL(location.href).searchParams.get('lang') const default_lang = new URL(location.href).searchParams.get('lang')
if (default_lang && this.langs.includes(default_lang)) { if (default_lang && this.langs.includes(default_lang)) {

View file

@ -1,11 +1,31 @@
import Vue from 'vue' import Vue from 'vue'
import VueI18n from 'vue-i18n' import VueI18n from 'vue-i18n'
import { messages } from '~/locale' import { messages } from '~/locale'
import { get } from '~/utils/localstorage'
Vue.use(VueI18n) Vue.use(VueI18n)
const fallbackLocale = 'en'
function detectBrowserLanguage(): string {
const browserLang = navigator.language.toLowerCase()
const supportedLangs = Object.keys(messages)
if (supportedLangs.includes(browserLang)) {
return browserLang
}
const baseLang = browserLang.split('-')[0]
const matchingLang = supportedLangs.find((lang) => lang.startsWith(baseLang))
if (matchingLang) {
return matchingLang
}
return fallbackLocale
}
export const i18n = new VueI18n({ export const i18n = new VueI18n({
locale: 'en', locale: get<string>('lang', detectBrowserLanguage()),
fallbackLocale: 'en', fallbackLocale,
messages, messages,
}) })