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 17 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 @@ -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 @@ -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
@@ -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
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,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) => {
arosiclair marked this conversation as resolved.
Show resolved Hide resolved
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
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

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 '';
arosiclair marked this conversation as resolved.
Show resolved Hide resolved
}

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) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Why are we casting variables as never here?

Copy link
Contributor

Choose a reason for hiding this comment

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

@arosiclair We're casting variables as never to bypass TypeScript's strict type checking. translateIfPhraseKey is being used dynamically, e.g., with errors that comes from the backend which we don't have static types for.

It allows translateIfPhraseKey to call the strictly typed translateLocal function without type errors. Yep, it does reduce type safety for variables, but looking at the implementation of translation and translationLocal it shouldn't be an issue.

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 @@ -418,10 +418,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) {
arosiclair marked this conversation as resolved.
Show resolved Hide resolved
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
Loading