Skip to content

Commit

Permalink
Merge pull request #29742 from software-mansion-labs/ts-migration/loc…
Browse files Browse the repository at this point in the history
…alize-lib

[TS migration] Migrate 'Localize' lib to TypeScript
  • Loading branch information
arosiclair authored Nov 6, 2023
2 parents fa89ada + 30359af commit 7601f89
Show file tree
Hide file tree
Showing 13 changed files with 113 additions and 97 deletions.
2 changes: 1 addition & 1 deletion src/languages/translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ export default {
en: flattenObject(en),
es: flattenObject(es),
// eslint-disable-next-line @typescript-eslint/naming-convention
'es-ES': esES,
'es-ES': flattenObject(esES),
};
1 change: 1 addition & 0 deletions src/languages/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ export type {
EnglishTranslation,
TranslationFlatObject,
AddressLineParams,
TranslationPaths,
CharacterLimitParams,
MaxParticipantsReachedParams,
ZipCodeExampleFormatParams,
Expand Down
8 changes: 7 additions & 1 deletion src/libs/DateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,13 @@ function isYesterday(date: Date, timeZone: string): boolean {
* Jan 20 at 5:30 PM within the past year
* Jan 20, 2019 at 5:30 PM anything over 1 year ago
*/
function datetimeToCalendarTime(locale: string, datetime: string, includeTimeZone = false, currentSelectedTimezone = timezone.selected, isLowercase = false): string {
function datetimeToCalendarTime(
locale: 'en' | 'es' | 'es-ES' | 'es_ES',
datetime: string,
includeTimeZone = false,
currentSelectedTimezone = timezone.selected,
isLowercase = false,
): string {
const date = getLocalDateFromDatetime(locale, datetime, currentSelectedTimezone);
const tz = includeTimeZone ? ' [UTC]Z' : '';
let todayAt = Localize.translate(locale, 'common.todayAt');
Expand Down
4 changes: 2 additions & 2 deletions src/libs/ErrorUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import CONST from '@src/CONST';
import {TranslationFlatObject} from '@src/languages/types';
import {TranslationFlatObject, TranslationPaths} from '@src/languages/types';
import {ErrorFields, Errors} from '@src/types/onyx/OnyxCommon';
import Response from '@src/types/onyx/Response';
import DateUtils from './DateUtils';
Expand Down Expand Up @@ -93,7 +93,7 @@ type ErrorsList = Record<string, string | [string, {isTranslated: boolean}]>;
* @param errorList - An object containing current errors in the form
* @param message - Message to assign to the inputID errors
*/
function addErrorMessage(errors: ErrorsList, inputID?: string, message?: string) {
function addErrorMessage<TKey extends TranslationPaths>(errors: ErrorsList, inputID?: string, message?: TKey) {
if (!message || !inputID) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import Onyx from 'react-native-onyx';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import BaseLocale, {LocaleListenerConnect} from './types';

let preferredLocale = CONST.LOCALES.DEFAULT;
let preferredLocale: BaseLocale = CONST.LOCALES.DEFAULT;

/**
* Adds event listener for changes to the locale. Callbacks are executed when the locale changes in Onyx.
*
* @param {Function} [callbackAfterChange]
*/
const connect = (callbackAfterChange = () => {}) => {
const connect: LocaleListenerConnect = (callbackAfterChange = () => {}) => {
Onyx.connect({
key: ONYXKEYS.NVP_PREFERRED_LOCALE,
callback: (val) => {
Expand All @@ -23,10 +22,7 @@ const connect = (callbackAfterChange = () => {}) => {
});
};

/*
* @return {String}
*/
function getPreferredLocale() {
function getPreferredLocale(): BaseLocale {
return preferredLocale;
}

Expand Down
13 changes: 0 additions & 13 deletions src/libs/Localize/LocaleListener/index.desktop.js

This file was deleted.

18 changes: 18 additions & 0 deletions src/libs/Localize/LocaleListener/index.desktop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import ELECTRON_EVENTS from '../../../../desktop/ELECTRON_EVENTS';
import BaseLocaleListener from './BaseLocaleListener';
import {LocaleListener, LocaleListenerConnect} from './types';

const localeListenerConnect: LocaleListenerConnect = (callbackAfterChange = () => {}) =>
BaseLocaleListener.connect((val) => {
// Send the updated locale to the Electron main process
window.electron.send(ELECTRON_EVENTS.LOCALE_UPDATED, val);

// Then execute the callback provided for the renderer process
callbackAfterChange(val);
});

const localeListener: LocaleListener = {
connect: localeListenerConnect,
};

export default localeListener;
5 changes: 0 additions & 5 deletions src/libs/Localize/LocaleListener/index.js

This file was deleted.

10 changes: 10 additions & 0 deletions src/libs/Localize/LocaleListener/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import BaseLocaleListener from './BaseLocaleListener';
import {LocaleListener, LocaleListenerConnect} from './types';

const localeListenerConnect: LocaleListenerConnect = BaseLocaleListener.connect;

const localizeListener: LocaleListener = {
connect: localeListenerConnect,
};

export default localizeListener;
13 changes: 13 additions & 0 deletions src/libs/Localize/LocaleListener/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {ValueOf} from 'type-fest';
import CONST from '@src/CONST';

type BaseLocale = ValueOf<typeof CONST.LOCALES>;

type LocaleListenerConnect = (callbackAfterChange?: (locale?: BaseLocale) => void) => void;

type LocaleListener = {
connect: LocaleListenerConnect;
};

export type {LocaleListenerConnect, LocaleListener};
export default BaseLocale;
102 changes: 40 additions & 62 deletions src/libs/Localize/index.js → src/libs/Localize/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import * as RNLocalize from 'react-native-localize';
import Onyx from 'react-native-onyx';
import _ from 'underscore';
import Log from '@libs/Log';
import Config from '@src/CONFIG';
import CONST from '@src/CONST';
import translations from '@src/languages/translations';
import {TranslationFlatObject, TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import LocaleListener from './LocaleListener';
import BaseLocaleListener from './LocaleListener/BaseLocaleListener';
Expand All @@ -15,12 +13,11 @@ import BaseLocaleListener from './LocaleListener/BaseLocaleListener';
let userEmail = '';
Onyx.connect({
key: ONYXKEYS.SESSION,
waitForCollectionCallback: true,
callback: (val) => {
if (!val) {
return;
}
userEmail = val.email;
userEmail = val?.email ?? '';
},
});

Expand All @@ -29,66 +26,60 @@ LocaleListener.connect();

// Note: This has to be initialized inside a function and not at the top level of the file, because Intl is polyfilled,
// and if React Native executes this code upon import, then the polyfill will not be available yet and it will barf
let CONJUNCTION_LIST_FORMATS_FOR_LOCALES;
let CONJUNCTION_LIST_FORMATS_FOR_LOCALES: Record<string, Intl.ListFormat>;
function init() {
CONJUNCTION_LIST_FORMATS_FOR_LOCALES = _.reduce(
CONST.LOCALES,
(memo, locale) => {
// This is not a supported locale, so we'll use ES_ES instead
if (locale === CONST.LOCALES.ES_ES_ONFIDO) {
// eslint-disable-next-line no-param-reassign
memo[locale] = new Intl.ListFormat(CONST.LOCALES.ES_ES, {style: 'long', type: 'conjunction'});
return memo;
}

CONJUNCTION_LIST_FORMATS_FOR_LOCALES = Object.values(CONST.LOCALES).reduce((memo: Record<string, Intl.ListFormat>, locale) => {
// This is not a supported locale, so we'll use ES_ES instead
if (locale === CONST.LOCALES.ES_ES_ONFIDO) {
// eslint-disable-next-line no-param-reassign
memo[locale] = new Intl.ListFormat(locale, {style: 'long', type: 'conjunction'});
memo[locale] = new Intl.ListFormat(CONST.LOCALES.ES_ES, {style: 'long', type: 'conjunction'});
return memo;
},
{},
);
}

// eslint-disable-next-line no-param-reassign
memo[locale] = new Intl.ListFormat(locale, {style: 'long', type: 'conjunction'});
return memo;
}, {});
}

type PhraseParameters<T> = T extends (...args: infer A) => string ? A : never[];
type Phrase<TKey extends TranslationPaths> = TranslationFlatObject[TKey] extends (...args: infer A) => unknown ? (...args: A) => string : string;

/**
* Return translated string for given locale and phrase
*
* @param {String} [desiredLanguage] eg 'en', 'es-ES'
* @param {String} phraseKey
* @param {Object} [phraseParameters] Parameters to supply if the phrase is a template literal.
* @returns {String}
* @param [desiredLanguage] eg 'en', 'es-ES'
* @param [phraseParameters] Parameters to supply if the phrase is a template literal.
*/
function translate(desiredLanguage = CONST.LOCALES.DEFAULT, phraseKey, phraseParameters = {}) {
const languageAbbreviation = desiredLanguage.substring(0, 2);
let translatedPhrase;

function translate<TKey extends TranslationPaths>(desiredLanguage: 'en' | 'es' | 'es-ES' | 'es_ES', phraseKey: TKey, ...phraseParameters: PhraseParameters<Phrase<TKey>>): string {
// Search phrase in full locale e.g. es-ES
const desiredLanguageDictionary = translations[desiredLanguage] || {};
translatedPhrase = desiredLanguageDictionary[phraseKey];
const language = desiredLanguage === CONST.LOCALES.ES_ES_ONFIDO ? CONST.LOCALES.ES_ES : desiredLanguage;
let translatedPhrase = translations?.[language]?.[phraseKey] as Phrase<TKey>;
if (translatedPhrase) {
return Str.result(translatedPhrase, phraseParameters);
return typeof translatedPhrase === 'function' ? translatedPhrase(...phraseParameters) : translatedPhrase;
}

// Phrase is not found in full locale, search it in fallback language e.g. es
const fallbackLanguageDictionary = translations[languageAbbreviation] || {};
translatedPhrase = fallbackLanguageDictionary[phraseKey];
const languageAbbreviation = desiredLanguage.substring(0, 2) as 'en' | 'es';
translatedPhrase = translations?.[languageAbbreviation]?.[phraseKey] as Phrase<TKey>;
if (translatedPhrase) {
return Str.result(translatedPhrase, phraseParameters);
return typeof translatedPhrase === 'function' ? translatedPhrase(...phraseParameters) : translatedPhrase;
}

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

// Phrase is not translated, search it in default language (en)
const defaultLanguageDictionary = translations[CONST.LOCALES.DEFAULT] || {};
translatedPhrase = defaultLanguageDictionary[phraseKey];
translatedPhrase = translations?.[CONST.LOCALES.DEFAULT]?.[phraseKey] as Phrase<TKey>;
if (translatedPhrase) {
return Str.result(translatedPhrase, phraseParameters);
return typeof translatedPhrase === 'function' ? translatedPhrase(...phraseParameters) : translatedPhrase;
}

// Phrase is not found in default language, on production and staging log an alert to server
// on development throw an error
if (Config.IS_IN_PRODUCTION || Config.IS_IN_STAGING) {
const phraseString = _.isArray(phraseKey) ? phraseKey.join('.') : phraseKey;
const phraseString: string = Array.isArray(phraseKey) ? phraseKey.join('.') : phraseKey;
Log.alert(`${phraseString} was not found in the en locale`);
if (userEmail.includes(CONST.EMAIL.EXPENSIFY_EMAIL_DOMAIN)) {
return CONST.MISSING_TRANSLATION;
Expand All @@ -100,49 +91,38 @@ function translate(desiredLanguage = CONST.LOCALES.DEFAULT, phraseKey, phrasePar

/**
* Uses the locale in this file updated by the Onyx subscriber.
*
* @param {String|Array} phrase
* @param {Object} [variables]
* @returns {String}
*/
function translateLocal(phrase, variables) {
return translate(BaseLocaleListener.getPreferredLocale(), phrase, variables);
function translateLocal<TKey extends TranslationPaths>(phrase: TKey, ...variables: PhraseParameters<Phrase<TKey>>) {
return translate(BaseLocaleListener.getPreferredLocale(), phrase, ...variables);
}

/**
* Return translated string for given error.
*
* @param {String|Array} message
* @returns {String}
*/
function translateIfPhraseKey(message) {
if (_.isEmpty(message)) {
function translateIfPhraseKey(message: string | [string, Record<string, unknown> & {isTranslated?: true}] | []): string {
if (!message || (Array.isArray(message) && message.length === 0)) {
return '';
}

try {
// check if error message has a variable parameter
const [phrase, variables] = _.isArray(message) ? message : [message];
const [phrase, variables] = Array.isArray(message) ? message : [message];

// This condition checks if the error is already translated. For example, if there are multiple errors per input, we handle translation in ErrorUtils.addErrorMessage due to the inability to concatenate error keys.

if (variables && variables.isTranslated) {
if (variables?.isTranslated) {
return phrase;
}

return translateLocal(phrase, variables);
return translateLocal(phrase as TranslationPaths, variables as never);
} catch (error) {
return message;
return Array.isArray(message) ? message[0] : message;
}
}

/**
* Format an array into a string with comma and "and" ("a dog, a cat and a chicken")
*
* @param {Array} anArray
* @return {String}
*/
function arrayToString(anArray) {
function arrayToString(anArray: string[]) {
if (!CONJUNCTION_LIST_FORMATS_FOR_LOCALES) {
init();
}
Expand All @@ -152,11 +132,9 @@ function arrayToString(anArray) {

/**
* Returns the user device's preferred language.
*
* @return {String}
*/
function getDevicePreferredLocale() {
return lodashGet(RNLocalize.findBestAvailableLanguage([CONST.LOCALES.EN, CONST.LOCALES.ES]), 'languageTag', CONST.LOCALES.DEFAULT);
function getDevicePreferredLocale(): string {
return RNLocalize.findBestAvailableLanguage([CONST.LOCALES.EN, CONST.LOCALES.ES])?.languageTag ?? CONST.LOCALES.DEFAULT;
}

export {translate, translateLocal, translateIfPhraseKey, arrayToString, getDevicePreferredLocale};
19 changes: 15 additions & 4 deletions src/libs/SidebarUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,10 +412,21 @@ function getOptionData(
const reportAction = lastReportActions?.[report.reportID];
if (result.isArchivedRoom) {
const archiveReason = (reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CLOSED && reportAction?.originalMessage?.reason) || CONST.REPORT.ARCHIVE_REASON.DEFAULT;
lastMessageText = Localize.translate(preferredLocale, `reportArchiveReasons.${archiveReason}`, {
displayName: PersonalDetailsUtils.getDisplayNameOrDefault(lastActorDetails, 'displayName'),
policyName: ReportUtils.getPolicyName(report, false, policy),
});

switch (archiveReason) {
case CONST.REPORT.ARCHIVE_REASON.ACCOUNT_CLOSED:
case CONST.REPORT.ARCHIVE_REASON.REMOVED_FROM_POLICY:
case CONST.REPORT.ARCHIVE_REASON.POLICY_DELETED: {
lastMessageText = Localize.translate(preferredLocale, `reportArchiveReasons.${archiveReason}`, {
policyName: ReportUtils.getPolicyName(report, false, policy),
displayName: PersonalDetailsUtils.getDisplayNameOrDefault(lastActorDetails, 'displayName'),
});
break;
}
default: {
lastMessageText = Localize.translate(preferredLocale, `reportArchiveReasons.default`);
}
}
}

if ((result.isChatRoom || result.isPolicyExpenseChat || result.isThread || result.isTaskReport) && !result.isArchivedRoom) {
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"es2021.weakref",
"es2022.array",
"es2022.object",
"es2022.string"
"es2022.string",
"ES2021.Intl"
],
"allowJs": true,
"checkJs": false,
Expand Down

0 comments on commit 7601f89

Please sign in to comment.