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

feat: add i18n extraction server and some i18n #379

Merged
merged 3 commits into from
Oct 7, 2024

Conversation

Kilerd
Copy link
Collaborator

@Kilerd Kilerd commented Oct 7, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new server script for managing translations.
    • Added a toggle for hiding closed accounts with internationalization support.
    • Enhanced localization with new entries in English and Chinese.
  • Bug Fixes

    • Improved error handling in the ErrorBox component.
  • Chores

    • Updated dependencies and added new development tools.
    • Configured pre-commit hooks for code formatting.

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

Walkthrough

The pull request introduces several changes to the frontend project, primarily focused on enhancing internationalization support and updating dependencies. A new server script is added, and various localization entries are introduced in English and Chinese. The package.json file is updated with new dependencies, including middleware and hooks for code formatting. Additionally, modifications to the ErrorBox component improve error handling, while the i18n configuration is refined for better translation management.

Changes

File Change Summary
frontend/package.json - Added script: "i18n-server": "node src/server.js"
- Updated dependency: "react-i18next": "^14.1.1" → "^15.0.2"
- Added new dependencies: "translation-check": "^1.1.0", "body-parser": "^1.20.3", "cors": "^2.8.5", "express": "^4.21.0", "i18next-http-middleware": "^3.6.0"
- Added husky configuration for pre-commit hook.
frontend/public/locales/en/translation.json - Added entry: "hide_closed_accounts": "Hide closed accounts"
frontend/public/locales/zh/translation.json - Added multiple new keys for localization, including translations for transactions and account visibility.
frontend/src/components/ErrorBox.tsx - Modified rendering logic to improve error handling for undefined error types.
frontend/src/i18n.ts - Changed fallbackLng to false, added saveMissing, and expanded backend configuration for translation management.
frontend/src/pages/Accounts.tsx - Changed switch label from hardcoded string to translatable string using t function.
frontend/src/server.js - Introduced a new Express server with a POST endpoint for adding translation entries.

Possibly related PRs

🐇 In the meadow, hops a little hare,
With scripts and translations, we show we care.
From English to Chinese, we spread the cheer,
Enhancing our project, the path is clear!
So let’s code with joy, and never despair,
For every new feature, we’ll always prepare! 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3815dd1 and a549c50.

