Skip to content
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

[TS migration] Migrate 'Localize' lib to TypeScript #29742

Merged
Merged
Show file tree
Hide file tree
Changes from 10 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
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 @@ -245,6 +245,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 @@ -133,7 +133,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
Expand Up @@ -3,7 +3,7 @@ import DateUtils from './DateUtils';
import * as Localize from './Localize';
import Response from '../types/onyx/Response';
import {ErrorFields, Errors} from '../types/onyx/OnyxCommon';
import {TranslationFlatObject} from '../languages/types';
import {TranslationFlatObject, TranslationPaths} from '../languages/types';

function getAuthenticateErrorMessage(response: Response): keyof TranslationFlatObject {
switch (response.jsonCode) {
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 '../../../CONST';
import ONYXKEYS from '../../../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.

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

const localeListener: 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);
});

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

This file was deleted.

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

const localeListener: LocaleListenerConnect = BaseLocaleListener.connect;

export default {
connect: localeListener,
};
9 changes: 9 additions & 0 deletions src/libs/Localize/LocaleListener/types.ts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we create a type for LocaleListener object itself and use it?

// types.ts
type LocaleListener = {
    connect: LocaleListenerConnect;
};

// index.native.ts
const localeListener: LocaleListener = {
    connect: BaseLocaleListener.connect;
};

export default localeListener;

In this way we ensure the default export structure is safely typed.

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import {ValueOf} from 'type-fest';
import CONST from '../../../CONST';

type BaseLocale = ValueOf<typeof CONST.LOCALES>;

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

export type {LocaleListenerConnect};
export default BaseLocale;
104 changes: 41 additions & 63 deletions src/libs/Localize/index.js → src/libs/Localize/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import _ from 'underscore';
import lodashGet from 'lodash/get';
import Str from 'expensify-common/lib/str';
import * as RNLocalize from 'react-native-localize';
import Onyx from 'react-native-onyx';
import Log from '../Log';
Expand All @@ -9,18 +6,18 @@ import translations from '../../languages/translations';
import CONST from '../../CONST';
import LocaleListener from './LocaleListener';
import BaseLocaleListener from './LocaleListener/BaseLocaleListener';
import {TranslationFlatObject, TranslationPaths} from '../../languages/types';
import ONYXKEYS from '../../ONYXKEYS';

// Current user mail is needed for handling missing translations
let userEmail = '';
Onyx.connect({
key: ONYXKEYS.SESSION,
waitForCollectionCallback: true,
arosiclair marked this conversation as resolved.
Show resolved Hide resolved
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 {
Comment on lines -60 to +54
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The translate function used to take 3 arguments and the third one being an object containing the parameters to be used by the translation phrase. Now the third argument is using the rest syntax and it's an array. Was that change intended?

Also previously the 3rd argument had a default value and now it does not which caused #34668 and #30949

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it was an intended change, now this function can take 2 arguments for translations like:

translate('en', 'common.error.invalidAmount');
// function translate<"common.error.invalidAmount">(desiredLanguage: 'en' | 'es' | 'es-ES' | 'es_ES', phraseKey: "common.error.invalidAmount", ...phraseParameters: never[]): string

3 arguments if translation takes additional argument:

translate('en', 'common.error.characterLimit', {limit: 10});
// function translate<"common.error.characterLimit">(desiredLanguage: 'en' | 'es' | 'es-ES' | 'es_ES', phraseKey: "common.error.characterLimit", phraseParameters_0: CharacterLimitParams): string

4 and more arguments if translation takes more than one argument:

//src/languages/en.ts
test: (arg1: string, arg2: string) => `This is a test ${arg1} ${arg2}`,

translate('en', 'common.error.test', "arg1", "arg2");
// function translate<"common.error.test">(desiredLanguage: 'en' | 'es' | 'es-ES' | 'es_ES', phraseKey: "common.error.test", arg1: string, arg2: string): string

Also previously the 3rd argument had a default value and now it does not which caused #34668 and #30949

Translation functions that takes arguments should always receive them, so I think this just uncovered these bugs 😅

Otherwise we'd add the missing parameters for translation that takes parameters.

I think we should always add missing parameters to translate function

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you know if we can have typescript help us with that? i.e. yield an error if we are missing to pass parameters to a translation function

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's already implemented @s77rt, but only in .ts/.tsx files

// 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<TKey extends TranslationPaths>(message: TKey | [TKey, PhraseParameters<Phrase<TKey>> & {isTranslated?: true}]): string {
if (!message || (Array.isArray(message) && message.length > 0)) {
arosiclair marked this conversation as resolved.
Show resolved Hide resolved
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) {
return phrase;
if (variables?.isTranslated) {
return phrase as string;
}

return translateLocal(phrase, variables);
return translateLocal(phrase, ...(variables as PhraseParameters<Phrase<TKey>>));
} 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};
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