Skip to content
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
3 changes: 2 additions & 1 deletion packages/i18n/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"lint:errors": "eslint src --ext .ts,.tsx --quiet"
},
"dependencies": {
"@plane/utils": "*"
"@plane/utils": "*",
"intl-messageformat": "^10.7.11"
},
"devDependencies": {
"@plane/eslint-config": "*",
Expand Down
29 changes: 0 additions & 29 deletions packages/i18n/src/components/index.tsx

This file was deleted.

42 changes: 0 additions & 42 deletions packages/i18n/src/components/store.ts

This file was deleted.

45 changes: 0 additions & 45 deletions packages/i18n/src/config/index.ts

This file was deleted.

1 change: 1 addition & 0 deletions packages/i18n/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./language";
13 changes: 13 additions & 0 deletions packages/i18n/src/constants/language.ts
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";
19 changes: 19 additions & 0 deletions packages/i18n/src/context/index.tsx
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>;
});
32 changes: 25 additions & 7 deletions packages/i18n/src/hooks/use-translation.ts
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,
};
}
5 changes: 3 additions & 2 deletions packages/i18n/src/index.ts
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";
170 changes: 170 additions & 0 deletions packages/i18n/src/store/index.ts
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;
}

/**
* 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;
} 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;
}
}
2 changes: 2 additions & 0 deletions packages/i18n/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./language";
export * from "./translation";
6 changes: 6 additions & 0 deletions packages/i18n/src/types/language.ts
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;
}
Loading
Loading