mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-09-03 21:34:59 +00:00
42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import { TranslatableString } from "ChillMainAssets/types";
|
|
|
|
/**
|
|
* Localizes a translatable string object based on the current locale.
|
|
* A fallback logic is implemented in case no translation is available for the current locale.
|
|
*
|
|
* @param translatableString Object containing translations for different locales
|
|
* @param locale defaults to browser locale
|
|
* @returns The localized string or null if no translation is available
|
|
*/
|
|
export function localizeString(
|
|
translatableString: TranslatableString | null | undefined,
|
|
locale?: string,
|
|
): string {
|
|
if (!translatableString || Object.keys(translatableString).length === 0) {
|
|
return "";
|
|
}
|
|
|
|
const currentLocale = locale || navigator.language.split("-")[0] || "fr";
|
|
|
|
if (translatableString[currentLocale]) {
|
|
return translatableString[currentLocale];
|
|
}
|
|
|
|
// Define fallback locales
|
|
const fallbackLocales: string[] = ["fr", "en"];
|
|
|
|
for (const fallbackLocale of fallbackLocales) {
|
|
if (translatableString[fallbackLocale]) {
|
|
return translatableString[fallbackLocale];
|
|
}
|
|
}
|
|
|
|
// No fallback translation found, use the first available
|
|
const availableLocales = Object.keys(translatableString);
|
|
if (availableLocales.length > 0) {
|
|
return translatableString[availableLocales[0]];
|
|
}
|
|
|
|
return "";
|
|
}
|