From e3b58528a8cb56f23866f66191f8ee7f984ddc01 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Wed, 23 Aug 2023 14:13:19 +0100 Subject: [PATCH 01/15] test: unit test for translation flatten object function --- tests/unit/translations.js | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tests/unit/translations.js diff --git a/tests/unit/translations.js b/tests/unit/translations.js new file mode 100644 index 000000000000..c411237e6c67 --- /dev/null +++ b/tests/unit/translations.js @@ -0,0 +1,45 @@ +const translations = require('../../src/languages/translations'); + +describe('Translations', () => { + 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!"], + }); + }); + }); +}); From 82919b7856bbc5e8a48d5c1f99771a962d84cf2a Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Wed, 23 Aug 2023 14:13:26 +0100 Subject: [PATCH 02/15] feat: flatten object function to flatten translation --- src/languages/translations.js | 46 +++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/src/languages/translations.js b/src/languages/translations.js index c8dd8c8ab0e0..5dd45e83624f 100644 --- a/src/languages/translations.js +++ b/src/languages/translations.js @@ -1,9 +1,51 @@ +import _ from 'underscore'; import en from './en'; import es from './es'; import esES from './es-ES'; +/** + * Converts an object to it's flattened version. + * + * Ex: + * Input: { common: { yes: "Yes", no: "No" }} + * Output: { "common.yes": "Yes", "common.no": "No" } + * + * @param {Object} obj + * @returns {Object} + */ +// 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) { + const result = {}; + + const recursive = (data, key) => { + // If the data is a function or not a object (eg. a string), it's + // the value of the key being built and no need for more recursion + if (_.isFunction(data) || _.isArray(data) || !_.isObject(data)) { + result[key] = data; + } else { + let isEmpty = true; + + // Recursive call to the keys and connect to the respective data + _.keys(data).forEach((k) => { + isEmpty = false; + recursive(data[k], 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; +} + export default { - en, - es, + en: flattenObject(en), + es: flattenObject(es), 'es-ES': esES, }; From 463daff3e06ed6f94484588ee3c90aff8beccc9f Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Wed, 23 Aug 2023 16:02:00 +0100 Subject: [PATCH 03/15] feat: remove lodashGet from translate --- src/libs/Localize/index.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/libs/Localize/index.js b/src/libs/Localize/index.js index 9878873377b8..a581e42b65e0 100644 --- a/src/libs/Localize/index.js +++ b/src/libs/Localize/index.js @@ -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[desiredLanguage] || {}; + 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); } From 62d4e91f3b6cee85f65433f0adc90c696c9975bc Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Wed, 23 Aug 2023 16:03:00 +0100 Subject: [PATCH 04/15] feat: migrate use of languages translate to new solution --- src/CONST.js | 2 ++ src/components/LocalePicker.js | 8 +++++--- src/pages/settings/Preferences/LanguagePage.js | 12 +++++++----- src/pages/settings/Preferences/PreferencesPage.js | 7 ++----- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/CONST.js b/src/CONST.js index 878d3f858dfb..72433212e320 100755 --- a/src/CONST.js +++ b/src/CONST.js @@ -1078,6 +1078,8 @@ const CONST = { DEFAULT: 'en', }, + LANGUAGES: ['en', 'es'], + POLICY: { TYPE: { FREE: 'free', 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 ( ({ - 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 ( Navigation.navigate(ROUTES.SETTINGS_PRIORITY_MODE)} /> Navigation.navigate(ROUTES.SETTINGS_LANGUAGE)} /> From 370d6790cce9b4d1808c3f052a4908e85331e462 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Wed, 23 Aug 2023 16:03:07 +0100 Subject: [PATCH 05/15] feat: migrate use of pronouns translate to new solution --- src/CONST.js | 21 +++++++++++++++++++++ src/pages/settings/Profile/ProfilePage.js | 6 +++++- src/pages/settings/Profile/PronounsPage.js | 13 ++++++------- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/CONST.js b/src/CONST.js index 72433212e320..0aa4c0f082c0 100755 --- a/src/CONST.js +++ b/src/CONST.js @@ -1080,6 +1080,27 @@ const CONST = { 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', diff --git a/src/pages/settings/Profile/ProfilePage.js b/src/pages/settings/Profile/ProfilePage.js index 1f89756353ff..e86ccd685d3e 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 50a231523834..eb799a4fe190 100644 --- a/src/pages/settings/Profile/PronounsPage.js +++ b/src/pages/settings/Profile/PronounsPage.js @@ -36,22 +36,21 @@ function PronounsPage(props) { const loadPronouns = useCallback(() => { const currentPronouns = lodashGet(props.currentUserPersonalDetails, 'pronouns', ''); - const pronouns = _.chain(props.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; if (isCurrentPronouns) { setInitiallyFocusedOption({ - text: value, - keyForList: key, + text: props.translate(`pronouns.${value}`), + keyForList: value, }); } return { - text: value, + text: props.translate(`pronouns.${value}`), value: fullPronounKey, - keyForList: key, + keyForList: value, isSelected: isCurrentPronouns, }; }) From 9f84e4245048122fa0fd0f1978cc1d76a1dc21d3 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Wed, 23 Aug 2023 17:11:58 +0100 Subject: [PATCH 06/15] feat: migrate use of countries and states translate to new solution --- src/CONST.js | 57 ++++++++++++++++++- .../CountryPicker/CountrySelectorModal.js | 17 +++--- src/components/CountryPicker/index.js | 12 ++-- .../StatePicker/StateSelectorModal.js | 18 +++--- src/components/StatePicker/index.js | 12 ++-- 5 files changed, 87 insertions(+), 29 deletions(-) diff --git a/src/CONST.js b/src/CONST.js index 0aa4c0f082c0..0b64d0904c8e 100755 --- a/src/CONST.js +++ b/src/CONST.js @@ -1098,7 +1098,7 @@ const CONST = { 'xeXemXyr', 'zeZieZirHir', 'zeHirHirs', - 'callMeByMyName' + 'callMeByMyName', ], POLICY: { @@ -1664,6 +1664,61 @@ const CONST = { ZW: 'Zimbabwe', }, + ALL_STATES: { + AK: 'Alaska', + AL: 'Alabama', + AR: 'Arkansas', + AZ: 'Arizona', + CA: 'California', + CO: 'Colorado', + CT: 'Connecticut', + DE: 'Delaware', + FL: 'Florida', + GA: 'Georgia', + HI: 'Hawaii', + IA: 'Iowa', + ID: 'Idaho', + IL: 'Illinois', + IN: 'Indiana', + KS: 'Kansas', + KY: 'Kentucky', + LA: 'Louisiana', + MA: 'Massachusetts', + MD: 'Maryland', + ME: 'Maine', + MI: 'Michigan', + MN: 'Minnesota', + MO: 'Missouri', + MS: 'Mississippi', + MT: 'Montana', + NC: 'North Carolina', + ND: 'North Dakota', + NE: 'Nebraska', + NH: 'New Hampshire', + NJ: 'New Jersey', + NM: 'New Mexico', + NV: 'Nevada', + NY: 'New York', + OH: 'Ohio', + OK: 'Oklahoma', + OR: 'Oregon', + PA: 'Pennsylvania', + PR: 'Puerto Rico', + RI: 'Rhode Island', + SC: 'South Carolina', + SD: 'South Dakota', + TN: 'Tennessee', + TX: 'Texas', + UT: 'Utah', + VA: 'Virginia', + VT: 'Vermont', + WA: 'Washington', + WI: 'Wisconsin', + WV: 'West Virginia', + WY: 'Wyoming', + DC: 'District Of Columbia', + }, + // 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 146b023bbf0c..c68aea276ee2 100644 --- a/src/components/CountryPicker/CountrySelectorModal.js +++ b/src/components/CountryPicker/CountrySelectorModal.js @@ -42,13 +42,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 6d1435dca796..9cae6291fafa 100644 --- a/src/components/CountryPicker/index.js +++ b/src/components/CountryPicker/index.js @@ -1,7 +1,6 @@ import React, {useEffect, useState} from 'react'; import {View} from 'react-native'; import PropTypes from 'prop-types'; -import lodashGet from 'lodash/get'; import styles from '../../styles/styles'; import MenuItemWithTopDescription from '../MenuItemWithTopDescription'; import useLocalize from '../../hooks/useLocalize'; @@ -31,16 +30,15 @@ const defaultProps = { function CountryPicker({value, errorText, onInputChange, forwardedRef}) { const {translate} = useLocalize(); - const allCountries = translate('allCountries'); const [isPickerVisible, setIsPickerVisible] = useState(false); - const [searchValue, setSearchValue] = useState(lodashGet(allCountries, value, '')); + const [searchValue, setSearchValue] = useState(value ? translate(`allCountries.${value}`) : ''); useEffect(() => { - setSearchValue(lodashGet(allCountries, value, '')); - }, [value, allCountries]); + setSearchValue(value ? translate(`allCountries.${value}`) : ''); + }, [value, translate]); const showPickerModal = () => { - setSearchValue(lodashGet(allCountries, value, '')); + setSearchValue(value ? translate(`allCountries.${value}`) : ''); setIsPickerVisible(true); }; @@ -53,7 +51,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/StatePicker/StateSelectorModal.js b/src/components/StatePicker/StateSelectorModal.js index 91ee1b225a1f..707562026786 100644 --- a/src/components/StatePicker/StateSelectorModal.js +++ b/src/components/StatePicker/StateSelectorModal.js @@ -46,13 +46,17 @@ function StateSelectorModal({currentState, isVisible, onClose, onStateSelected, const countryStates = useMemo( () => - _.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(_.keys(CONST.ALL_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 c934790f54e5..a069a39623c0 100644 --- a/src/components/StatePicker/index.js +++ b/src/components/StatePicker/index.js @@ -1,6 +1,5 @@ import React, {useEffect, useState} from 'react'; import {View} from 'react-native'; -import lodashGet from 'lodash/get'; import PropTypes from 'prop-types'; import styles from '../../styles/styles'; import MenuItemWithTopDescription from '../MenuItemWithTopDescription'; @@ -35,16 +34,15 @@ 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(lodashGet(allStates, `${value}.stateName`, '')); + const [searchValue, setSearchValue] = useState(value ? translate(`allStates.${value}.stateName`) : ''); useEffect(() => { - setSearchValue(lodashGet(allStates, `${value}.stateName`, '')); - }, [value, allStates]); + setSearchValue(value ? translate(`allStates.${value}.stateName`) : ''); + }, [translate, value]); const showPickerModal = () => { - setSearchValue(lodashGet(allStates, `${value}.stateName`, '')); + setSearchValue(value ? translate(`allStates.${value}.stateName`) : ''); setIsPickerVisible(true); }; @@ -57,7 +55,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 ( From 654824122508f525977b1971735a5f05778da9c6 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Wed, 23 Aug 2023 17:12:04 +0100 Subject: [PATCH 07/15] style: prettier --- src/pages/settings/Preferences/LanguagePage.js | 1 - src/pages/settings/Profile/ProfilePage.js | 2 +- src/pages/settings/Profile/PronounsPage.js | 3 ++- tests/unit/translations.js | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pages/settings/Preferences/LanguagePage.js b/src/pages/settings/Preferences/LanguagePage.js index ac575b987ba2..706fa3b62db6 100644 --- a/src/pages/settings/Preferences/LanguagePage.js +++ b/src/pages/settings/Preferences/LanguagePage.js @@ -25,7 +25,6 @@ function LanguagePage(props) { isSelected: props.preferredLocale === language, })); - return ( { const currentPronouns = lodashGet(props.currentUserPersonalDetails, 'pronouns', ''); - const pronouns = _.chain(CONST.PRONOUNS_LIST).map((value) => { + const pronouns = _.chain(CONST.PRONOUNS_LIST) + .map((value) => { const fullPronounKey = `${CONST.PRONOUNS.PREFIX}${value}`; const isCurrentPronouns = fullPronounKey === currentPronouns; diff --git a/tests/unit/translations.js b/tests/unit/translations.js index c411237e6c67..0f79f61f34fb 100644 --- a/tests/unit/translations.js +++ b/tests/unit/translations.js @@ -23,7 +23,7 @@ describe('Translations', () => { none: 'No description', }, content: func, - messages: ["Hello", "Hi", "Sup!"] + messages: ['Hello', 'Hi', 'Sup!'], }, }, }; @@ -38,7 +38,7 @@ describe('Translations', () => { 'complex.report.title.task': 'Task', 'complex.report.description.none': 'No description', 'complex.report.content': func, - 'complex.report.messages': ["Hello", "Hi", "Sup!"], + 'complex.report.messages': ['Hello', 'Hi', 'Sup!'], }); }); }); From f38a0bf7e664d20d2ad3158d7fd496992e9443a1 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Thu, 24 Aug 2023 14:18:59 +0100 Subject: [PATCH 08/15] fix: small error --- src/libs/Localize/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libs/Localize/index.js b/src/libs/Localize/index.js index a581e42b65e0..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} */ @@ -54,7 +54,7 @@ function translate(desiredLanguage = CONST.LOCALES.DEFAULT, phraseKey, phrasePar } // Phrase is not found in full locale, search it in fallback language e.g. es - const fallbackLanguageDictionary = translations[desiredLanguage] || {}; + const fallbackLanguageDictionary = translations[languageAbbreviation] || {}; translatedPhrase = fallbackLanguageDictionary[phraseKey]; if (translatedPhrase) { return Str.result(translatedPhrase, phraseParameters); From 2fef893390000ace720f3c71af1be726ff6b0f86 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Thu, 24 Aug 2023 14:20:02 +0100 Subject: [PATCH 09/15] refactor: move unit test to translate unit suite --- tests/unit/TranslateTest.js | 53 ++++++++++++++++++++++++++++++++----- tests/unit/translations.js | 45 ------------------------------- 2 files changed, 47 insertions(+), 51 deletions(-) delete mode 100644 tests/unit/translations.js diff --git a/tests/unit/TranslateTest.js b/tests/unit/TranslateTest.js index 9ac23d6b81b0..d7dffa2293e7 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', () => { @@ -53,7 +53,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 +96,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!'], + }); + }); +}); diff --git a/tests/unit/translations.js b/tests/unit/translations.js deleted file mode 100644 index 0f79f61f34fb..000000000000 --- a/tests/unit/translations.js +++ /dev/null @@ -1,45 +0,0 @@ -const translations = require('../../src/languages/translations'); - -describe('Translations', () => { - 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!'], - }); - }); - }); -}); From 9d8b224bde17718943ecb66b884ef28d43acfcba Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Thu, 24 Aug 2023 14:24:00 +0100 Subject: [PATCH 10/15] fix: remove unused usage --- tests/unit/TranslateTest.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/unit/TranslateTest.js b/tests/unit/TranslateTest.js index d7dffa2293e7..45d4a12b61f5 100644 --- a/tests/unit/TranslateTest.js +++ b/tests/unit/TranslateTest.js @@ -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; }); From ad78499070c7f8ca766e7f47d951f35c37863d2f Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Fri, 25 Aug 2023 14:41:41 +0100 Subject: [PATCH 11/15] feat: rename const --- src/CONST.js | 2 +- src/components/StatePicker/StateSelectorModal.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CONST.js b/src/CONST.js index 0b64d0904c8e..9b4a84c10ce4 100755 --- a/src/CONST.js +++ b/src/CONST.js @@ -1664,7 +1664,7 @@ const CONST = { ZW: 'Zimbabwe', }, - ALL_STATES: { + ALL_US_STATES: { AK: 'Alaska', AL: 'Alabama', AR: 'Arkansas', diff --git a/src/components/StatePicker/StateSelectorModal.js b/src/components/StatePicker/StateSelectorModal.js index 707562026786..91458892676a 100644 --- a/src/components/StatePicker/StateSelectorModal.js +++ b/src/components/StatePicker/StateSelectorModal.js @@ -46,7 +46,7 @@ function StateSelectorModal({currentState, isVisible, onClose, onStateSelected, const countryStates = useMemo( () => - _.map(_.keys(CONST.ALL_STATES), (state) => { + _.map(_.keys(CONST.ALL_US_STATES), (state) => { const stateName = translate(`allStates.${state}.stateName`); const stateISO = translate(`allStates.${state}.stateISO`); return { From 0088b39d496cddb72ad9b1e8a8d33f89e2c4f877 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Mon, 4 Sep 2023 08:52:36 +0100 Subject: [PATCH 12/15] feat: switch us states const to an array of ISOs --- src/CONST.js | 108 +++++++++--------- .../StatePicker/StateSelectorModal.js | 2 +- 2 files changed, 55 insertions(+), 55 deletions(-) diff --git a/src/CONST.js b/src/CONST.js index 9b4a84c10ce4..33c8aeaf5289 100755 --- a/src/CONST.js +++ b/src/CONST.js @@ -1664,60 +1664,60 @@ const CONST = { ZW: 'Zimbabwe', }, - ALL_US_STATES: { - AK: 'Alaska', - AL: 'Alabama', - AR: 'Arkansas', - AZ: 'Arizona', - CA: 'California', - CO: 'Colorado', - CT: 'Connecticut', - DE: 'Delaware', - FL: 'Florida', - GA: 'Georgia', - HI: 'Hawaii', - IA: 'Iowa', - ID: 'Idaho', - IL: 'Illinois', - IN: 'Indiana', - KS: 'Kansas', - KY: 'Kentucky', - LA: 'Louisiana', - MA: 'Massachusetts', - MD: 'Maryland', - ME: 'Maine', - MI: 'Michigan', - MN: 'Minnesota', - MO: 'Missouri', - MS: 'Mississippi', - MT: 'Montana', - NC: 'North Carolina', - ND: 'North Dakota', - NE: 'Nebraska', - NH: 'New Hampshire', - NJ: 'New Jersey', - NM: 'New Mexico', - NV: 'Nevada', - NY: 'New York', - OH: 'Ohio', - OK: 'Oklahoma', - OR: 'Oregon', - PA: 'Pennsylvania', - PR: 'Puerto Rico', - RI: 'Rhode Island', - SC: 'South Carolina', - SD: 'South Dakota', - TN: 'Tennessee', - TX: 'Texas', - UT: 'Utah', - VA: 'Virginia', - VT: 'Vermont', - WA: 'Washington', - WI: 'Wisconsin', - WV: 'West Virginia', - WY: 'Wyoming', - DC: 'District Of Columbia', - }, + 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 diff --git a/src/components/StatePicker/StateSelectorModal.js b/src/components/StatePicker/StateSelectorModal.js index 91458892676a..39dcf3479478 100644 --- a/src/components/StatePicker/StateSelectorModal.js +++ b/src/components/StatePicker/StateSelectorModal.js @@ -46,7 +46,7 @@ function StateSelectorModal({currentState, isVisible, onClose, onStateSelected, const countryStates = useMemo( () => - _.map(_.keys(CONST.ALL_US_STATES), (state) => { + _.map(CONST.ALL_US_ISO_STATES, (state) => { const stateName = translate(`allStates.${state}.stateName`); const stateISO = translate(`allStates.${state}.stateISO`); return { From be487e778beea017cf8e0913fa142d6c2c3b8140 Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Tue, 12 Sep 2023 16:59:00 +0100 Subject: [PATCH 13/15] feat: improve translation types --- src/languages/en.ts | 2 +- src/languages/es.ts | 3 ++- src/languages/translations.ts | 10 +++++----- src/languages/types.ts | 32 +++++++++++++++++++++++++++++--- 4 files changed, 37 insertions(+), 10 deletions(-) diff --git a/src/languages/en.ts b/src/languages/en.ts index e9fb2fc0fb7c..1f3e8048a7b0 100755 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -1756,4 +1756,4 @@ export default { selectSuggestedAddress: 'Please select a suggested address', }, }, -} as Translation; +} 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 e631c2f4522d..3a04190b2bff 100644 --- a/src/languages/translations.ts +++ b/src/languages/translations.ts @@ -1,7 +1,7 @@ import en from './en'; import es from './es'; import esES from './es-ES'; -import type {Translation, TranslationBaseValue, TranslationFlatObject} from './types'; +import type {Translation, TranslationFlatObject} from './types'; /** * Converts an object to it's flattened version. @@ -13,14 +13,14 @@ import type {Translation, TranslationBaseValue, TranslationFlatObject} from './t // 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: 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 as TranslationBaseValue; + result[key] = data; } else { let isEmpty = true; @@ -33,13 +33,13 @@ export function flattenObject(obj: Translation): TranslationFlatObject { // Check for when the object is empty but a key exists, so that // it defaults to an empty object if (isEmpty && key) { - result[key] = {} as TranslationBaseValue; + result[key] = ''; } } }; recursive(obj, ''); - return result; + return result as TranslationFlatObject; } export default { diff --git a/src/languages/types.ts b/src/languages/types.ts index dff6488312e7..124a67d05ad7 100644 --- a/src/languages/types.ts +++ b/src/languages/types.ts @@ -1,3 +1,5 @@ +import en from './en'; + type AddressLineParams = { lineNumber: number; }; @@ -190,16 +192,40 @@ 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 TranslationBaseValue = string | string[] | ((...args: any[]) => string); type Translation = {[key: string]: TranslationBaseValue | Translation}; -type TranslationFlatObject = Record; +/* 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 + [K in keyof T]: T[K] extends (...args: any[]) => any + ? `${Prefix}${K & string}` + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + T[K] extends any[] + ? `${Prefix}${K & string}` + : // eslint-disable-next-line @typescript-eslint/ban-types + T[K] extends object + ? FlattenObject + : `${Prefix}${K & string}`; +}[keyof T]; + +// Retrieves a type for a given key path (calculated from the type above) +type TranslateType = Path extends keyof T ? T[Path] : Path extends `${infer K}.${infer Rest}` ? (K extends keyof T ? TranslateType : never) : never; + +type TranslationsType = typeof en; + +type TranslationPaths = FlattenObject; + +type TranslationFlatObject = { + [K in TranslationPaths]: TranslateType; +}; export type { Translation, - TranslationBaseValue, TranslationFlatObject, AddressLineParams, CharacterLimitParams, From 2931a451afb74738bc172868e97f8da9c596019c Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Tue, 12 Sep 2023 17:15:11 +0100 Subject: [PATCH 14/15] refactor: rename generics --- src/languages/types.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/languages/types.ts b/src/languages/types.ts index 124a67d05ad7..d0482bea8bfd 100644 --- a/src/languages/types.ts +++ b/src/languages/types.ts @@ -200,28 +200,28 @@ 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 = { +type FlattenObject = { // eslint-disable-next-line @typescript-eslint/no-explicit-any - [K in keyof T]: T[K] extends (...args: any[]) => any - ? `${Prefix}${K & string}` + [TKey in keyof TObject]: TObject[TKey] extends (...args: any[]) => any + ? `${TPrefix}${TKey & string}` : // eslint-disable-next-line @typescript-eslint/no-explicit-any - T[K] extends any[] - ? `${Prefix}${K & string}` + TObject[TKey] extends any[] + ? `${TPrefix}${TKey & string}` : // eslint-disable-next-line @typescript-eslint/ban-types - T[K] extends object - ? FlattenObject - : `${Prefix}${K & string}`; -}[keyof T]; + 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 = Path extends keyof T ? T[Path] : Path extends `${infer K}.${infer Rest}` ? (K extends keyof T ? TranslateType : never) : never; +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 = { - [K in TranslationPaths]: TranslateType; + [TKey in TranslationPaths]: TranslateType; }; export type { From 8f8420afe666c5838a0c061caaf94f097196b13a Mon Sep 17 00:00:00 2001 From: Ana Margarida Silva Date: Tue, 12 Sep 2023 17:52:18 +0100 Subject: [PATCH 15/15] style: prettier --- src/languages/types.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/languages/types.ts b/src/languages/types.ts index d0482bea8bfd..17c5e1f1a07c 100644 --- a/src/languages/types.ts +++ b/src/languages/types.ts @@ -214,7 +214,13 @@ type FlattenObject = { }[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 TranslateType = TPath extends keyof TObject + ? TObject[TPath] + : TPath extends `${infer TKey}.${infer TRest}` + ? TKey extends keyof TObject + ? TranslateType + : never + : never; type TranslationsType = typeof en;