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

Improve translations - flatten translation objects #25846

Merged

Conversation

BeeMargarida
Copy link
Contributor

@BeeMargarida BeeMargarida commented Aug 24, 2023

Details

  • Flatten translation object
  • Unit tests for flatten function
  • Adapt Localize.translate to use this new object (remove lodashGet usages)
  • Adapt usages of translate object where they used the object instead of the translation strings

Performance improvement of ±50%.

Before After
keyboardShortcutModal.title: 0.09912109375 ms
keyboardShortcutModal.subtitle: 0.01416015625 ms
reportActionContextMenu.deleteAction: 0.065185546875 ms
reportActionContextMenu.deleteConfirmation: 0.058837890625 ms
common.delete: 0.01904296875 ms
common.cancel: 0.009033203125 ms
reportActionContextMenu.copyToClipboard: 0.01318359375 ms
reportActionContextMenu.copied: 0.010009765625 ms
reportActionContextMenu.markAsUnread: 0.015869140625 ms
login.hero.header: 0.02001953125 ms
welcomeText.getStarted: 0.010009765625 ms
login.hero.header: 0.027099609375 ms
login.hero.body: 0.015869140625 ms
footer.features: 0.015869140625 ms
footer.resources: 0.00927734375 ms
footer.learnMore: 0.00927734375 ms
footer.getStarted: 0.0068359375 ms
footer.expenseManagement: 0.022216796875 ms
footer.spendManagement: 0.01220703125 ms
footer.expenseReports: 0.010009765625 ms
footer.companyCreditCard: 0.008056640625 ms
footer.receiptScanningApp: 0.0078125 ms
footer.billPay: 0.007080078125 ms
footer.invoicing: 0.02294921875 ms
footer.CPACard: 0.015869140625 ms
footer.payroll: 0.0078125 ms
footer.travel: 0.02490234375 ms
footer.expensifyApproved: 0.010009765625 ms
footer.pressKit: 0.00927734375 ms
footer.support: 0.0068359375 ms
footer.expensifyHelp: 0.0068359375 ms
footer.community: 0.01416015625 ms
footer.privacy: 0.009033203125 ms
footer.aboutExpensify: 0.00927734375 ms
footer.blog: 0.0078125 ms
footer.jobs: 0.00927734375 ms
footer.expensifyOrg: 0.0078125 ms
footer.investorRelations: 0.007080078125 ms
footer.createAccount: 0.010009765625 ms
footer.logIn: 0.00830078125 ms
termsOfUse.phrase5: 0.008056640625 ms
termsOfUse.phrase6: 0.0068359375 ms
languagePage.languages: 0.008056640625 ms
DownloadAppModal.downloadTheApp: 0.041015625 ms
DownloadAppModal.keepTheConversationGoing: 0.010009765625 ms
common.download: 0.010009765625 ms
DownloadAppModal.noThanks: 0.008056640625 ms
loginForm.loginForm: 0.02685546875 ms
loginForm.phoneOrEmail: 0.008056640625 ms
loginForm.phoneOrEmail: 0.006103515625 ms
common.continue: 0.0087890625 ms
common.please: 0.019775390625 ms
common.fixTheErrors: 0.0078125 ms
common.inTheFormBeforeContinuing: 0.010009765625 ms
login.hero.header: 0.01708984375 ms
welcomeText.getStarted: 0.011962890625 ms
loginForm.loginForm: 0.017822265625 ms
loginForm.phoneOrEmail: 0.0068359375 ms
loginForm.phoneOrEmail: 0.004150390625 ms
common.continue: 0.00634765625 ms
common.please: 0.02490234375 ms
common.fixTheErrors: 0.007080078125 ms
common.inTheFormBeforeContinuing: 0.007080078125 ms
login.hero.header: 0.025146484375 ms
login.hero.body: 0.005859375 ms
footer.features: 0.010986328125 ms
footer.resources: 0.0048828125 ms
footer.learnMore: 0.0048828125 ms
footer.getStarted: 0.004150390625 ms
footer.expenseManagement: 0.006103515625 ms
footer.spendManagement: 0.010009765625 ms
footer.expenseReports: 0.008056640625 ms
footer.companyCreditCard: 0.0068359375 ms
footer.receiptScanningApp: 0.004638671875 ms
footer.billPay: 0.006103515625 ms
footer.invoicing: 0.0048828125 ms
footer.CPACard: 0.02099609375 ms
footer.payroll: 0.01123046875 ms
footer.travel: 0.009765625 ms
footer.expensifyApproved: 0.010986328125 ms
footer.pressKit: 0.008056640625 ms
footer.support: 0.015869140625 ms
footer.expensifyHelp: 0.0048828125 ms
footer.community: 0.006103515625 ms
footer.privacy: 0.005126953125 ms
footer.aboutExpensify: 0.0048828125 ms
footer.blog: 0.0048828125 ms
footer.jobs: 0.00390625 ms
footer.expensifyOrg: 0.005126953125 ms
footer.investorRelations: 0.005126953125 ms
footer.createAccount: 0.006103515625 ms
footer.logIn: 0.00390625 ms
termsOfUse.phrase5: 0.005859375 ms
termsOfUse.phrase6: 0.00390625 ms
languagePage.languages: 0.005126953125 ms
loginForm.loginForm: 0.031005859375 ms
loginForm.phoneOrEmail: 0.0068359375 ms
loginForm.phoneOrEmail: 0.005126953125 ms
common.continue: 0.0048828125 ms
common.please: 0.013671875 ms
common.fixTheErrors: 0.005126953125 ms
common.inTheFormBeforeContinuing: 0.0048828125 ms
DownloadAppModal.downloadTheApp: 0.031982421875 ms
DownloadAppModal.keepTheConversationGoing: 0.010009765625 ms
common.download: 0.010986328125 ms
DownloadAppModal.noThanks: 0.005859375 ms
keyboardShortcutModal.title: 0.01416015625 ms
keyboardShortcutModal.subtitle: 0.02880859375 ms
keyboardShortcutModal.shortcuts.openShortcutDialog: 0.02197265625 ms
keyboardShortcutModal.title: 0.06103515625 ms
keyboardShortcutModal.subtitle: 0.005126953125 ms
reportActionContextMenu.deleteAction: 0.036865234375 ms
reportActionContextMenu.deleteConfirmation: 0.010986328125 ms
common.delete: 0.001708984375 ms
common.cancel: 0.000732421875 ms
reportActionContextMenu.copyToClipboard: 0.003173828125 ms
reportActionContextMenu.copied: 0.001953125 ms
reportActionContextMenu.markAsUnread: 0.0126953125 ms
login.hero.header: 0.011962890625 ms
welcomeText.getStarted: 0.001220703125 ms
login.hero.header: 0.011962890625 ms
login.hero.body: 0.002197265625 ms
footer.features: 0.006103515625 ms
footer.resources: 0.001953125 ms
footer.learnMore: 0.001953125 ms
footer.getStarted: 0.0009765625 ms
footer.expenseManagement: 0.0029296875 ms
footer.spendManagement: 0.0068359375 ms
footer.expenseReports: 0.005126953125 ms
footer.companyCreditCard: 0.004150390625 ms
footer.receiptScanningApp: 0.002685546875 ms
footer.billPay: 0.007080078125 ms
footer.invoicing: 0.010986328125 ms
footer.CPACard: 0.007080078125 ms
footer.payroll: 0.0029296875 ms
footer.travel: 0.003173828125 ms
footer.expensifyApproved: 0.0029296875 ms
footer.pressKit: 0.001953125 ms
footer.support: 0.001953125 ms
footer.expensifyHelp: 0.001953125 ms
footer.community: 0.0009765625 ms
footer.privacy: 0 ms
footer.aboutExpensify: 0.001220703125 ms
footer.blog: 0.001953125 ms
footer.jobs: 0.002197265625 ms
footer.expensifyOrg: 0.0009765625 ms
footer.investorRelations: 0.001708984375 ms
footer.createAccount: 0.0068359375 ms
footer.logIn: 0.001953125 ms
termsOfUse.phrase5: 0.001708984375 ms
termsOfUse.phrase6: 0.002197265625 ms
languagePage.languages.en.label: 0.002197265625 ms
languagePage.languages.es.label: 0.001953125 ms
DownloadAppModal.downloadTheApp: 0.008056640625 ms
DownloadAppModal.keepTheConversationGoing: 0.002197265625 ms
common.download: 0.000732421875 ms
DownloadAppModal.noThanks: 0.001708984375 ms
loginForm.loginForm: 0.004150390625 ms
loginForm.phoneOrEmail: 0.001953125 ms
loginForm.phoneOrEmail: 0.003173828125 ms
common.continue: 0.0078125 ms
common.please: 0.0078125 ms
common.fixTheErrors: 0.0009765625 ms
common.inTheFormBeforeContinuing: 0.001953125 ms
login.hero.header: 0.0078125 ms
welcomeText.getStarted: 0.002197265625 ms
loginForm.loginForm: 0.0068359375 ms
loginForm.phoneOrEmail: 0.0009765625 ms
loginForm.phoneOrEmail: 0.0009765625 ms
common.continue: 0.001220703125 ms
common.please: 0.007080078125 ms
common.fixTheErrors: 0.0009765625 ms
common.inTheFormBeforeContinuing: 0.002197265625 ms
login.hero.header: 0.01318359375 ms
login.hero.body: 0.009033203125 ms
footer.features: 0.003173828125 ms
footer.resources: 0.0009765625 ms
footer.learnMore: 0.0009765625 ms
footer.getStarted: 0.001953125 ms
footer.expenseManagement: 0.002197265625 ms
footer.spendManagement: 0.002197265625 ms
footer.expenseReports: 0.0009765625 ms
footer.companyCreditCard: 0 ms
footer.receiptScanningApp: 0.0009765625 ms
footer.billPay: 0.001953125 ms
footer.invoicing: 0.0009765625 ms
footer.CPACard: 0.001953125 ms
footer.payroll: 0.0009765625 ms
footer.travel: 0.002197265625 ms
footer.expensifyApproved: 0.001953125 ms
footer.pressKit: 0.000732421875 ms
footer.support: 0.0029296875 ms
footer.expensifyHelp: 0.002197265625 ms
footer.community: 0.001953125 ms
footer.privacy: 0.001953125 ms
footer.aboutExpensify: 0.0029296875 ms
footer.blog: 0.008056640625 ms
footer.jobs: 0.004150390625 ms
footer.expensifyOrg: 0.001953125 ms
footer.investorRelations: 0.0009765625 ms
footer.createAccount: 0.006103515625 ms
footer.logIn: 0.003173828125 ms
termsOfUse.phrase5: 0.001708984375 ms
termsOfUse.phrase6: 0 ms
languagePage.languages.en.label: 0.001953125 ms
languagePage.languages.es.label: 0.0009765625 ms
loginForm.loginForm: 0.010009765625 ms
loginForm.phoneOrEmail: 0.001953125 ms
loginForm.phoneOrEmail: 0.001953125 ms
common.continue: 0.00390625 ms
common.please: 0.010009765625 ms
common.fixTheErrors: 0.001220703125 ms
common.inTheFormBeforeContinuing: 0 ms
DownloadAppModal.downloadTheApp: 0.010009765625 ms
DownloadAppModal.keepTheConversationGoing: 0.0009765625 ms
common.download: 0.001220703125 ms
DownloadAppModal.noThanks: 0.001953125 ms
keyboardShortcutModal.title: 0.007080078125 ms
keyboardShortcutModal.subtitle: 0.0009765625 ms
keyboardShortcutModal.shortcuts.openShortcutDialog: 0.002197265625 ms

