diff --git a/src/languages/translations.ts b/src/languages/translations.ts index d228394589b2..4d89f1f529de 100644 --- a/src/languages/translations.ts +++ b/src/languages/translations.ts @@ -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), }; diff --git a/src/languages/types.ts b/src/languages/types.ts index d2a387a329d0..5f6669315041 100644 --- a/src/languages/types.ts +++ b/src/languages/types.ts @@ -246,6 +246,7 @@ export type { EnglishTranslation, TranslationFlatObject, AddressLineParams, + TranslationPaths, CharacterLimitParams, MaxParticipantsReachedParams, ZipCodeExampleFormatParams, diff --git a/src/libs/DateUtils.ts b/src/libs/DateUtils.ts index 965d85134968..b956b5adcc51 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -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'); diff --git a/src/libs/ErrorUtils.ts b/src/libs/ErrorUtils.ts index 99cd8f34b1e7..5bc8ea1d3508 100644 --- a/src/libs/ErrorUtils.ts +++ b/src/libs/ErrorUtils.ts @@ -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'; @@ -93,7 +93,7 @@ type ErrorsList = Record; * @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(errors: ErrorsList, inputID?: string, message?: TKey) { if (!message || !inputID) { return; } diff --git a/src/libs/Localize/LocaleListener/BaseLocaleListener.js b/src/libs/Localize/LocaleListener/BaseLocaleListener.ts similarity index 72% rename from src/libs/Localize/LocaleListener/BaseLocaleListener.js rename to src/libs/Localize/LocaleListener/BaseLocaleListener.ts index 0f861b20040a..c5eba18af422 100644 --- a/src/libs/Localize/LocaleListener/BaseLocaleListener.js +++ b/src/libs/Localize/LocaleListener/BaseLocaleListener.ts @@ -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) => { @@ -23,10 +22,7 @@ const connect = (callbackAfterChange = () => {}) => { }); }; -/* - * @return {String} - */ -function getPreferredLocale() { +function getPreferredLocale(): BaseLocale { return preferredLocale; } diff --git a/src/libs/Localize/LocaleListener/index.desktop.js b/src/libs/Localize/LocaleListener/index.desktop.js deleted file mode 100644 index 0c0d723122da..000000000000 --- a/src/libs/Localize/LocaleListener/index.desktop.js +++ /dev/null @@ -1,13 +0,0 @@ -import ELECTRON_EVENTS from '../../../../desktop/ELECTRON_EVENTS'; -import BaseLocaleListener from './BaseLocaleListener'; - -export default { - connect: (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); - }), -}; diff --git a/src/libs/Localize/LocaleListener/index.desktop.ts b/src/libs/Localize/LocaleListener/index.desktop.ts new file mode 100644 index 000000000000..6974d3ed4879 --- /dev/null +++ b/src/libs/Localize/LocaleListener/index.desktop.ts @@ -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; diff --git a/src/libs/Localize/LocaleListener/index.js b/src/libs/Localize/LocaleListener/index.js deleted file mode 100644 index e5f1ea03f93f..000000000000 --- a/src/libs/Localize/LocaleListener/index.js +++ /dev/null @@ -1,5 +0,0 @@ -import BaseLocaleListener from './BaseLocaleListener'; - -export default { - connect: BaseLocaleListener.connect, -}; diff --git a/src/libs/Localize/LocaleListener/index.ts b/src/libs/Localize/LocaleListener/index.ts new file mode 100644 index 000000000000..b0dda5d5fabc --- /dev/null +++ b/src/libs/Localize/LocaleListener/index.ts @@ -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; diff --git a/src/libs/Localize/LocaleListener/types.ts b/src/libs/Localize/LocaleListener/types.ts new file mode 100644 index 000000000000..4daf90af0483 --- /dev/null +++ b/src/libs/Localize/LocaleListener/types.ts @@ -0,0 +1,13 @@ +import {ValueOf} from 'type-fest'; +import CONST from '@src/CONST'; + +type BaseLocale = ValueOf; + +type LocaleListenerConnect = (callbackAfterChange?: (locale?: BaseLocale) => void) => void; + +type LocaleListener = { + connect: LocaleListenerConnect; +}; + +export type {LocaleListenerConnect, LocaleListener}; +export default BaseLocale; diff --git a/src/libs/Localize/index.js b/src/libs/Localize/index.ts similarity index 52% rename from src/libs/Localize/index.js rename to src/libs/Localize/index.ts index f2f8cfa1f8b0..fd49902af369 100644 --- a/src/libs/Localize/index.js +++ b/src/libs/Localize/index.ts @@ -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'; @@ -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 ?? ''; }, }); @@ -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; 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, 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 extends (...args: infer A) => string ? A : never[]; +type Phrase = 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(desiredLanguage: 'en' | 'es' | 'es-ES' | 'es_ES', phraseKey: TKey, ...phraseParameters: PhraseParameters>): 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; 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; 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; 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; @@ -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(phrase: TKey, ...variables: PhraseParameters>) { + 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 & {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(); } @@ -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}; diff --git a/src/libs/SidebarUtils.ts b/src/libs/SidebarUtils.ts index 80ed96d25d65..8905616d94ce 100644 --- a/src/libs/SidebarUtils.ts +++ b/src/libs/SidebarUtils.ts @@ -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) { diff --git a/tsconfig.json b/tsconfig.json index 151087fb1321..eafc7c375fdd 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,8 @@ "es2021.weakref", "es2022.array", "es2022.object", - "es2022.string" + "es2022.string", + "ES2021.Intl" ], "allowJs": true, "checkJs": false,