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 translation module for labels #11

Merged
merged 3 commits into from
Feb 10, 2025

Conversation

IAM5K
Copy link
Contributor

@IAM5K IAM5K commented Feb 7, 2025

OsmosysForm PR Checklist

Pre-requisites

  • I have gone through the Contributing guidelines for Submitting a Pull Request (PR) and ensured that this is not a duplicate PR.
  • I have performed preliminary testing to ensure that any existing features are not impacted and any new features are working as expected.
  • I have tested the library in a demo Angular application to verify functionality and integration.

PR Details

PR details have been updated as per the given format (see below)

  • PR title adheres to the format specified in guidelines (e.g., feat: add dynamic form validation).
  • Description has been added.
  • Related changes have been added (optional).
  • Screenshots have been added (optional).
  • Pending actions have been added (optional).
  • Any other additional notes have been added (optional).

Additional Information

  • Appropriate label(s) have been added (ready for review should be added if the PR is ready to be reviewed).
  • Assignee(s) and reviewer(s) have been added (optional).

Development Specific

  • Unit Tests: Relevant unit tests have been added or updated, and all tests pass (run ng test) (optional).
  • Library Build: Run ng build osmosys-form to ensure the library builds without errors.
  • Demo Application Testing: The new feature or fix has been tested within a demo application to ensure proper functionality and integration.
  • Documentation: Relevant documentation has been updated, including the README and any inline comments.
  • Version Bump: The version number has been incremented following semantic versioning guidelines if necessary.

Description:

This PR introduces robust translation support to the osmosys-forms component, allowing seamless integration of multilingual capabilities within user applications. The implementation leverages the ngx-translate language service to dynamically translate field labels, placeholders, and validation error messages based on the user's selected language.

Related changes:

  • Added the ngx-translate module to the osmosys-forms project to handle translation services.
  • Developed a helper function that utilizes the ngx-translate service to translate UI elements such as labels, placeholders, and validation messages when translation is enabled and available.
  • Refactored relevant components to utilize the translation helper function, replacing hardcoded text with dynamic translation keys.
  • Added a new useTranslation flag to the osmosys-forms component, giving users the flexibility to enable or disable translation based on their needs.

Screenshots:
image

Pending actions:

  • Add a list of any pending actions that have or would require to be done in this PR.
    Usage guide:

  • Users must have translation support set up in their application where they are using the osmosys-forms component. This includes configuring the ngx-translate service and defining translation files with appropriate keys and values.

  • Users can enable translation by passing the useTranslation flag as true and providing the translation service to the osmosys-forms component.

<osmosys-form [useTranslation]="true" [translateService]="translate">
  • Users should include all necessary translation keys and values in their translation files. These keys will be passed in the JSON schema used to generate the forms.
  • If translation is not required (useTranslation=false), the labels, placeholders, and validation messages will display exactly as provided in the JSON schema.
  • If translation is enabled but the JSON schema contains plain text instead of a translation key, the plain text will be displayed on the UI.

Additional notes:

  • Modified the existing placeholder logic. If a user hasn't provided a placeholder, that will appear blank.

Related issues:
close #7


Summary by CodeRabbit

  • New Features
    • Introduced enhanced internationalization for the form by enabling translations for labels, placeholders, and validation messages across various input elements.
    • Added optional functionality to activate translation based on user language preferences, ensuring a more adaptable and localized user experience.
    • Integrated a new dependency to support translation services.

Copy link

coderabbitai bot commented Feb 7, 2025

Walkthrough

This pull request adds translation support to the osmosys-form component. It introduces the "@ngx-translate/core" dependency in package.json. The HTML template is updated to wrap user-facing texts (labels, placeholders, validation messages, and options) with translation function calls. In the TypeScript file, two new input properties (useTranslation and translateService) and a new translate(key: string) method are added to conditionally apply translations based on user configuration.

Changes

Files Change Summary
package.json Added dependency "@ngx-translate/core": "^15.0.0".
projects/.../osmosys-form.component.html Wrapped form element texts (labels, placeholders, validation messages, and option labels) with calls to a translation function.
projects/.../osmosys-form.component.ts Introduced new input properties (useTranslation, translateService) and added a new translate(key: string) method to conditionally return translated values.

Assessment against linked issues

Objective Addressed Explanation
Add translation support using ngx-translate (#7)

Possibly related PRs

  • feat: add event handlers #10: Updates to component.ts and component.html for dynamic events and input handling relate directly to the translation functionality changes.

Suggested reviewers

  • xixas

Poem

In a burrow deep in code, I hop with glee,
Translating every label for all to see.
With new inputs and methods shining bright,
I code in carrots and bytes day and night.
A merry rabbit’s tune in a digital delight!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6899efd and 336b3f6.

📒 Files selected for processing (1)
  • projects/osmosys-form/src/lib/osmosys-form.component.html (22 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • projects/osmosys-form/src/lib/osmosys-form.component.html

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.

@IAM5K IAM5K changed the title feat: add translation module fror labels feat: add translation module for labels Feb 7, 2025
Copy link

@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: 2

🔭 Outside diff range comments (1)
projects/osmosys-form/src/lib/osmosys-form.component.ts (1)

60-68: Add TranslateService validation in ngOnInit.

When translation is enabled, the component should validate that TranslateService is properly provided.

Add this validation to ngOnInit:

   ngOnInit(): void {
+    if (this.useTranslation && !this.translateService) {
+      console.error('TranslateService is required when useTranslation is enabled');
+    }
+
     this.formConfig = this.formJsonData || {};
 
     if (this.formConfig.layout?.rows) {
       this.createForm(this.formConfig.layout.rows);
     }
 
     this.formInstance.emit(this.form);
   }
🧹 Nitpick comments (3)
projects/osmosys-form/src/lib/osmosys-form.component.html (2)

39-39: Consider security implications of autocomplete attribute.

The autocomplete attribute has been added with a default of 'off' for all form elements. While this enhances security, it might affect user experience for non-sensitive fields.

Consider making the autocomplete value configurable through the form configuration:

-[autocomplete]="element.autocomplete || 'off'"
+[autocomplete]="element.autocomplete || element.type === 'password' ? 'off' : 'on'"

Also applies to: 75-75, 123-123, 163-163, 198-198, 233-233, 286-286, 327-327, 368-368, 409-409


39-39: Enhance autocomplete attributes with semantic values.

While setting autocomplete to 'off' by default is a good start, consider using semantic values for better user experience.

For example:

-[autocomplete]="element.autocomplete || 'off'"
+[autocomplete]="element.autocomplete || getDefaultAutocomplete(element.type, element.name)"

Add this helper method to the component:

private getDefaultAutocomplete(type: string, name: string): string {
  switch (type) {
    case 'input':
      if (name.includes('email')) return 'email';
      if (name.includes('phone')) return 'tel';
      if (name.includes('name')) return 'name';
      return 'off';
    case 'password':
      return 'new-password';
    default:
      return 'off';
  }
}

Also applies to: 75-75, 123-123, 163-163, 198-198, 233-233, 286-286, 327-327, 368-368, 409-409

projects/osmosys-form/src/lib/osmosys-form.component.ts (1)

188-200: Add type safety and null checks to the translate method.

While the implementation is functional, it could benefit from improved type safety and null handling.

Consider this enhanced implementation:

-  translate(key: string): string {
+  translate(key: string | null | undefined): string {
+    if (!key) {
+      console.warn('Translation key is empty');
+      return '';
+    }
+
     if (this.useTranslation && this.translateService) {
-      if (key) {
-        return this.translateService.instant(key) || key;
-      }
-
-      // eslint-disable-next-line no-console
-      console.warn(`Translation key is empty: ${key}`);
-      return ''; // Return an empty string if the key is invalid
+      const translated = this.translateService.instant(key);
+      return translated || key;
     }
 
     return key; // Return the key as fallback if translation is not used
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d447a16 and 12ba052.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • projects/osmosys-form/src/lib/osmosys-form.component.html (22 hunks)
  • projects/osmosys-form/src/lib/osmosys-form.component.ts (3 hunks)
🔇 Additional comments (4)
projects/osmosys-form/src/lib/osmosys-form.component.ts (3)

22-22: LGTM! The translation service integration looks good.

The implementation correctly imports TranslateService and adds input properties with appropriate defaults for backward compatibility.

Also applies to: 38-40


188-200: Consider adding unit tests for the translate method.

The translate method implementation looks good with proper null checks and fallback handling. However, it's missing unit tests to verify the behavior.

Would you like me to generate unit tests for the translate method to cover:

  • Translation with valid key
  • Translation with empty key
  • Translation when service is not provided
  • Translation when useTranslation is false

22-22: LGTM! Translation service integration looks good.

The TranslateService import and input properties are properly defined with good defaults for backward compatibility.

Also applies to: 38-40

package.json (1)

24-24: Verify compatibility between Angular 18 and ngx-translate 15.

The project uses Angular 18, but @ngx-translate/core is pinned to version 15. Let's verify if this version is compatible with Angular 18.

xixas
xixas previously approved these changes Feb 7, 2025
@xixas xixas merged commit 5274b72 into OsmosysSoftware:main Feb 10, 2025
2 checks passed
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.

2 participants