Fixed Issues

$ #25466

Tests

  1. Open app and check that the translations are working
  2. Change language and check that the translation are working
  3. Try to change pronouns and/or country
  4. Check that the translations are working and no error happens
  • Verify that no errors appear in the JS console

Offline tests

  1. Open app and check that the translations are working
  2. Change language and check that the translation are working
  3. Try to change pronouns and/or country
  4. Check that the translations are working and no error happens

QA Steps

  1. Open app and check that the translations are working
  2. Change language and check that the translation are working
  3. Try to change pronouns and/or country
  4. Check that the translations are working and no error happens
  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
    • MacOS / Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I verified the translation was requested/reviewed in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is approved by marketing by adding the Waiting for Copy label for a copy review on the original GH to get the correct copy.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(themeColors.componentBG))
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR author checklist, including those that don't apply to this PR.

Screenshots/Videos

Web
web_t.mp4
Mobile Web - Chrome
mchrome_t.mp4
Mobile Web - Safari
msafari_t.mp4
Desktop
desktop_t.mp4
iOS
ios_t.mp4
Android
android_t.mp4

@melvin-bot
Copy link

melvin-bot bot commented Aug 24, 2023

Hey! I see that you made changes to our Form component. Make sure to update the docs in FORMS.md accordingly. Cheers!

