-
Notifications
You must be signed in to change notification settings - Fork 3.6k
[WEB-3153] improvement: add support for nested translations and ICU formatting #6411
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from "./language"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| import { TLanguage, ILanguageOption } from "../types"; | ||
|
|
||
| export const FALLBACK_LANGUAGE: TLanguage = "en"; | ||
|
|
||
| export const SUPPORTED_LANGUAGES: ILanguageOption[] = [ | ||
| { label: "English", value: "en" }, | ||
| { label: "Français", value: "fr" }, | ||
| { label: "Español", value: "es" }, | ||
| { label: "日本語", value: "ja" }, | ||
| { label: "中文", value: "zh-CN" }, | ||
| ]; | ||
|
|
||
| export const STORAGE_KEY = "userLanguage"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { observer } from "mobx-react"; | ||
| import React, { createContext } from "react"; | ||
| // store | ||
| import { TranslationStore } from "../store"; | ||
|
|
||
| export const TranslationContext = createContext<TranslationStore | null>(null); | ||
|
|
||
| interface TranslationProviderProps { | ||
| children: React.ReactNode; | ||
| } | ||
|
|
||
| /** | ||
| * Provides the translation store to the application | ||
| */ | ||
| export const TranslationProvider: React.FC<TranslationProviderProps> = observer(({ children }) => { | ||
| const [store] = React.useState(() => new TranslationStore()); | ||
|
|
||
| return <TranslationContext.Provider value={store}>{children}</TranslationContext.Provider>; | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,35 @@ | ||
| import { useContext } from "react"; | ||
| import { TranslationContext } from "../components"; | ||
| import { Language } from "../config"; | ||
| import { useContext } from 'react'; | ||
| // context | ||
| import { TranslationContext } from '../context'; | ||
| // types | ||
| import { ILanguageOption, TLanguage } from '../types'; | ||
|
|
||
| export function useTranslation() { | ||
| export type TTranslationStore = { | ||
| t: (key: string, params?: Record<string, any>) => string; | ||
| currentLocale: TLanguage; | ||
| changeLanguage: (lng: TLanguage) => void; | ||
| languages: ILanguageOption[]; | ||
| }; | ||
|
|
||
| /** | ||
| * 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 | ||
| * @throws {Error} if the TranslationProvider is not used | ||
| */ | ||
| export function useTranslation(): TTranslationStore { | ||
| const store = useContext(TranslationContext); | ||
| if (!store) { | ||
| throw new Error("useTranslation must be used within a TranslationProvider"); | ||
| throw new Error('useTranslation must be used within a TranslationProvider'); | ||
| } | ||
|
|
||
| return { | ||
| t: (key: string) => store.t(key), | ||
| t: store.t.bind(store), | ||
| currentLocale: store.currentLocale, | ||
| changeLanguage: (lng: Language) => store.setLanguage(lng), | ||
| changeLanguage: (lng: TLanguage) => store.setLanguage(lng), | ||
| languages: store.availableLanguages, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| export * from "./config"; | ||
| export * from "./components"; | ||
| export * from "./constants"; | ||
| export * from "./context"; | ||
| export * from "./hooks"; | ||
| export * from "./types"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| import IntlMessageFormat from "intl-messageformat"; | ||
| import get from "lodash/get"; | ||
| import { makeAutoObservable } from "mobx"; | ||
| // constants | ||
| import { FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, STORAGE_KEY } from "../constants"; | ||
| // types | ||
| import { TLanguage, ILanguageOption, ITranslations } from "../types"; | ||
|
|
||
| /** | ||
| * Mobx store class for handling translations and language changes in the application | ||
| * Provides methods to translate keys with params and change the language | ||
| * Uses IntlMessageFormat to format the translations | ||
| */ | ||
| export class TranslationStore { | ||
| // List of translations for each language | ||
| private translations: ITranslations = {}; | ||
| // Cache for IntlMessageFormat instances | ||
| private messageCache: Map<string, IntlMessageFormat> = new Map(); | ||
| // Current language | ||
| currentLocale: TLanguage = FALLBACK_LANGUAGE; | ||
|
|
||
| /** | ||
| * Constructor for the TranslationStore class | ||
| */ | ||
| constructor() { | ||
| makeAutoObservable(this); | ||
| this.initializeLanguage(); | ||
| this.loadTranslations(); | ||
| } | ||
|
|
||
| /** | ||
| * Loads translations from JSON files and initializes the message cache | ||
| */ | ||
| private async loadTranslations() { | ||
| 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; | ||
| this.messageCache.clear(); // Clear cache when translations change | ||
| } catch (error) { | ||
| console.error("Failed to load translations:", error); | ||
| } | ||
| } | ||
|
|
||
| /** Initializes the language based on the local storage or browser language */ | ||
| private initializeLanguage() { | ||
| if (typeof window === "undefined") return; | ||
|
|
||
| const savedLocale = localStorage.getItem(STORAGE_KEY) as TLanguage; | ||
| if (this.isValidLanguage(savedLocale)) { | ||
| this.setLanguage(savedLocale); | ||
| return; | ||
| } | ||
|
|
||
| const browserLang = this.getBrowserLanguage(); | ||
| this.setLanguage(browserLang); | ||
| } | ||
|
|
||
| /** Checks if the language is valid based on the supported languages */ | ||
| private isValidLanguage(lang: string | null): lang is TLanguage { | ||
| return lang !== null && SUPPORTED_LANGUAGES.some((l) => l.value === lang); | ||
| } | ||
|
|
||
| /** Gets the browser language based on the navigator.language */ | ||
| private getBrowserLanguage(): TLanguage { | ||
| const browserLang = navigator.language.split("-")[0]; | ||
| return this.isValidLanguage(browserLang) ? browserLang : FALLBACK_LANGUAGE; | ||
| } | ||
prateekshourya29 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Gets the cache key for the given key and locale | ||
| * @param key - the key to get the cache key for | ||
| * @param locale - the locale to get the cache key for | ||
| * @returns the cache key for the given key and locale | ||
| */ | ||
| private getCacheKey(key: string, locale: TLanguage): string { | ||
| return `${locale}:${key}`; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the IntlMessageFormat instance for the given key and locale | ||
| * Returns cached instance if available | ||
| * Throws an error if the key is not found in the translations | ||
| */ | ||
| private getMessageInstance(key: string, locale: TLanguage): IntlMessageFormat | null { | ||
| const cacheKey = this.getCacheKey(key, locale); | ||
|
|
||
| // Check if the cache already has the key | ||
| if (this.messageCache.has(cacheKey)) { | ||
| return this.messageCache.get(cacheKey) || null; | ||
| } | ||
|
|
||
| // Get the message from the translations | ||
| const message = get(this.translations[locale], key); | ||
| if (!message) return null; | ||
|
|
||
| try { | ||
| const formatter = new IntlMessageFormat(message as any, locale); | ||
| this.messageCache.set(cacheKey, formatter); | ||
| return formatter; | ||
| } catch (error) { | ||
| console.error(`Failed to create message formatter for key "${key}":`, error); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Translates a key with params using the current locale | ||
| * Falls back to the default language if the translation is not found | ||
| * Returns the key itself if the translation is not found | ||
| * @param key - The key to translate | ||
| * @param params - The params to format the translation with | ||
| * @returns The translated string | ||
| */ | ||
| t(key: string, params?: Record<string, any>): string { | ||
| try { | ||
| // Try current locale | ||
| let formatter = this.getMessageInstance(key, this.currentLocale); | ||
|
|
||
| // Fallback to default language if necessary | ||
| if (!formatter && this.currentLocale !== FALLBACK_LANGUAGE) { | ||
| formatter = this.getMessageInstance(key, FALLBACK_LANGUAGE); | ||
| } | ||
|
|
||
| // If we have a formatter, use it | ||
| if (formatter) { | ||
| return formatter.format(params || {}) as string; | ||
| } | ||
|
|
||
| // Last resort: return the key itself | ||
| return key; | ||
| } catch (error) { | ||
| console.error(`Translation error for key "${key}":`, error); | ||
| return key; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Sets the current language and updates the translations | ||
| * @param lng - The new language | ||
| */ | ||
| 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; | ||
prateekshourya29 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } catch (error) { | ||
| console.error("Failed to set language:", error); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Gets the available language options for the dropdown | ||
| * @returns An array of language options | ||
| */ | ||
| get availableLanguages(): ILanguageOption[] { | ||
| return SUPPORTED_LANGUAGES; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export * from "./language"; | ||
| export * from "./translation"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| export type TLanguage = "en" | "fr" | "es" | "ja" | "zh-CN"; | ||
|
|
||
| export interface ILanguageOption { | ||
| label: string; | ||
| value: TLanguage; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.