⛔ Files ignored due to path filters (1)
  • frontend/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • frontend/package.json (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/package.json

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Kilerd
Copy link
Collaborator Author

Kilerd commented Oct 7, 2024

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (10)
frontend/public/locales/zh/translation.json (1)

42-46: LGTM: Transaction-related translations are accurate and well-structured.

The new translations for transaction-related UI elements are clear and consistent with common Chinese UI terminology. They accurately convey the meaning of their English counterparts.

For consistency with other dialog-related translations in the file, consider changing "NEW_TRANSACTION_DIALOG_TITLE" to "NEW_TRANSACTION_MODAL_TITLE". This aligns with the naming convention used for other modal-related keys (e.g., "TRANSACTION_PREVIEW_MODAL_TITLE").

frontend/public/locales/en/translation.json (2)

55-57: LGTM! Consider adding a period for consistency.

The addition of the "hide_closed_accounts" entry is well-structured and clear. It enhances the functionality for managing account visibility in the UI.

For consistency with other similar entries in the file, consider adding a period at the end of the value:

 "accounts": {
-  "hide_closed_accounts": "Hide closed accounts"
+  "hide_closed_accounts": "Hide closed accounts."
 }

Line range hint 1-57: Consider improving consistency and completeness of translations.

While the file is well-structured, there are a few suggestions for improvement:

  1. Punctuation consistency: Some entries end with a period, while others don't. Consider standardizing this across all entries.

  2. Common UI elements: The file seems to be missing translations for some common UI elements. Consider adding translations for:

    • "Yes"
    • "No"
    • "OK"
    • "Cancel" (there's a specific "NEW_TRANSACTION_CANCEL", but a generic one might be useful)
  3. Grouping: Consider grouping related items under nested objects for better organization. For example, group all navigation-related items under a "nav" object.

Would you like assistance in implementing these suggestions?

frontend/package.json (1)

12-13: LGTM! Consider using double quotes for consistency.

The changes to the scripts section look good. The addition of the "i18n-server" script aligns with the PR's objective of adding i18n extraction capabilities.

For consistency with other scripts in this file, consider using double quotes instead of single quotes in the "prettier:fix" script:

-    "prettier:fix": "prettier --write 'src/**/*.{js,jsx,ts,tsx,json,css,scss,md}'",
+    "prettier:fix": "prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,scss,md}\"",
frontend/src/pages/Accounts.tsx (2)

71-71: Excellent internationalization improvement!

The change from a hardcoded string to a translatable one using the t function is a great step towards better internationalization support. This allows for easy translation of the "Hide closed accounts" label into different languages.

Consider using a more specific key for this translation. Instead of 'accounts.hide_closed_accounts', you might want to use something like 'accounts.toggle_label.hide_closed_accounts'. This can help organize translations better, especially as the project grows.

-              {t('accounts.hide_closed_accounts')}
+              {t('accounts.toggle_label.hide_closed_accounts')}

Line range hint 1-101: Suggestions for component improvements

While the component functions well, here are some suggestions to enhance its structure and maintainability:

  1. Consider extracting the account filtering logic into a custom hook or utility function. This would improve readability and make the logic reusable across other components if needed.

  2. The component uses a mix of Mantine hooks and custom UI components. For consistency, consider standardizing on one set of UI components throughout the application.

  3. The refreshAccounts function is called directly in the onClick handler. For larger applications, it's often beneficial to wrap such calls in useCallback to prevent unnecessary re-renders and improve performance.

Here's an example of how you could implement these suggestions:

// In a new file, e.g., useAccountFiltering.ts
import { useState, useMemo } from 'react';
import { AccountStatus } from '../rest-model';
import AccountTrie from '../utils/AccountTrie';

export function useAccountFiltering(accounts, hideClosedAccount, filterKeyword) {
  return useMemo(() => {
    let trie = new AccountTrie();
    for (let account of accounts.filter((it) => (hideClosedAccount ? it.status === AccountStatus.Open : true))) {
      let trimmedKeyword = filterKeyword.trim().toLowerCase();
      if (trimmedKeyword === '' || 
          account.name.toLowerCase().includes(trimmedKeyword) ||
          (account.alias?.toLowerCase() ?? '').includes(trimmedKeyword)) {
        trie.insert(account);
      }
    }
    return trie;
  }, [accounts, hideClosedAccount, filterKeyword]);
}

// In Accounts.tsx
import { useCallback } from 'react';
import { useAccountFiltering } from './useAccountFiltering';

export default function Accounts() {
  // ... other code ...

  const accounts = useAtomValue(accountAtom);
  const accountTrie = useAccountFiltering(accounts, hideClosedAccount, filterKeyword);

  const refreshAccountsCallback = useCallback(() => refreshAccounts(), [refreshAccounts]);

  // ... rest of the component ...

  return (
    // ... other JSX ...
    <Button variant="outline" onClick={refreshAccountsCallback}>
      {t('REFRESH')}
    </Button>
    // ... other JSX ...
  );
}

These changes would make the component more modular, consistent, and potentially more performant.

frontend/src/components/ErrorBox.tsx (2)

57-57: Approve the change with a minor suggestion for improvement.

The modification enhances the robustness of the error type rendering by handling the case where selectError?.error_type is undefined. This prevents potential runtime errors and improves the component's reliability.

For improved readability, consider using a nullish coalescing operator:

-<p>{selectError?.error_type === undefined ? '' : t(`ERROR.${selectError.error_type}`)}</p>
+<p>{t(`ERROR.${selectError?.error_type ?? ''}`)}</p>

This change maintains the same functionality while making the code more concise and easier to read.


Line range hint 44-51: Address commented-out code in saveErrorModifyData

The saveErrorModifyData function contains commented-out code that appears to be related to modifying a file. This might indicate incomplete functionality or outdated code.

Consider one of the following actions:

  1. If the functionality is needed, implement it and remove the comments.
  2. If the functionality is no longer required, remove the commented-out code entirely.
  3. If the functionality is planned for future implementation, add a TODO comment explaining the plan and timeline.

Keeping the codebase clean of unused commented code improves maintainability and reduces confusion for other developers.

frontend/src/server.js (2)

35-48: Handle concurrent write operations to prevent data corruption

Multiple clients might attempt to write to the same translation file simultaneously, leading to race conditions and potential data loss or corruption.

Consider implementing file write queuing, locks, or using asynchronous file operations with proper concurrency control to handle simultaneous write requests. Alternatively, using a database or a dedicated key-value store like Redis could help manage concurrent access more effectively.


16-18: Consolidate logging statements for clarity

The logs at lines 16 and 18 both print the contents of req.body with messages about missing and inserting translations. Since both log statements output the same data, consider consolidating them or differentiating their purposes more clearly.

For example:

-  console.log(`Missing translations for ${req.params.lng}/${req.params.ns}:`, req.body);
 ...
-  console.log(`inserting translations for ${req.params.lng}/${req.params.ns}:`, req.body);
+  console.log(`Processing translations for ${req.params.lng}/${req.params.ns}:`, req.body);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b4e1332 and 3815dd1.

⛔ Files ignored due to path filters (1)
  • frontend/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • frontend/package.json (4 hunks)
  • frontend/public/locales/en/translation.json (1 hunks)
  • frontend/public/locales/zh/translation.json (1 hunks)
  • frontend/src/components/ErrorBox.tsx (1 hunks)
  • frontend/src/i18n.ts (1 hunks)
  • frontend/src/pages/Accounts.tsx (1 hunks)
  • frontend/src/server.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (9)
frontend/src/i18n.ts (3)

4-4: LGTM: Improved code readability

The addition of an empty line after the import statements improves code readability by clearly separating the imports from the rest of the code.


Line range hint 1-35: Summary of i18n configuration changes

The changes to the i18n configuration in this file are generally positive, enhancing the internationalization capabilities of the application. Key points from the review:

  1. Improved code readability with better spacing.
  2. Changed fallbackLng behavior, which needs verification to ensure it doesn't negatively impact user experience.
  3. Added saveMissing option, which is good for development purposes.
  4. Introduced backend configuration, which is a step in the right direction but may need refinement for better portability across environments.

Please address the suggestions in the previous comments, particularly regarding the use of environment variables for the backend URL. This will make the configuration more flexible and easier to manage across different environments.


12-13: Verify the impact of fallbackLng change and consider saveMissing implications

The changes to the i18n configuration have significant implications:

  1. Setting fallbackLng: false means no fallback language will be used when a translation is missing. This could lead to blank spots or keys being displayed instead of translated text in the UI. Ensure this is the intended behavior and that all necessary translations are in place.

  2. The saveMissing: isDevelopment option is a good practice. It allows saving missing translation keys in development, which can help identify missing translations, but prevents this in production.

To ensure all necessary translations are in place, run the following script:

This script will help identify any missing translations across all locale files.

✅ Verification successful

Re-attempting to verify missing translations with updated search parameters

The previous script failed to locate the locales directory. Let's search the entire repository for JSON files that may contain translation keys.


All translations are complete; fallbackLng set to false is safe

The verification shows that there are no missing translations in the locale files:

  • frontend/public/locales/en/translation.json
  • frontend/public/locales/zh/translation.json

Therefore, setting fallbackLng: false will not result in untranslated keys being displayed in the UI. Additionally, the saveMissing: isDevelopment configuration ensures that any future missing translations are tracked during development.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for missing translations in all locale files

# Find all locale JSON files
locale_files=$(fd -e json . locales)

# Loop through each file and check for empty string values
for file in $locale_files; do
  echo "Checking $file for missing translations:"
  jq -r 'paths as $p | select(getpath($p) == "") | $p | join(".")' "$file"
  echo "---"
done

Length of output: 134


Script:

#!/bin/bash
# Description: Locate all potential locale JSON files and check for missing translations

# Find all JSON files that likely contain locale translations
locale_files=$(fd -e json .)

# Filter files that are likely to be locale files based on common naming conventions
locale_files=$(echo "$locale_files" | grep -E '/(locales|i18n|translations)/|/en\.json$|/fr\.json$|/es\.json$')

if [ -z "$locale_files" ]; then
  echo "No locale JSON files found."
  exit 1
fi

# Loop through each locale file and check for empty string values
for file in $locale_files; do
  echo "Checking $file for missing translations:"
  jq -r 'paths as $p | select(getpath($p) == "") | $p | join(".")' "$file"
  echo "---"
done

Length of output: 5664

frontend/public/locales/zh/translation.json (3)

38-41: LGTM: New translations are consistent and clear.

The new translations for ledger health status and account visibility options are well-structured and consistent with the existing translations. They provide clear Chinese equivalents for the English phrases.


53-54: LGTM: Transaction edit modal translations are accurate and complete the UI set.

The new translations for the transaction edit modal description and title are clear, consistent with the existing style, and accurately convey the intended meanings in Chinese. These additions complete the set of UI elements for comprehensive transaction management.


38-54: Overall: Excellent additions to Chinese localization

The new translations added in this file significantly enhance the internationalization support for Chinese users. They provide clear and accurate translations for new UI elements related to transaction management, account visibility, and journal operations. The additions are well-structured, consistent with existing translations, and maintain the established JSON format.

A few minor suggestions have been made for naming consistency, but overall, these changes greatly improve the user experience for Chinese-speaking users of the application.

frontend/package.json (3)

94-94: LGTM! Improved formatting.

The addition of a trailing comma after the last devDependency is a good practice. It improves consistency and makes future additions to the list easier and cleaner in version control diffs.


74-75: Verify the necessity of new server-related devDependencies.

The addition of new devDependencies (body-parser, cors, express, i18next-http-middleware) aligns with the PR's objective of adding an i18n extraction server. However:

  1. Consider if these server-related packages should be regular dependencies instead of devDependencies, especially if they're used in the i18n-server script.
  2. Ensure that the i18n extraction server is only used during development and not in production.

Please run the following script to check the usage of these new dependencies:

#!/bin/bash
# Description: Check usage of new server-related dependencies

# Test: Search for usage of new dependencies in the codebase
echo "Searching for usage of new dependencies:"
rg --type typescript --type javascript 'from [\'"]express[\'"]|from [\'"]body-parser[\'"]|from [\'"]cors[\'"]|from [\'"]i18next-http-middleware[\'"]' -A 5

# Note: Review the output to ensure these dependencies are used appropriately and only in development contexts.

Also applies to: 80-80, 83-83


48-48: Verify compatibility with the updated react-i18next version.

The dependency updates look good and align with the PR's i18n focus. However, please note:

  1. The update to react-i18next (^15.0.2) is a major version bump from the previous ^14.1.1. This may introduce breaking changes.
  2. The new "translation-check" dependency is a welcome addition for i18n support.

Please run the following script to check for any breaking changes in the react-i18next update:

Also applies to: 56-56

frontend/src/i18n.ts Show resolved Hide resolved
frontend/public/locales/zh/translation.json Show resolved Hide resolved
frontend/package.json Outdated Show resolved Hide resolved
frontend/src/server.js Show resolved Hide resolved
frontend/src/server.js Show resolved Hide resolved
frontend/src/server.js Show resolved Hide resolved
@Kilerd
Copy link
Collaborator Author

Kilerd commented Oct 7, 2024

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Kilerd Kilerd merged commit 2b1f0d9 into main Oct 7, 2024
24 checks passed
@Kilerd Kilerd deleted the fix/i18n-auto-extraction branch October 7, 2024 08:22
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.

1 participant