src/CONST.js Outdated Show resolved Hide resolved
src/CONST.js Outdated Show resolved Hide resolved
src/CONST.js Outdated Show resolved Hide resolved
@BeeMargarida BeeMargarida marked this pull request as ready for review September 4, 2023 10:13
@BeeMargarida BeeMargarida requested a review from a team as a code owner September 4, 2023 10:13
@melvin-bot melvin-bot bot requested review from narefyev91 and removed request for a team September 4, 2023 10:13
@melvin-bot
Copy link

melvin-bot bot commented Sep 4, 2023

@narefyev91 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@narefyev91
Copy link
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified tests pass on all platforms & I tested again on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
    • MacOS / Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is approved by marketing by adding the Waiting for Copy label for a copy review on the original GH to get the correct copy.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(themeColors.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Web
web3.mov
Mobile Web - Chrome
android-web3.mov
Mobile Web - Safari
ios-web3.mov
Desktop
desktop3.mov
iOS
ios3.mov
Android
android3.mov

Copy link
Contributor

@narefyev91 narefyev91 left a comment

Choose a reason for hiding this comment

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

LGTM!
🎀 👀 🎀 C+ reviewed

@melvin-bot melvin-bot bot requested a review from mountiny September 5, 2023 11:07
@mountiny mountiny changed the title #25466: improve translations - flatten translation objects [HOLD merge freeze] #25466: improve translations - flatten translation objects Sep 5, 2023
@BeeMargarida
Copy link
Contributor Author

BeeMargarida commented Sep 7, 2023

@narefyev91 @mountiny This might require another review, since I had to merge with main to fix conflicts and it forced me to port the new functions and translation object to typescript.

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

@blazejkustra blazejkustra Sep 11, 2023

Choose a reason for hiding this comment

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

TranslationFlatObject is way too generic (along with Translation & TranslationBaseValue types). The problem is that we lose type safety using flattenObject function:

const translations = flattenObject(en);
const text2 = translations.nonExistingKey; // TranslationFlatObject, meanwhile it's undefined in reality

This is a big problem as we should infer what keys are available to stay type safe when using Localize inside of components.

What we should do is to flatten the object in Typescript. Something like this (link):

type Join<K, P> = K extends string | number ? (P extends string | number ? `${K}${'' extends P ? '' : '.'}${P}` : never) : never;

type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...Array<0>];

