Skip to content

fix: Fix default language when chat language is null #2204

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

Merged
merged 2 commits into from
Feb 10, 2025
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
4 changes: 2 additions & 2 deletions ui/src/locales/useLocale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ export function useLocale() {
function changeLocale(lang: string) {
// 如果切换的语言不在对应语言文件里则默认为简体中文
if (!langCode.includes(lang)) {
lang = 'zh-CN';
lang = 'en-US';
}

locale.value = lang;
useLocalStorage(localeConfigKey, 'zh-CN').value = lang;
useLocalStorage(localeConfigKey, 'en-US').value = lang;
}

const getComponentsLocale = computed(() => {
Expand Down
2 changes: 1 addition & 1 deletion ui/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const locale_map: any = {
'en-US': enUs
}
app.use(ElementPlus, {
locale: locale_map[localStorage.getItem('MaxKB-locale') || navigator.language || 'zh-CN']
locale: locale_map[localStorage.getItem('MaxKB-locale') || navigator.language || 'en-US']
})

app.use(router)
Expand Down
5 changes: 2 additions & 3 deletions ui/src/stores/modules/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { defineStore } from 'pinia'
import applicationApi from '@/api/application'
import applicationXpackApi from '@/api/application-xpack'
import { type Ref } from 'vue'

import { getBrowserLang } from '@/locales/index'
import useUserStore from './user'
const useApplicationStore = defineStore({
id: 'application',
Expand Down Expand Up @@ -79,8 +79,7 @@ const useApplicationStore = defineStore({
applicationApi
.getAppProfile(loading)
.then((res) => {
sessionStorage.setItem('language', res.data?.language)

sessionStorage.setItem('language', res.data?.language || getBrowserLang())
resolve(res)
})
.catch((error) => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this code, there seems to be an issue with setting sessionStorage.setItem('language'). When using the variable directly (getBrowserLang) without properly importing it or passing any arguments, it might result in errors. Ensure that getBrowserLang is correctly imported and used.

Suggested optimizations include:

  • Importing getBrowserLang at the beginning of the file to avoid confusion.
  • Verifying that getBrowserLang() returns a value before assigning it to localStorage.

Also, consider handling cases where res.data.language might not be available (e.g., null or undefined). This could make your app more robust.

Expand Down
6 changes: 3 additions & 3 deletions ui/src/stores/modules/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const useUserStore = defineStore({
getLanguage() {
return this.userType === 1
? localStorage.getItem('MaxKB-locale') || getBrowserLang()
: sessionStorage.getItem('language')
: sessionStorage.getItem('language') || getBrowserLang()
},
showXpack() {
return this.isXPack
Expand Down Expand Up @@ -124,7 +124,7 @@ const useUserStore = defineStore({
async profile() {
return UserApi.profile().then(async (ok) => {
this.userInfo = ok.data
useLocalStorage(localeConfigKey, 'zh-CN').value = ok.data?.language
useLocalStorage(localeConfigKey, 'en-US').value = ok.data?.language || this.getLanguage()
return this.asyncGetProfile()
})
},
Expand Down Expand Up @@ -171,7 +171,7 @@ const useUserStore = defineStore({
return new Promise((resolve, reject) => {
UserApi.postLanguage({ language: lang }, loading)
.then(async (ok) => {
useLocalStorage(localeConfigKey, 'zh-CN').value = lang
useLocalStorage(localeConfigKey, 'en-US').value = lang
window.location.reload()
resolve(ok)
})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code looks mostly correct but here are some minor improvements:

  1. Code Duplication:
    The useLocalStorage call with 'zh-CN' is repeated twice at lines 126 and 173. This could be optimized to a single call by using an array of languages and checking if the current language is in that list.

  2. Default Language Handling:
    It seems like you have two different behaviors for non-authenticated users regarding language handling:

    • For authenticated users (this.userType === 1), it prefers localStorage.
    • Otherwise, it defaults to sessionStorage.

    Ensure these behaviors align as expected for both cases (authenticated vs. unauthenticated).

  3. Async/await Style:
    Although not explicitly checked for async / await style consistency, consider whether all asynchronous operations should follow consistent patterns throughout your application.

Here's a slightly revised version incorporating the above points:

import { defineStore } from "pinia";

const useUserStore = defineStore({
  id: 'user',
  
  state: () => ({
    userType: null,
    userLang: '',
    userInfo: {},
  }),
  
  getters: {
    getLanguage() {
      return this.$auth.isAuthenticated 
        ? localStorage.getItem('MaxKB-locale') || getBrowserLang()
        : sessionStorage.getItem('language');
    },
    
    showXpack() {
      // Assuming $auth.isAuthenticated is part of your auth module
      return this.$auth.isAuthenticated && this.useAuthModule.someFunction(); // Replace with actual function name
    }
  },
  
  actions: {
    ...mapMutations(['setError']),
    
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },
    
    async postLanguage(langParam) {
      try {
        this.setError(null);
        
        const response = await UserApi.postLanguage({ language: langParam });
        this.setUserInfo(response.data);
        
        // Use local storage based on authentication status.
        setLocale(this.$auth.isAuthenticated ? localeConfigKey : 'storage_key', langParam); // Replace with your custom logic
        
        window.location.reload();
      } catch (error) {
        this.setError(error.message);
      }
    }
  }
});

// Helper function to determine appropriate localization strategy
function setLocale(key, value) {
  // Implement how you want to handle setting the locale (e.g., via store or environment variables)
}

export default useUserStore;

Key Changes:

  • Removed duplicated useLocalStorage('zh-CN') calls.
  • Assumed $auth.isAuthenticated exists in your project context (modify as necessary).
  • Simplified action structure slightly.
  • Created a helper function setLocale for better organization and clarity. Adjust according to your app’s needs.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ import type { FormInstance, FormRules, UploadFiles } from 'element-plus'
import applicationApi from '@/api/application'
import { isWorkFlow } from '@/utils/application'
import { MsgSuccess, MsgError } from '@/utils/message'
import { langList, t } from '@/locales'

import { getBrowserLang, langList, t } from '@/locales'
const route = useRoute()
const {
params: { id }
Expand Down Expand Up @@ -80,7 +79,7 @@ const open = (data: any, content: any) => {
form.value.show_source = data.show_source
form.value.language = data.language
if (!form.value.language) {
form.value.language = 'zh-CN'
form.value.language = getBrowserLang()
}

dialogVisible.value = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ import type { FormInstance, FormRules, UploadFiles } from 'element-plus'
import { isAppIcon, isWorkFlow } from '@/utils/application'
import applicationXpackApi from '@/api/application-xpack'
import { MsgSuccess, MsgError } from '@/utils/message'
import { langList, t } from '@/locales'
import { getBrowserLang, langList, t } from '@/locales'
import useStore from '@/stores'
import { cloneDeep } from 'lodash'

Expand All @@ -398,7 +398,7 @@ const emit = defineEmits(['refresh'])

const defaultSetting = {
show_source: false,
language: 'zh-CN',
language: getBrowserLang(),
show_history: true,
draggable: true,
show_guide: true,
Expand Down Expand Up @@ -427,7 +427,7 @@ const form = ref<any>({

const xpackForm = ref<any>({
show_source: false,
language: 'zh-CN',
language: getBrowserLang(),
show_history: false,
draggable: false,
show_guide: false,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has no major irregularities or potential issues based on the information available up to February 2025. Here are some recommendations for enhancement:

  1. Avoid Redundancy: The langList variable is now being imported twice (once with and once without the browser language). This might cause confusion and could be simplified.

  2. Consistent Language Handling: Ensure that if you need both system-defined languages (langList) and browser-detected language, they are handled consistently to avoid redundant logic.

  3. Update Locale Import Paths: If these locale imports have been moved since October 1, make sure their import paths reflect this change. For example:

    // Before: import { language } from '@/ locales'
    // After: import { language } from '@/locales/index.js'  # Adjusted path accordingly
  4. Performance Considerations: Since the getBrowserLang() function is called twice (on load and when the user changes settings), consider caching it if performance becomes an issue.

Overall, the code looks clean and functional for its intended purpose.

Expand Down
3 changes: 2 additions & 1 deletion ui/src/views/chat/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import useStore from '@/stores'
import Auth from '@/views/chat/auth/index.vue'
import { hexToRgba } from '@/utils/theme'
import { useI18n } from 'vue-i18n'
import { getBrowserLang } from '@/locales/index'
const { locale } = useI18n({ useScope: 'global' })
const route = useRoute()
const { application, user } = useStore()
Expand Down Expand Up @@ -80,7 +81,7 @@ const init_data_end = ref<boolean>(false)
const applicationAvailable = ref<boolean>(true)
function getAppProfile() {
return application.asyncGetAppProfile(loading).then((res: any) => {
locale.value = res.data?.language
locale.value = res.data?.language || getBrowserLang()
show_history.value = res.data?.show_history
application_profile.value = res.data
})
Expand Down
2 changes: 1 addition & 1 deletion ui/src/views/login/components/wecomQrCode.vue
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const init = async () => {
corpId: props.config.corp_id,
agentId: props.config.agent_id
}
const lang = localStorage.getItem('MaxKB-locale') || getBrowserLang() || 'zh-CN'
const lang = localStorage.getItem('MaxKB-locale') || getBrowserLang() || 'en-US'
const redirectUri = window.location.origin
try {
wwLogin.value = ww.createWWLoginPanel({
Expand Down
2 changes: 1 addition & 1 deletion ui/src/views/login/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ const login = () => {
user
.login(loginMode.value, loginForm.value.username, loginForm.value.password)
.then(() => {
locale.value = localStorage.getItem('MaxKB-locale') || getBrowserLang() || 'zh-CN'
locale.value = localStorage.getItem('MaxKB-locale') || getBrowserLang() || 'en-US'
router.push({ name: 'home' })
})
.finally(() => (loading.value = false))
Expand Down