diff --git a/src/CONST.ts b/src/CONST.ts index 5bb2b06360d7..3e5777bba1de 100755 --- a/src/CONST.ts +++ b/src/CONST.ts @@ -1089,6 +1089,29 @@ const CONST = { DEFAULT: 'en', }, + LANGUAGES: ['en', 'es'], + + PRONOUNS_LIST: [ + 'coCos', + 'eEyEmEir', + 'heHimHis', + 'heHimHisTheyThemTheirs', + 'sheHerHers', + 'sheHerHersTheyThemTheirs', + 'merMers', + 'neNirNirs', + 'neeNerNers', + 'perPers', + 'theyThemTheirs', + 'thonThons', + 'veVerVis', + 'viVir', + 'xeXemXyr', + 'zeZieZirHir', + 'zeHirHirs', + 'callMeByMyName', + ], + POLICY: { TYPE: { FREE: 'free', @@ -1660,6 +1683,61 @@ const CONST = { ZW: 'Zimbabwe', }, + ALL_US_ISO_STATES: [ + 'AK', + 'AL', + 'AR', + 'AZ', + 'CA', + 'CO', + 'CT', + 'DE', + 'FL', + 'GA', + 'HI', + 'IA', + 'ID', + 'IL', + 'IN', + 'KS', + 'KY', + 'LA', + 'MA', + 'MD', + 'ME', + 'MI', + 'MN', + 'MO', + 'MS', + 'MT', + 'NC', + 'ND', + 'NE', + 'NH', + 'NJ', + 'NM', + 'NV', + 'NY', + 'OH', + 'OK', + 'OR', + 'PA', + 'PR', + 'RI', + 'SC', + 'SD', + 'TN', + 'TX', + 'UT', + 'VA', + 'VT', + 'WA', + 'WI', + 'WV', + 'WY', + 'DC', + ], + // Sources: https://github.com/Expensify/App/issues/14958#issuecomment-1442138427 // https://github.com/Expensify/App/issues/14958#issuecomment-1456026810 COUNTRY_ZIP_REGEX_DATA: { diff --git a/src/components/CountryPicker/CountrySelectorModal.js b/src/components/CountryPicker/CountrySelectorModal.js index e6ed1a77ce85..ac543d9921d2 100644 --- a/src/components/CountryPicker/CountrySelectorModal.js +++ b/src/components/CountryPicker/CountrySelectorModal.js @@ -49,13 +49,16 @@ function CountrySelectorModal({currentCountry, isVisible, onClose, onCountrySele const countries = useMemo( () => - _.map(translate('allCountries'), (countryName, countryISO) => ({ - value: countryISO, - keyForList: countryISO, - text: countryName, - isSelected: currentCountry === countryISO, - searchValue: StringUtils.sanitizeString(`${countryISO}${countryName}`), - })), + _.map(_.keys(CONST.ALL_COUNTRIES), (countryISO) => { + const countryName = translate(`allCountries.${countryISO}`); + return { + value: countryISO, + keyForList: countryISO, + text: countryName, + isSelected: currentCountry === countryISO, + searchValue: StringUtils.sanitizeString(`${countryISO}${countryName}`), + }; + }), [translate, currentCountry], ); diff --git a/src/components/CountryPicker/index.js b/src/components/CountryPicker/index.js index c6bbae0dd645..c838ed8f4060 100644 --- a/src/components/CountryPicker/index.js +++ b/src/components/CountryPicker/index.js @@ -31,7 +31,6 @@ const defaultProps = { function CountryPicker({value, errorText, onInputChange, forwardedRef}) { const {translate} = useLocalize(); - const allCountries = translate('allCountries'); const [isPickerVisible, setIsPickerVisible] = useState(false); const [searchValue, setSearchValue] = useState(''); @@ -48,7 +47,7 @@ function CountryPicker({value, errorText, onInputChange, forwardedRef}) { hidePickerModal(); }; - const title = allCountries[value] || ''; + const title = value ? translate(`allCountries.${value}`) : ''; const descStyle = title.length === 0 ? styles.textNormal : null; return ( diff --git a/src/components/LocalePicker.js b/src/components/LocalePicker.js index 532c29535e50..435f88e51e53 100644 --- a/src/components/LocalePicker.js +++ b/src/components/LocalePicker.js @@ -27,9 +27,11 @@ const defaultProps = { }; function LocalePicker(props) { - const localesToLanguages = _.map(props.translate('languagePage.languages'), (language, key) => ({ - value: key, - label: language.label, + const localesToLanguages = _.map(CONST.LANGUAGES, (language) => ({ + value: language, + label: props.translate(`languagePage.languages.${language}.label`), + keyForList: language, + isSelected: props.preferredLocale === language, })); return ( - _.map(translate('allStates'), (state) => ({ - value: state.stateISO, - keyForList: state.stateISO, - text: state.stateName, - isSelected: currentState === state.stateISO, - searchValue: StringUtils.sanitizeString(`${state.stateISO}${state.stateName}`), - })), + _.map(CONST.ALL_US_ISO_STATES, (state) => { + const stateName = translate(`allStates.${state}.stateName`); + const stateISO = translate(`allStates.${state}.stateISO`); + return { + value: stateISO, + keyForList: stateISO, + text: stateName, + isSelected: currentState === stateISO, + searchValue: StringUtils.sanitizeString(`${stateISO}${stateName}`), + }; + }), [translate, currentState], ); diff --git a/src/components/StatePicker/index.js b/src/components/StatePicker/index.js index a4d3ea5e8133..9653a207c1fb 100644 --- a/src/components/StatePicker/index.js +++ b/src/components/StatePicker/index.js @@ -35,7 +35,6 @@ const defaultProps = { function StatePicker({value, errorText, onInputChange, forwardedRef, label}) { const {translate} = useLocalize(); - const allStates = translate('allStates'); const [isPickerVisible, setIsPickerVisible] = useState(false); const [searchValue, setSearchValue] = useState(''); @@ -52,7 +51,7 @@ function StatePicker({value, errorText, onInputChange, forwardedRef, label}) { hidePickerModal(); }; - const title = allStates[value] ? allStates[value].stateName : ''; + const title = value ? translate(`allStates.${value}.stateName`) : ''; const descStyle = title.length === 0 ? styles.textNormal : null; return ( diff --git a/src/languages/en.ts b/src/languages/en.ts index bd518f1fdda9..1f3e8048a7b0 100755 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -1,6 +1,7 @@ import {CONST as COMMON_CONST} from 'expensify-common/lib/CONST'; import CONST from '../CONST'; import type { + Translation, AddressLineParams, CharacterLimitParams, MaxParticipantsReachedParams, @@ -1755,4 +1756,4 @@ export default { selectSuggestedAddress: 'Please select a suggested address', }, }, -} as const; +} satisfies Translation; diff --git a/src/languages/es.ts b/src/languages/es.ts index 3c5d98b724d2..7b7f736dc994 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -1,6 +1,7 @@ import CONST from '../CONST'; import * as ReportActionsUtils from '../libs/ReportActionsUtils'; import type { + Translation, AddressLineParams, CharacterLimitParams, MaxParticipantsReachedParams, @@ -2247,4 +2248,4 @@ export default { selectSuggestedAddress: 'Por favor, selecciona una dirección sugerida', }, }, -}; +} satisfies Translation; diff --git a/src/languages/translations.ts b/src/languages/translations.ts index a2d27baa26c9..3a04190b2bff 100644 --- a/src/languages/translations.ts +++ b/src/languages/translations.ts @@ -1,10 +1,50 @@ import en from './en'; import es from './es'; import esES from './es-ES'; +import type {Translation, TranslationFlatObject} from './types'; + +/** + * Converts an object to it's flattened version. + * + * Ex: + * Input: { common: { yes: "Yes", no: "No" }} + * Output: { "common.yes": "Yes", "common.no": "No" } + */ +// Necessary to export so that it is accessible to the unit tests +// eslint-disable-next-line rulesdir/no-inline-named-export +export function flattenObject(obj: Translation): TranslationFlatObject { + const result: Record = {}; + + const recursive = (data: Translation, key: string): void => { + // If the data is a function or not a object (eg. a string or array), + // it's the final value for the key being built and there is no need + // for more recursion + if (typeof data === 'function' || Array.isArray(data) || !(typeof data === 'object' && !!data)) { + result[key] = data; + } else { + let isEmpty = true; + + // Recursive call to the keys and connect to the respective data + Object.keys(data).forEach((k) => { + isEmpty = false; + recursive(data[k] as Translation, key ? `${key}.${k}` : k); + }); + + // Check for when the object is empty but a key exists, so that + // it defaults to an empty object + if (isEmpty && key) { + result[key] = ''; + } + } + }; + + recursive(obj, ''); + return result as TranslationFlatObject; +} export default { - en, - es, + en: flattenObject(en), + es: flattenObject(es), // eslint-disable-next-line @typescript-eslint/naming-convention 'es-ES': esES, }; diff --git a/src/languages/types.ts b/src/languages/types.ts index 7a698f912b14..17c5e1f1a07c 100644 --- a/src/languages/types.ts +++ b/src/languages/types.ts @@ -1,3 +1,5 @@ +import en from './en'; + type AddressLineParams = { lineNumber: number; }; @@ -190,7 +192,47 @@ type RemovedTheRequestParams = {valueName: string; oldValueToDisplay: string}; type UpdatedTheRequestParams = {valueName: string; newValueToDisplay: string; oldValueToDisplay: string}; +/* Translation Object types */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type TranslationBaseValue = string | string[] | ((...args: any[]) => string); + +type Translation = {[key: string]: TranslationBaseValue | Translation}; + +/* Flat Translation Object types */ +// Flattens an object and returns concatenations of all the keys of nested objects +type FlattenObject = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [TKey in keyof TObject]: TObject[TKey] extends (...args: any[]) => any + ? `${TPrefix}${TKey & string}` + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + TObject[TKey] extends any[] + ? `${TPrefix}${TKey & string}` + : // eslint-disable-next-line @typescript-eslint/ban-types + TObject[TKey] extends object + ? FlattenObject + : `${TPrefix}${TKey & string}`; +}[keyof TObject]; + +// Retrieves a type for a given key path (calculated from the type above) +type TranslateType = TPath extends keyof TObject + ? TObject[TPath] + : TPath extends `${infer TKey}.${infer TRest}` + ? TKey extends keyof TObject + ? TranslateType + : never + : never; + +type TranslationsType = typeof en; + +type TranslationPaths = FlattenObject; + +type TranslationFlatObject = { + [TKey in TranslationPaths]: TranslateType; +}; + export type { + Translation, + TranslationFlatObject, AddressLineParams, CharacterLimitParams, MaxParticipantsReachedParams, diff --git a/src/libs/Localize/index.js b/src/libs/Localize/index.js index 9878873377b8..db371301f43f 100644 --- a/src/libs/Localize/index.js +++ b/src/libs/Localize/index.js @@ -38,7 +38,7 @@ function init() { * Return translated string for given locale and phrase * * @param {String} [desiredLanguage] eg 'en', 'es-ES' - * @param {String|Array} phraseKey + * @param {String} phraseKey * @param {Object} [phraseParameters] Parameters to supply if the phrase is a template literal. * @returns {String} */ @@ -47,15 +47,15 @@ function translate(desiredLanguage = CONST.LOCALES.DEFAULT, phraseKey, phrasePar let translatedPhrase; // Search phrase in full locale e.g. es-ES - const desiredLanguageDictionary = lodashGet(translations, desiredLanguage); - translatedPhrase = lodashGet(desiredLanguageDictionary, phraseKey); + const desiredLanguageDictionary = translations[desiredLanguage] || {}; + translatedPhrase = desiredLanguageDictionary[phraseKey]; if (translatedPhrase) { return Str.result(translatedPhrase, phraseParameters); } // Phrase is not found in full locale, search it in fallback language e.g. es - const fallbackLanguageDictionary = lodashGet(translations, languageAbbreviation); - translatedPhrase = lodashGet(fallbackLanguageDictionary, phraseKey); + const fallbackLanguageDictionary = translations[languageAbbreviation] || {}; + translatedPhrase = fallbackLanguageDictionary[phraseKey]; if (translatedPhrase) { return Str.result(translatedPhrase, phraseParameters); } @@ -64,8 +64,8 @@ function translate(desiredLanguage = CONST.LOCALES.DEFAULT, phraseKey, phrasePar } // Phrase is not translated, search it in default language (en) - const defaultLanguageDictionary = lodashGet(translations, CONST.LOCALES.DEFAULT, {}); - translatedPhrase = lodashGet(defaultLanguageDictionary, phraseKey); + const defaultLanguageDictionary = translations[CONST.LOCALES.DEFAULT] || {}; + translatedPhrase = defaultLanguageDictionary[phraseKey]; if (translatedPhrase) { return Str.result(translatedPhrase, phraseParameters); } diff --git a/src/pages/settings/Preferences/LanguagePage.js b/src/pages/settings/Preferences/LanguagePage.js index 0eb93853726a..706fa3b62db6 100644 --- a/src/pages/settings/Preferences/LanguagePage.js +++ b/src/pages/settings/Preferences/LanguagePage.js @@ -7,6 +7,7 @@ import withLocalize, {withLocalizePropTypes} from '../../../components/withLocal import * as App from '../../../libs/actions/App'; import Navigation from '../../../libs/Navigation/Navigation'; import ROUTES from '../../../ROUTES'; +import CONST from '../../../CONST'; import SelectionList from '../../../components/SelectionList'; const propTypes = { @@ -17,11 +18,11 @@ const propTypes = { }; function LanguagePage(props) { - const localesToLanguages = _.map(props.translate('languagePage.languages'), (language, key) => ({ - value: key, - text: language.label, - keyForList: key, - isSelected: props.preferredLocale === key, + const localesToLanguages = _.map(CONST.LANGUAGES, (language) => ({ + value: language, + text: props.translate(`languagePage.languages.${language}.label`), + keyForList: language, + isSelected: props.preferredLocale === language, })); return ( diff --git a/src/pages/settings/Preferences/PreferencesPage.js b/src/pages/settings/Preferences/PreferencesPage.js index b8bb74295567..9e30e99ff38f 100755 --- a/src/pages/settings/Preferences/PreferencesPage.js +++ b/src/pages/settings/Preferences/PreferencesPage.js @@ -40,9 +40,6 @@ function PreferencesPage(props) { const {isProduction} = useEnvironment(); const {translate, preferredLocale} = useLocalize(); - const priorityModes = translate('priorityModePage.priorityModes'); - const languages = translate('languagePage.languages'); - return ( Navigation.navigate(ROUTES.SETTINGS_PRIORITY_MODE)} /> Navigation.navigate(ROUTES.SETTINGS_LANGUAGE)} /> diff --git a/src/pages/settings/Profile/ProfilePage.js b/src/pages/settings/Profile/ProfilePage.js index 1f89756353ff..b0cbe7c9cc32 100755 --- a/src/pages/settings/Profile/ProfilePage.js +++ b/src/pages/settings/Profile/ProfilePage.js @@ -57,7 +57,11 @@ function ProfilePage(props) { if (pronounsKey.startsWith(CONST.PRONOUNS.PREFIX)) { pronounsKey = pronounsKey.slice(CONST.PRONOUNS.PREFIX.length); } - return lodashGet(props.translate('pronouns'), pronounsKey, props.translate('profilePage.selectYourPronouns')); + + if (!pronounsKey) { + return props.translate('profilePage.selectYourPronouns'); + } + return props.translate(`pronouns.${pronounsKey}`); }; const currentUserDetails = props.currentUserPersonalDetails || {}; const contactMethodBrickRoadIndicator = UserUtils.getLoginListBrickRoadIndicator(props.loginList); diff --git a/src/pages/settings/Profile/PronounsPage.js b/src/pages/settings/Profile/PronounsPage.js index 5ce9957f568f..777cfa214e1a 100644 --- a/src/pages/settings/Profile/PronounsPage.js +++ b/src/pages/settings/Profile/PronounsPage.js @@ -27,23 +27,23 @@ function PronounsPage({currentUserPersonalDetails}) { const currentPronounsKey = currentPronouns.substring(CONST.PRONOUNS.PREFIX.length); const [searchValue, setSearchValue] = useState(() => { - const currentPronounsText = _.chain(translate('pronouns')) - .find((_value, key) => key === currentPronounsKey) + const currentPronounsText = _.chain(CONST.PRONOUNS_LIST) + .find((_value) => _value === currentPronounsKey) .value(); return currentPronounsText || ''; }); const filteredPronounsList = useMemo(() => { - const pronouns = _.chain(translate('pronouns')) - .map((value, key) => { - const fullPronounKey = `${CONST.PRONOUNS.PREFIX}${key}`; + const pronouns = _.chain(CONST.PRONOUNS_LIST) + .map((value) => { + const fullPronounKey = `${CONST.PRONOUNS.PREFIX}${value}`; const isCurrentPronouns = fullPronounKey === currentPronouns; return { - text: value, + text: translate(`pronouns.${value}`), value: fullPronounKey, - keyForList: key, + keyForList: value, isSelected: isCurrentPronouns, }; }) diff --git a/tests/unit/TranslateTest.js b/tests/unit/TranslateTest.js index 9ac23d6b81b0..45d4a12b61f5 100644 --- a/tests/unit/TranslateTest.js +++ b/tests/unit/TranslateTest.js @@ -7,19 +7,19 @@ const CONST = require('../../src/CONST').default; const originalTranslations = _.clone(translations); translations.default = { - [CONST.LOCALES.EN]: { + [CONST.LOCALES.EN]: translations.flattenObject({ testKey1: 'English', testKey2: 'Test Word 2', testKey3: 'Test Word 3', testKeyGroup: { testFunction: ({testVariable}) => `With variable ${testVariable}`, }, - }, - [CONST.LOCALES.ES]: { + }), + [CONST.LOCALES.ES]: translations.flattenObject({ testKey1: 'Spanish', testKey2: 'Spanish Word 2', - }, - [CONST.LOCALES.ES_ES]: {testKey1: 'Spanish ES'}, + }), + [CONST.LOCALES.ES_ES]: translations.flattenObject({testKey1: 'Spanish ES'}), }; describe('translate', () => { @@ -38,14 +38,12 @@ describe('translate', () => { test('Test when key is not found in default', () => { expect(() => Localize.translate(CONST.LOCALES.ES_ES, 'testKey4')).toThrow(Error); - expect(() => Localize.translate(CONST.LOCALES.ES_ES, ['a', 'b', 'c'])).toThrow(Error); }); test('Test when key is not found in default (Production Mode)', () => { const ORIGINAL_IS_IN_PRODUCTION = CONFIG.default.IS_IN_PRODUCTION; CONFIG.default.IS_IN_PRODUCTION = true; expect(Localize.translate(CONST.LOCALES.ES_ES, 'testKey4')).toBe('testKey4'); - expect(Localize.translate(CONST.LOCALES.ES_ES, ['a', 'b', 'c'])).toBe('a.b.c'); CONFIG.default.IS_IN_PRODUCTION = ORIGINAL_IS_IN_PRODUCTION; }); @@ -53,7 +51,6 @@ describe('translate', () => { const expectedValue = 'With variable Test Variable'; const testVariable = 'Test Variable'; expect(Localize.translate(CONST.LOCALES.EN, 'testKeyGroup.testFunction', {testVariable})).toBe(expectedValue); - expect(Localize.translate(CONST.LOCALES.EN, ['testKeyGroup', 'testFunction'], {testVariable})).toBe(expectedValue); }); }); @@ -97,3 +94,45 @@ describe('Translation Keys', () => { }); }); }); + +describe('flattenObject', () => { + it('It should work correctly', () => { + const func = ({content}) => `This is the content: ${content}`; + const simpleObject = { + common: { + yes: 'Yes', + no: 'No', + }, + complex: { + activity: { + none: 'No Activity', + some: 'Some Activity', + }, + report: { + title: { + expense: 'Expense', + task: 'Task', + }, + description: { + none: 'No description', + }, + content: func, + messages: ['Hello', 'Hi', 'Sup!'], + }, + }, + }; + + const result = translations.flattenObject(simpleObject); + expect(result).toStrictEqual({ + 'common.yes': 'Yes', + 'common.no': 'No', + 'complex.activity.none': 'No Activity', + 'complex.activity.some': 'Some Activity', + 'complex.report.title.expense': 'Expense', + 'complex.report.title.task': 'Task', + 'complex.report.description.none': 'No description', + 'complex.report.content': func, + 'complex.report.messages': ['Hello', 'Hi', 'Sup!'], + }); + }); +});