type Leaves<T, D extends number = 10> = [D] extends [never] ? never : T extends object ? {[K in keyof T]-?: Join<K, Leaves<T[K], Prev[D]>>}[keyof T] : '';

declare function flattenObject<TTranslation extends Translation>(obj: TTranslation): Record<Leaves<TTranslation>, string | ...>;

const enFlattened = flattenObject2(en);

⚠️ These types might be quite slow, so be careful and test before using.

Copy link
Contributor

Choose a reason for hiding this comment

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

However this will be quite irritating to use inside of components as the value is not inferred and it's too generic: string | string[] | Function. So we would have to always check the types inside of components 😒

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually I had a similar problem in my side project, something like this could work here but the type is quite complicated ngl 😅 (this would have to be tested as I used it a little bit differentl in my project)

// Flatten object type
type FlattenObject<T> = CollapseEntries<CreateObjectEntries<T, T>>;

type Entry = {key: string; value: unknown};
type EmptyEntry<T> = {key: ''; value: T};

// Transforms entries to one flattened type
type CollapseEntries<T extends Entry> = {
    [E in T as E['key']]: E['value'];
} extends infer V
    ? {[K in keyof V]: V[K]}
    : never;

type CreateObjectEntries<T, I> = T extends infer U
    ? // Checks that U is an object
      U extends object
        ? {
              // Checks that Key is of type string
              [K in keyof U]-?: K extends string
                  ? // Nested key can be an object, run recursively to the bottom
                    CreateObjectEntries<U[K], I> extends infer E
                      ? E extends Entry
                          ? {
                                key: E['key'] extends '' ? K : `${K}.${E['key']}`;
                                value: E['value'];
                            }
                          : never
                      : never
                  : never;
          }[keyof U] // Builds entry for each key
        : EmptyEntry<U>
    : never;

