Skip to content

[WEB-3153] improvement: add support for nested translations and ICU formatting#6411

Merged
sriramveeraghanta merged 2 commits intopreviewfrom
improvement-language-translation
Jan 16, 2025
Merged

[WEB-3153] improvement: add support for nested translations and ICU formatting#6411
sriramveeraghanta merged 2 commits intopreviewfrom
improvement-language-translation

Conversation

@prateekshourya29
Copy link
Member

@prateekshourya29 prateekshourya29 commented Jan 16, 2025

Description

Translation System Enhancement

Changes

  • Implemented ICU MessageFormat for handling complex translation strings
  • Added support for nested translations and plural forms

Example Usage

// "messages": {
//     "welcome": "Welcome, {name}!"
//   },
//   "trial_days_left": "You have {days, plural, one{# day} other{# days}} left in your PRO trial period"

t('message.welcome', { name: "Prateek" })
// "Welcome, Prateek!"
t('trial_days_left', { days: 5 })
// "You have 5 days left in your PRO trial period"
t('trial_days_left', { days: 1 })
// "You have 1 day left in your PRO trial period"

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • Feature (non-breaking change which adds functionality)
  • Improvement (change that would cause existing functionality to not work as expected)
  • Code refactoring
  • Performance improvements
  • Documentation update

References

WEB-3153

Summary by CodeRabbit

  • New Features

    • Enhanced internationalization (i18n) support with a new language management system.
    • Added support for multiple languages: English, French, Spanish, Japanese, and Chinese (Simplified).
    • Introduced a new TranslationProvider component for managing translations.
  • Dependency Updates

    • Added intl-messageformat library for improved translation handling.
  • Refactor

    • Completely restructured translation management system.
    • Updated type definitions and context for language support.
    • Streamlined module exports for easier access to language and translation functionalities.

@makeplane
Copy link

makeplane bot commented Jan 16, 2025

Pull Request Linked with Plane Issues

Comment Automatically Generated by Plane

1 similar comment
@makeplane
Copy link

makeplane bot commented Jan 16, 2025

Pull Request Linked with Plane Issues

Comment Automatically Generated by Plane

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

Walkthrough

The pull request introduces significant changes to the internationalization (i18n) package, including the addition of a new dependency, intl-messageformat. It removes several files related to the previous translation context and store implementation while implementing a new TranslationStore class. The structure is enhanced with new type definitions and constants related to language support, and the module exports have been updated to reflect a more modular design.

Changes

File Change Summary
packages/i18n/package.json Added intl-messageformat dependency
packages/i18n/src/components/* Removed translation context and store implementation
packages/i18n/src/config/* Deleted configuration files for translations
packages/i18n/src/constants/index.ts Re-exported language module exports
packages/i18n/src/constants/language.ts Added language-related constants
packages/i18n/src/context/index.tsx Created new translation context
packages/i18n/src/hooks/use-translation.ts Updated translation hook with new type definitions
packages/i18n/src/index.ts Updated module exports
packages/i18n/src/store/index.ts Implemented new TranslationStore class
packages/i18n/src/types/* Added new type and interface definitions
web/core/lib/wrappers/store-wrapper.tsx Updated language type import

Possibly related PRs

Suggested Labels

🌟improvement, 🌐frontend

Suggested Reviewers

  • sriramveeraghanta
  • SatishGandham
  • rahulramesha

Poem

🐰 Translations dance, a linguistic delight,
Code refactored with linguistic might.
Languages blend, types now precise,
A rabbit's journey through syntax so nice!
Internationalization takes its flight! 🌍

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
packages/i18n/src/types/translation.ts (2)

1-3: Consider adding JSDoc documentation and ICU message format validation.

The interface correctly enables nested translations with its recursive design. However, consider these improvements:

  1. Add JSDoc documentation explaining the purpose and usage
  2. Consider adding type validation for ICU message format strings

Example enhancement:

+/**
+ * Represents a translation object that can contain either direct string translations
+ * or nested translation objects.
+ * @example
+ * {
+ *   "welcome": "Hello {name}!",
+ *   "notifications": {
+ *     "count": "You have {count, plural, one{# notification} other{# notifications}}"
+ *   }
+ * }
+ */
 export interface ITranslation {
+  // ICU MessageFormat strings or nested translation objects
   [key: string]: string | ITranslation;
 }

