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 when chat language is null #2204

Merged
merged 2 commits into from
Feb 10, 2025

Conversation

shaohuzhang1
Copy link
Contributor

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

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.

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

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

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

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

@wangdan-fit2cloud wangdan-fit2cloud merged commit 9113526 into main Feb 10, 2025
4 checks passed
@wangdan-fit2cloud wangdan-fit2cloud deleted the pr@main@default-language branch February 10, 2025 07:14
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