declare function flattenObject2<TTranslation extends Translation>(obj: TTranslation): FlattenObject<TTranslation>;

const enFlattened = flattenObject2(es);

const type = enFlattened['common.websiteExample']; // string

Copy link
Contributor

Choose a reason for hiding this comment

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

Also cc @fabioh8010 as this is quite important to get right 😅

@mountiny
Copy link
Contributor

@BeeMargarida what do you think of the above, my types game is not that great yet 😂

@BeeMargarida
Copy link
Contributor Author

BeeMargarida commented Sep 11, 2023

@BeeMargarida what do you think of the above, my types game is not that great yet 😂

Currently working on this. My typing skills are not at this level 😬, but I'm trying to wrap my head around it and craft a solution for this.
Found a similar use case as well here and here, trying to see how can I combine both (links and comments above) to create robust translation typings.

@mountiny mountiny changed the title [HOLD merge freeze] #25466: improve translations - flatten translation objects Improve translations - flatten translation objects Sep 12, 2023
@BeeMargarida
Copy link
Contributor Author

@mountiny @blazejkustra Updated! Types for the flat object should now be more robust (thank you @fabioh8010 🙌).

@@ -190,7 +192,41 @@ 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);
Copy link
Contributor

Choose a reason for hiding this comment

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

@blazejkustra We need any[] here I think, I tried with unknown[] and every function starts failing.

src/languages/types.ts Outdated Show resolved Hide resolved
src/languages/types.ts Outdated Show resolved Hide resolved
src/languages/types.ts Outdated Show resolved Hide resolved
@BeeMargarida
Copy link
Contributor Author

Updated!

@narefyev91
Copy link
Contributor

@mountiny re-tested again - looking good!

Copy link
Contributor

@mountiny mountiny left a comment

Choose a reason for hiding this comment

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

Excited for this one, lets ship it

@mountiny mountiny merged commit 67f9f77 into Expensify:main Sep 13, 2023
13 checks passed
@OSBotify
Copy link
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify
Copy link
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 1.3.69-0 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 web 🕸 success ✅

@Pluto0104
Copy link
Contributor

@BeeMargarida @narefyev91 @mountiny I'm just curious, why do we need to flatten translation objects? maybe for performance?

@hotel1960
Copy link

👍

@BeeMargarida
Copy link
Contributor Author

PR to fix regressions: #27358

@OSBotify
Copy link
Contributor

🚀 Deployed to production by https://github.com/mountiny in version: 1.3.69-2 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 failure ❌
🕸 web 🕸 success ✅

@OSBotify
Copy link
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 1.3.70-0 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 web 🕸 success ✅

@OSBotify
Copy link
Contributor

🚀 Deployed to production by https://github.com/thienlnam in version: 1.3.70-8 🚀

platform result
🤖 android 🤖 failure ❌
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 failure ❌
🕸 web 🕸 success ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

10 participants