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: Fix default language #2202

Merged
merged 1 commit 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
fix: Fix default language
  • Loading branch information
wangdan-fit2cloud committed Feb 10, 2025
commit ff96c273aec838fbfd6e78685ef716b4d49b5478
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.

Your code seems to be well-structured and follows best practices for using Pinia and Vue.js store. Here are some minor suggestions for improvement:

  1. Type Annotations: The applicationStore function is returning a Promise immediately after being resolved without awaiting it in the .then() block. This might cause unexpected behavior. Consider awaiting it explicitly.

  2. Consistent Usage of await: Ensure that you consistently use either synchronous or asynchronous operations based on where promises need resolution.

  3. Variable Naming: Use consistent naming conventions for variables and functions, especially those related to localization, like sessionStorage.setItem, getBrowserLang(). Using descriptive names can make the code more readable.

Here's an optimized version of your code with these improvements in mind:

import { defineStore } from 'pinia'
import applicationApi from '@/api/application'
import applicationXpackApi from '@/api/application-xpack'
import { type Ref, ref } from 'vue'

import { getBrowserLang } from '@/locales/index'
import useUserStore from './user'

const useApplicationStore = defineStore({
  id: 'application',
  state: () => ({
    // Define your state properties here if needed
  }),
  actions: {
    getAppProfile(loading: Ref<boolean>) {
      return new Promise ((resolve, reject) => {
        setTimeout(() => {
          // Simulate API call
          resolve({ data: { language: 'en' } });
        }, Math.random() * 2000);
      }).then(async (res) => {
        const browserLanguage = await getBrowserLang();
        
        sessionStorage.setItem('language', res.data.language || browserLanguage);
        loading.value = false;
        resolve(res);
      }).catch((error) => {
        console.error(error);
        reject(error);
      });
    }
  },
  getters: {
    getUserLanguage(state): string | null {
      return state.userLanguage; // Assuming this exists in your state
    }
  },
})

export default useApplicationStore

Optimization Suggestions:

  • If you frequently access the session storage for 'language', consider caching it locally instead of fetching it each time. You could also implement lazy evaluation for browserLang to only fetch it when necessary.

In summary, everything looks good syntactically. However, consider making changes around the promise handling and variable naming to maintain consistency and potentially improve performance.

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 appears mostly correct but has a couple of minor optimizations and improvements:

  • Remove duplicate useLocalStorage calls when setting the locale.
  • Simplify conditional logic in the showXpack() function to directly return this.isXPack.

Optimized code:

const useUserStore = defineStore({
  state() {
    return {
      userType: 1,
      isXPack: false,
      userInfo: {}
    };
  },
  getters: {
    getLanguage(): string {
      return (
        this.userType === 1 && localStorage.getItem('MAXKB-locale')
          ? localStorage.getItem('MAXKB-locale') || getBrowserLang()
          : sessionStorage.getItem('language') || getBrowserLang()
      );
    }
  },
  actions: {
    async profile(lang?: string): Promise<void> {
      const data = await UserApi.profile();
      this.userInfo = data.data;
      
      // Update local storage with new language preference if provided
      this.updateLocale(lang);
      
      
      await this.asyncGetProfile();
    },
    
    updateLocale(language?: string): void {
      const key = language ? 'en-US' : "zh-CN";
      useLocalStorage(key).value = language || this.getLanguage();
      
      // Optionally reload page to apply changes
      window.location.reload(false);
    },
    
    
    async postLanguage(lang: string): Promise<void> {
      await UserApi.postLanguage({language}, (loading) => {});
      
      // Update local storage after successful change
      this.updateLocale(lang);
    }
  }
});

Explanation of changes:

  1. Removed the duplicated useLocalStorage(localeConfigKey, 'zh-CN').value = ok.data.language line in both places where it was used.
  2. Simplified the condition in the showXpack() function by using direct reference to this.isXPack.
  3. Added an updateLocale action that handles updating the locale, reducing repeated code. This method can be called separately from profile and postLanguage, depending on whether a new language needs to be set.

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 snippet has some small improvements and optimizations:

  1. Removed Unnecessary Imports: The import statement that was removed (import { isAppIcon, isWorkFlow }) doesn't appear to be used anywhere in the current context, so it can be safely removed.

  2. Added Comments: A few comments were added where the change might make sense or improve readability. These comments explain why getBrowserLang() is being used instead of 'zh-CN'.

  3. Consistency: There's a consistency issue with how variables like show_history are set across both defaultSetting and xpackForm. You might want to consider making these consistent for better maintainability.

Here's the revised version:

@@ -383,6 +383,7 @@ import { FormInstance, FormRules, UploadFiles } from 'element-plus'
 import { isAppIcon, isWorkFlow } from '@/utils/application'
 import applicationXpackApi from '@/api/application-xpack'
+// Removed because not used
// import { isAppIcon, isWorkFlow } from '@/utils/application'

import { MsgSuccess, MsgError } from '@/utils/message'
import { getBrowserLang, langList, t } from '@/locales'
import useStore from '@/stores'
import { cloneDeep } from 'lodash'

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

const defaultSetting = {
-  show_source: false,
-  language: 'zh-CN',
+  show_source: false,
+  // Use browser-detected language for localization
+  language: getBrowserLang(),
   show_history: true,
   draggable: true,
   show_guide: true,

@@ -427,6 +428,7 @@ const form = ref<any>({
 

 const xpackForm = ref<any>({
   show_source: false,
-  language: 'zh-CN',
+  language: getBrowserLang(), // Use browser-detected language for localization
   show_history: false,
   draggable: false,
   show_guide: false);

Additional Suggestion

Consider adding a fallback mechanism for cases where getBrowserLang returns an unexpected value. For example, you could set a default language like 'en-US' if no recognized language is detected:

language: getBrowserLang() || 'en-US';

This ensures that your application still functions correctly even if the user's browser does not detect a supported language.

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