Skip to content

Commit

Permalink
fix some comments
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhenjaHorbach committed Sep 25, 2024
1 parent ffcd48e commit 480bdda
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 26 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,28 @@ Some pointers:
key to the translation file and use the arrow function version, like so:
`nameOfTheKey: ({amount, dateTime}) => "User has sent " + amount + " to you on " + dateTime,`.
This is because the order of the phrases might vary from one language to another.
- When working with translations that involve plural forms, it's important to handle different cases correctly.

For example:
- zero: Used when there are no items **(optional)**.
- one: Used when there's exactly one item.
- few: Used for a small number of items **(optional)**.
- many: Used for larger quantities **(optional)**.
- other: A catch-all case for other counts or variations.
Here’s an example of how to implement plural translations:
messages: () => ({
zero: 'No messages',
one: 'One message',
few: (count) => `${count} messages`,
many: (count) => `You have ${count} messages`,
other: (count) => `You have ${count} unread messages`,
})
In your code, you can use the translation like this:
`translate('common.messages', {count: 1});`
----
# Deploying
Expand Down
5 changes: 4 additions & 1 deletion src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3661,7 +3661,10 @@ const translations = {
rate: 'Rate',
addRate: 'Add rate',
trackTax: 'Track tax',
deleteRates: ({count}: DistanceRateOperationsParams) => `Delete ${Str.pluralize('rate', 'rates', count)}`,
deleteRates: () => ({
one: 'Delete rate',
other: () => `Delete rates`,
}),
enableRates: ({count}: DistanceRateOperationsParams) => `Enable ${Str.pluralize('rate', 'rates', count)}`,
disableRates: ({count}: DistanceRateOperationsParams) => `Disable ${Str.pluralize('rate', 'rates', count)}`,
enableRate: 'Enable rate',
Expand Down
5 changes: 4 additions & 1 deletion src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3711,7 +3711,10 @@ const translations = {
rate: 'Tasa',
addRate: 'Agregar tasa',
trackTax: 'Impuesto de seguimiento',
deleteRates: ({count}: DistanceRateOperationsParams) => `Eliminar ${Str.pluralize('tasa', 'tasas', count)}`,
deleteRates: () => ({
one: 'Eliminar tasa',
other: () => `Eliminar tasas`,
}),
enableRates: ({count}: DistanceRateOperationsParams) => `Activar ${Str.pluralize('tasa', 'tasas', count)}`,
disableRates: ({count}: DistanceRateOperationsParams) => `Desactivar ${Str.pluralize('tasa', 'tasas', count)}`,
enableRate: 'Activar tasa',
Expand Down
12 changes: 6 additions & 6 deletions src/languages/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ type FlattenObject<TObject, TPrefix extends string = ''> = {
/**
* Retrieves a type for a given key path (calculated from the type above)
*/
type TranslationValue<TObject, TPath extends string> = TPath extends keyof TObject
? TObject[TPath]
: TPath extends `${infer TKey}.${infer TRest}`
? TKey extends keyof TObject
? TranslationValue<TObject[TKey], TRest>
type TranslationValue<TObject, TKey extends string> = TKey extends keyof TObject
? TObject[TKey]
: TKey extends `${infer TPathKey}.${infer TRest}`
? TPathKey extends keyof TObject
? TranslationValue<TObject[TPathKey], TRest>
: never
: never;

Expand All @@ -85,7 +85,7 @@ type FlatTranslationsObject = {
/**
* Determines the expected parameters for a specific translation function based on the provided translation path
*/
type TranslationParameters<TPath extends TranslationPaths> = FlatTranslationsObject[TPath] extends (...args: infer Args) => infer Return
type TranslationParameters<TKey extends TranslationPaths> = FlatTranslationsObject[TKey] extends (...args: infer Args) => infer Return
? Return extends PluralForm
? Args[0] extends undefined
? [PluralParams]
Expand Down
34 changes: 16 additions & 18 deletions src/libs/Localize/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,37 +80,35 @@ const translationCache = new Map<ValueOf<typeof CONST.LOCALES>, Map<TranslationP
* phrase and stores the translated value in the cache and returns
* the translated value.
*/
function getTranslatedPhrase<TPath extends TranslationPaths>(
function getTranslatedPhrase<TKey extends TranslationPaths>(
language: 'en' | 'es' | 'es-ES',
path: TPath,
phraseKey: TKey,
fallbackLanguage: 'en' | 'es' | null,
...parameters: TranslationParameters<TPath>
...parameters: TranslationParameters<TKey>
): string | null {
// Get the cache for the above locale
const cacheForLocale = translationCache.get(language);

// Directly access and assign the translated value from the cache, instead of
// going through map.has() and map.get() to avoid multiple lookups.
const valueFromCache = cacheForLocale?.get(path);
const valueFromCache = cacheForLocale?.get(phraseKey);

// If the phrase is already translated, return the translated value
if (valueFromCache) {
return valueFromCache;
}

const translatedPhrase = translations?.[language]?.[path];
const translatedPhrase = translations?.[language]?.[phraseKey];

if (translatedPhrase) {
if (typeof translatedPhrase === 'function') {
/**
*
* is Plain object is for checking if the phraseTranslated output
* is an object then further check if it include the count param or not
* OR before checking the plain object output, we can check if we have the count
* param in parameters
*
* If the result of `translatedPhrase` is an object, check if it contains the 'count' property
* to handle pluralization logic.
* Alternatively, before evaluating the translated result, we can check if the 'count' parameter
* exists in the passed parameters.
*/
const translateFunction = translatedPhrase as unknown as (...parameters: TranslationParameters<TPath>) => string | PluralForm;
const translateFunction = translatedPhrase as unknown as (...parameters: TranslationParameters<TKey>) => string | PluralForm;
const translateResult = translateFunction(...parameters);

if (typeof translateResult === 'string') {
Expand All @@ -121,7 +119,7 @@ function getTranslatedPhrase<TPath extends TranslationPaths>(
if (phraseObject && typeof phraseObject === 'object' && 'count' in phraseObject && typeof phraseObject.count === 'number') {
const pluralRule = new Intl.PluralRules(language).select(phraseObject.count);

const pluralResult = pluralRule in translateResult && translateResult[pluralRule];
const pluralResult = translateResult[pluralRule];
if (pluralResult) {
if (typeof pluralResult === 'string') {
return pluralResult;
Expand All @@ -133,11 +131,11 @@ function getTranslatedPhrase<TPath extends TranslationPaths>(
return translateResult.other(phraseObject.count);
}

throw new Error(`Invalid plural form for '${path}'`);
throw new Error(`Invalid plural form for '${phraseKey}'`);
}

// We set the translated value in the cache only for the phrases without parameters.
cacheForLocale?.set(path, translatedPhrase);
cacheForLocale?.set(phraseKey, translatedPhrase);
return translatedPhrase;
}

Expand All @@ -146,18 +144,18 @@ function getTranslatedPhrase<TPath extends TranslationPaths>(
}

// Phrase is not found in full locale, search it in fallback language e.g. es
const fallbackTranslatedPhrase = getTranslatedPhrase(fallbackLanguage, path, null, ...parameters);
const fallbackTranslatedPhrase = getTranslatedPhrase(fallbackLanguage, phraseKey, null, ...parameters);

if (fallbackTranslatedPhrase) {
return fallbackTranslatedPhrase;
}

if (fallbackLanguage !== CONST.LOCALES.DEFAULT) {
Log.alert(`${path} was not found in the ${fallbackLanguage} locale`);
Log.alert(`${phraseKey} was not found in the ${fallbackLanguage} locale`);
}

// Phrase is not translated, search it in default language (en)
return getTranslatedPhrase(CONST.LOCALES.DEFAULT, path, null, ...parameters);
return getTranslatedPhrase(CONST.LOCALES.DEFAULT, phraseKey, null, ...parameters);
}

/**
Expand Down

0 comments on commit 480bdda

Please sign in to comment.