5-7: Consider adding type safety for locale strings.

The interface provides a clean structure for organizing translations by locale. Consider enhancing type safety by:

  1. Using a union type of supported locales instead of string
  2. Adding JSDoc documentation listing supported locales

Example enhancement:

+/** Supported locale codes */
+export type SupportedLocale = 'en' | 'es' | 'fr' | 'de' | 'ja' | 'ko' | 'zh';
+
+/**
+ * Maps locale codes to their respective translations.
+ * @see SupportedLocale for list of supported locales
+ */
 export interface ITranslations {
-  [locale: string]: ITranslation;
+  [locale in SupportedLocale]: ITranslation;
 }
packages/i18n/src/store/index.ts (1)

34-49: Optimize translation loading to improve performance

Currently, the loadTranslations method loads all translation files for all supported languages upon initialization. This could impact performance, especially if the translation files are large. Consider loading translations on demand when a language is set or when it's actually needed.

Apply this diff to refactor the translation loading:

-  private async loadTranslations() {
+  private async loadTranslations(locale: TLanguage) {
     try {
-      // dynamic import of translations
-      const translations = {
-        en: (await import("../locales/en/translations.json")).default,
-        fr: (await import("../locales/fr/translations.json")).default,
-        es: (await import("../locales/es/translations.json")).default,
-        ja: (await import("../locales/ja/translations.json")).default,
-        "zh-CN": (await import("../locales/zh-CN/translations.json")).default,
-      };
-      this.translations = translations;
+      const translation = (await import(`../locales/${locale}/translations.json`)).default;
+      this.translations[locale] = translation;
       this.messageCache.clear(); // Clear cache when translations change
     } catch (error) {
       console.error("Failed to load translations:", error);
     }
   }

Update the constructor and setLanguage method to load translations for the current locale:

 constructor() {
   makeAutoObservable(this);
   this.initializeLanguage();
-  this.loadTranslations();
+  this.loadTranslations(this.currentLocale);
 }

 setLanguage(lng: TLanguage): void {
   try {
     if (!this.isValidLanguage(lng)) {
       throw new Error(`Invalid language: ${lng}`);
     }

     localStorage.setItem(STORAGE_KEY, lng);
     this.currentLocale = lng;
     this.messageCache.clear(); // Clear cache when language changes
     document.documentElement.lang = lng;
+    this.loadTranslations(lng);
   } catch (error) {
     console.error("Failed to set language:", error);
   }
 }
packages/i18n/src/context/index.tsx (1)

6-6: Consider adding a custom error message for the null context case.

While the null default value is appropriate, adding a descriptive error message in the default value could help developers identify missing providers more easily.

-export const TranslationContext = createContext<TranslationStore | null>(null);
+export const TranslationContext = createContext<TranslationStore | null>((() => {
+  throw new Error('TranslationContext: using context without provider');
+})());
packages/i18n/src/hooks/use-translation.ts (2)

14-22: Consider improving JSDoc accuracy.

The @returns tag is repeated multiple times. Consider using @Property tags for describing the returned object's properties.

 /**
  * Provides the translation store to the application
- * @returns {TTranslationStore}
- * @returns {(key: string, params?: Record<string, any>) => string} t: method to translate the key with params
- * @returns {TLanguage} currentLocale - current locale language
- * @returns {(lng: TLanguage) => void} changeLanguage - method to change the language
- * @returns {ILanguageOption[]} languages - available languages
+ * @returns {TTranslationStore} The translation store object
+ * @property {Function} t - Method to translate the key with params
+ * @property {TLanguage} currentLocale - Current locale language
+ * @property {Function} changeLanguage - Method to change the language
+ * @property {ILanguageOption[]} languages - Available languages
  * @throws {Error} if the TranslationProvider is not used
  */

29-34: Consider optimizing the store method binding.

The bind call in the return object will create a new function on every render. Consider moving it to a useMemo or the initialization phase.

 export function useTranslation(): TTranslationStore {
   const store = useContext(TranslationContext);
   if (!store) {
     throw new Error('useTranslation must be used within a TranslationProvider');
   }
 
+  const translationFn = React.useMemo(() => store.t.bind(store), [store]);
+
   return {
-    t: store.t.bind(store),
+    t: translationFn,
     currentLocale: store.currentLocale,
     changeLanguage: (lng: TLanguage) => store.setLanguage(lng),
     languages: store.availableLanguages,
   };
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ac2074 and c0004fb.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (14)
  • packages/i18n/package.json (1 hunks)
  • packages/i18n/src/components/index.tsx (0 hunks)
  • packages/i18n/src/components/store.ts (0 hunks)
  • packages/i18n/src/config/index.ts (0 hunks)
  • packages/i18n/src/constants/index.ts (1 hunks)
  • packages/i18n/src/constants/language.ts (1 hunks)
  • packages/i18n/src/context/index.tsx (1 hunks)
  • packages/i18n/src/hooks/use-translation.ts (1 hunks)
  • packages/i18n/src/index.ts (1 hunks)
  • packages/i18n/src/store/index.ts (1 hunks)
  • packages/i18n/src/types/index.ts (1 hunks)
  • packages/i18n/src/types/language.ts (1 hunks)
  • packages/i18n/src/types/translation.ts (1 hunks)
  • web/core/lib/wrappers/store-wrapper.tsx (2 hunks)
💤 Files with no reviewable changes (3)
  • packages/i18n/src/components/store.ts
  • packages/i18n/src/components/index.tsx
  • packages/i18n/src/config/index.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/i18n/src/constants/index.ts
  • packages/i18n/src/types/index.ts
  • packages/i18n/src/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint-web
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)
🔇 Additional comments (8)
packages/i18n/src/types/translation.ts (1)

1-7: Well-designed foundation for the i18n system!

The type definitions provide a solid foundation for:

  • Nested translations
  • ICU MessageFormat support
  • Locale-based organization
packages/i18n/src/store/index.ts (1)

14-165: Overall implementation is clean and follows best practices

The TranslationStore class is well-structured, leveraging MobX effectively to manage state. The methods provided offer a robust solution for handling translations and language settings.

packages/i18n/src/types/language.ts (1)

1-6: Type definitions are clear and enhance type safety

The TLanguage type and ILanguageOption interface are properly defined, improving type safety and consistency across the application.

packages/i18n/src/constants/language.ts (1)

1-13: Language constants are well-defined and consistent

The FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, and STORAGE_KEY constants are appropriately set up, enhancing the maintainability and clarity of the language configuration.

packages/i18n/src/context/index.tsx (1)

15-19: LGTM! Clean implementation of the TranslationProvider.

The implementation follows React best practices:

  • Uses observer pattern for reactivity
  • Initializes store only once using useState callback
  • Properly types the props interface
packages/i18n/src/hooks/use-translation.ts (1)

7-12: LGTM! Well-defined type interface for the translation store.

The TTranslationStore type clearly defines all required methods and properties for the translation functionality.

web/core/lib/wrappers/store-wrapper.tsx (1)

56-56: LGTM! Proper type handling for language change.

The type casting ensures type safety while maintaining the existing functionality.

packages/i18n/package.json (1)

13-14: LGTM! Appropriate dependency for ICU message formatting.

The addition of intl-messageformat aligns with the PR's objective to support ICU MessageFormat for translations.

Let's verify if this is the latest stable version:

✅ Verification successful

Version ^10.7.11 of intl-messageformat is the latest stable release

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check latest version of intl-messageformat
npm view intl-messageformat versions --json | jq -r '.[-1]'

Length of output: 69

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0004fb and 784ba92.

📒 Files selected for processing (1)
  • packages/i18n/src/store/index.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)
🔇 Additional comments (1)
packages/i18n/src/store/index.ts (1)

71-74: Browser language detection may not handle region codes correctly

In the getBrowserLanguage() method, splitting navigator.language by '-' and taking the first part may cause issues for languages with region codes like 'zh-CN' or 'pt-BR'. This could result in 'zh' or 'pt', which may not match your supported languages, leading to a fallback to the default language instead of the user's preferred language.

Apply this diff to fix the issue:

 private getBrowserLanguage(): TLanguage {
+  if (typeof navigator === "undefined") {
+    return FALLBACK_LANGUAGE;
+  }
-   const browserLang = navigator.language.split("-")[0];
+   const browserLang = navigator.language;
+   if (this.isValidLanguage(browserLang)) {
+     return browserLang;
+   }
+   const baseLang = browserLang.split("-")[0];
+   return this.isValidLanguage(baseLang) ? (baseLang as TLanguage) : FALLBACK_LANGUAGE;
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants