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

fix: Fix default language #2202

merged 1 commit into from
Feb 10, 2025

Conversation

shaohuzhang1
Copy link
Contributor

fix: Fix default language

Copy link

f2c-ci-robot bot commented Feb 10, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

Copy link

f2c-ci-robot bot commented Feb 10, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@@ -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.

@@ -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.

@@ -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.

@wangdan-fit2cloud wangdan-fit2cloud merged commit 9937b61 into main Feb 10, 2025
4 checks passed
@wangdan-fit2cloud wangdan-fit2cloud deleted the pr@main@default-language branch February 10, 2025 06:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants