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

added i18n support for plugins #10182

Merged
merged 3 commits into from
Jan 27, 2025
Merged

added i18n support for plugins #10182

merged 3 commits into from
Jan 27, 2025

Conversation

khavinshankar
Copy link
Member

@khavinshankar khavinshankar commented Jan 25, 2025

Proposed Changes

  • Added support for i18n for plugins

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced internationalization (i18n) support with dynamic translation resource loading
    • Improved app configuration with more detailed app name extraction
  • Dependencies

    • Added i18next-resources-to-backend package
    • Updated @types/node to latest version
  • Improvements

    • Refined translation resource handling
    • Added default namespace for translations
    • Implemented more robust URL generation for translation files
  • Localization Updates

    • Removed multiple entries related to the ABHA feature from localization files, streamlining the application’s language support.

@khavinshankar khavinshankar requested a review from a team as a code owner January 25, 2025 11:09
Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

Walkthrough

The pull request modifies the careApps property in the careConfig object within care.config.ts, enhancing the parsing logic for app configurations. It introduces error handling for org and repo values and constructs URLs based on the presence of a CDN. The package.json file sees the addition of a new dependency and an update to an existing one. The src/i18n.ts file is updated to improve dynamic translation resource handling, including a new function for URL generation and enhanced error management. Several keys related to the ABHA system are removed from the localization file.

Changes

File Change Summary
care.config.ts Enhanced careApps parsing logic with error handling and URL construction.
package.json - Added i18next-resources-to-backend@1.2.1 dependency
- Updated @types/node from ^22.9.0 to ^22.10.10
src/i18n.ts - Added namespaceToUrl function
- Updated i18n.init() for dynamic loading and namespace management
public/locale/en.json Removed multiple entries related to the ABHA feature.

Possibly related PRs

Suggested labels

tested, needs review

Suggested reviewers

  • rithviknishad

Poem

🐰 In the garden of code, where changes bloom,
CareApps now flourish, dispelling the gloom.
URLs crafted with care, translations take flight,
ABHA's whispers fade into the night.
Hopping through updates, we celebrate cheer,
With each little change, our vision is clear! 🌼

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

Copy link

netlify bot commented Jan 25, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit a5b3417
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67972fcd4f8eef0008b1dec8
😎 Deploy Preview https://deploy-preview-10182--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

cloudflare-workers-and-pages bot commented Jan 25, 2025

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: a5b3417
Status: ✅  Deploy successful!
Preview URL: https://ee505838.care-fe.pages.dev
Branch Preview URL: https://plugs-i18n.care-fe.pages.dev

View logs

Copy link

cypress bot commented Jan 25, 2025

CARE    Run #4424

Run Properties:  status check passed Passed #4424  •  git commit a5b34178bd: added i18n support for plugins
Project CARE
Branch Review plugs-i18n
Run status status check passed Passed #4424
Run duration 02m 56s
Commit git commit a5b34178bd: added i18n support for plugins
Committer Khavin Shankar
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 5
View all changes introduced in this branch ↗︎

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: 1

🧹 Nitpick comments (3)
src/i18n.ts (2)

17-27: Consider validating or defaulting empty input
If input is empty or whitespace only, the function returns "https://"—which may fail later. A fallback or validation for an empty string can help avoid such errors.


43-63: Optionally provide a fallback for missing translations
If translation fetch fails, the callback passes an error, causing the i18n load to break. Returning an empty object can keep the UI partially functional rather than halting.

Possible fallback approach:

 .catch((error) => {
   console.error(
     `Failed to load translations for ${language}/${namespace}:`,
     error,
   );
-  callback(error, null);
+  callback(null, {});
 });
care.config.ts (1)

124-124: Safeguard against invalid string patterns
Splitting the string twice may fail if the app name doesn't follow organization/app@branch. Consider a fallback or error handling if a slash is missing.

- name: app.split("@")[0].split("/")[1],
+ const [org, appName] = app.split("@")[0].split("/");
+ name: appName || org,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 131111f and dd280b2.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • care.config.ts (1 hunks)
  • package.json (2 hunks)
  • src/i18n.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (6)
src/i18n.ts (4)

1-1: No issues with this import
Essential import for referencing the careConfig.


5-5: No issues with the new dependency import
The resourcesToBackend import is properly integrated and aligns with the i18n enhancement.


66-66: Dynamic namespaces are well implemented
Adding ...careConfig.careApps.map(app => app.name) ensures robust multi-app translation support.


73-73: Default namespace choice looks good
Setting defaultNS to "care_fe" is consistent with your existing codebase.

package.json (2)

103-103: New i18n resource dependency
Good addition for enabling dynamic resource loading.


142-142: Incremental type definition update
Updating @types/node to ^22.10.10 is generally safe.

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: 1

🧹 Nitpick comments (2)
src/i18n.ts (2)

25-45: Enhance resource loading resilience.

While the error handling is good, consider these improvements for production readiness:

  1. Add retry mechanism for failed requests
  2. Implement caching strategy
  3. Add request timeout
  4. Handle partial translation data

Here's a suggested implementation:

  .use(
    resourcesToBackend((language, namespace, callback) => {
+     const controller = new AbortController();
+     const timeoutId = setTimeout(() => controller.abort(), 5000);
+     
+     const retryFetch = (retries = 3) =>
      fetch(`${namespaceToUrl(namespace)}/locale/${language}.json`, {
+       signal: controller.signal,
+       cache: 'default'
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then((resources) => {
+         clearTimeout(timeoutId);
+         // Validate required translation keys
+         if (!resources || typeof resources !== 'object') {
+           throw new Error('Invalid translation data');
+         }
          callback(null, resources);
        })
        .catch((error) => {
+         if (retries > 0 && error.name !== 'AbortError') {
+           return retryFetch(retries - 1);
+         }
          console.error(
            `Failed to load translations for ${language}/${namespace}:`,
            error,
          );
          callback(error, null);
        });
+     
+     retryFetch();
    }),
  )

46-55: Consider additional i18n options for production use.

The current configuration is good, but consider these additional options for better production performance:

  .init({
    fallbackLng: "en",
    ns: ["care_fe", ...careConfig.careApps.map((app) => app.name)],
    load: "currentOnly",
    supportedLngs: Object.keys(LANGUAGES),
    interpolation: {
      escapeValue: false,
      skipOnVariables: false,
    },
    defaultNS: "care_fe",
+   // Performance optimizations
+   partialBundledLanguages: true,
+   nonExplicitSupportedLngs: false,
+   // Debug options for non-production environments
+   debug: process.env.NODE_ENV !== 'production',
  });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd280b2 and a5b3417.

📒 Files selected for processing (3)
  • care.config.ts (1 hunks)
  • public/locale/en.json (0 hunks)
  • src/i18n.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • public/locale/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • care.config.ts
🔇 Additional comments (2)
src/i18n.ts (2)

1-5: LGTM! Clean import structure.

The imports are well-organized and include all necessary dependencies for i18n functionality.


27-27: Verify URL construction in careConfig.

The code now uses pre-constructed URLs instead of building them from individual components, which should address the previous branch-related issues. However, let's verify the URL construction in careConfig.

✅ Verification successful

URL construction in careConfig is properly implemented

The URL construction in careConfig is robust and secure, with proper validation, protocol handling, and error checking. The code correctly handles both GitHub Pages and custom CDN URLs, with appropriate fallbacks and error handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify URL construction in careConfig

# Check URL construction logic
rg -A 10 'careApps.*url'

# Check for any remaining branch usage
rg 'careApp.*branch'

Length of output: 501


Script:

#!/bin/bash
# Search for careConfig definition and initialization
rg -A 5 "careConfig.*=" 

# Look for type definitions
ast-grep --pattern "interface CareApp {
  $$$
}"

# Check for any config files that might contain careConfig
fd -e json -e ts -e js config

Length of output: 1863


Script:

#!/bin/bash
# Get complete careConfig content
cat care.config.ts

# Look for type definitions in the codebase
ast-grep --pattern "type CareConfig = {
  $$$
}"

# Search for careApps related code
rg -A 5 "careApps.*=" 

Length of output: 5889

Comment on lines +17 to +19
const namespaceToUrl = (namespace: string) => {
return careConfig.careApps.find((app) => app.name === namespace)?.url ?? "";
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and type safety in namespaceToUrl.

The current implementation has several potential issues:

  1. Returning an empty string on failure could lead to silent failures
  2. No validation of the URL structure
  3. Missing type safety for namespace parameter

Consider this improved implementation:

-const namespaceToUrl = (namespace: string) => {
-  return careConfig.careApps.find((app) => app.name === namespace)?.url ?? "";
-};
+type ValidNamespace = typeof careConfig.careApps[number]['name'];
+
+const namespaceToUrl = (namespace: ValidNamespace): string => {
+  const app = careConfig.careApps.find((app) => app.name === namespace);
+  if (!app?.url) {
+    throw new Error(`Invalid namespace or missing URL: ${namespace}`);
+  }
+  return app.url;
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const namespaceToUrl = (namespace: string) => {
return careConfig.careApps.find((app) => app.name === namespace)?.url ?? "";
};
type ValidNamespace = typeof careConfig.careApps[number]['name'];
const namespaceToUrl = (namespace: ValidNamespace): string => {
const app = careConfig.careApps.find((app) => app.name === namespace);
if (!app?.url) {
throw new Error(`Invalid namespace or missing URL: ${namespace}`);
}
return app.url;
};

@gigincg gigincg merged commit a481488 into develop Jan 27, 2025
26 checks passed
@gigincg gigincg deleted the plugs-i18n branch January 27, 2025 13:08
Copy link

@khavinshankar Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

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

Successfully merging this pull request may close these issues.

3 participants