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

fix: dokan js translation loading #2377

Merged
merged 4 commits into from
Oct 16, 2024
Merged

fix: dokan js translation loading #2377

merged 4 commits into from
Oct 16, 2024

Conversation

osmansufy
Copy link
Contributor

@osmansufy osmansufy commented Sep 24, 2024

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Related Pull Request(s)

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Updated script dependencies to streamline localization under the WordPress internationalization framework.
    • Added a new dependency for improved internationalization support.
  • Bug Fixes

    • Removed unused script registration to enhance performance and reduce clutter.
  • Chores

    • Adjusted the order of dependencies in the package configuration for better organization.
    • Integrated default plugins into the webpack configuration for enhanced functionality.
    • Updated import statements to utilize the WordPress i18n library for localization functions.

@osmansufy osmansufy self-assigned this Sep 24, 2024
Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

Walkthrough

The pull request introduces significant changes focused on script dependencies and localization within the codebase. Key modifications include replacing the script dependency 'dokan-i18n-jed' with 'wp-i18n' in includes/Assets.php, adding a new dependency in package.json, and updating import statements in src/utils/Mixin.js. Additionally, the file src/utils/i18n.js has been removed, consolidating internationalization handling under the WordPress standards.

Changes

File Change Summary
includes/Assets.php Updated script dependencies, commented out unused script registration, and adjusted localization targets.
package.json Added new dependency @wordpress/i18n and rearranged the order of existing dependencies.
src/utils/Mixin.js Changed import source for internationalization functions from '@/utils/i18n' to '@wordpress/i18n'.
webpack.config.js Added spread operator to include defaultConfig.plugins in the updatedConfig.plugins array.
src/utils/i18n.js Removed file containing functions and variables related to internationalization using the Jed library.

Possibly related PRs

Suggested labels

QA approved, :+1: Dev Review Done, Upcoming Release

Suggested reviewers

  • shohag121

Poem

🐇 In the meadow where scripts play,
Dependencies dance and sway,
With wp-i18n in the lead,
Localization's now guaranteed!
Hopping forward, we refine,
A brighter code, oh how divine! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b1fd6a7 and d51a47a.

📒 Files selected for processing (1)
  • includes/Assets.php (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • includes/Assets.php

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.

@osmansufy osmansufy added In Progress The issues is being worked on Dependency With Pro labels Sep 24, 2024
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: 2

Outside diff range and nitpick comments (4)
src/utils/Mixin.js (1)

Line range hint 3-38: Consider refactoring the mixin for improved maintainability and testability.

While the import change is good, there are a few suggestions to further improve this file:

  1. The wrapper methods in the mixin (e.g., __, _nx, __n, sprintf) seem redundant as they simply call the imported functions without adding any functionality. Consider removing these methods and using the imported functions directly where needed in your components.

  2. The dateTimePickerFormat method relies on global variables (window.dokan_get_daterange_picker_format() and window.dokan_helper.daterange_picker_local). This could make the code harder to test and maintain. Consider refactoring this to use dependency injection or a configuration object passed to the mixin.

Here's a suggested refactoring:

import { setLocaleData, __, _x, __n, _nx, sprintf } from '@wordpress/i18n'

export default {
    methods: {
        setLocaleData,

        dateTimePickerFormat(config = {}) {
          return {
            format: (config.getDaterangePickerFormat || (() => '')).toLowerCase(),
            ...(config.daterangePickerLocal || {})
          }
        },
    }
}

Then, where you use this mixin, you can pass the necessary configuration:

mixins: [i18nMixin],
data() {
  return {
    i18nConfig: {
      getDaterangePickerFormat: window.dokan_get_daterange_picker_format,
      daterangePickerLocal: window.dokan_helper.daterange_picker_local
    }
  }
},
methods: {
  someMethod() {
    const format = this.dateTimePickerFormat(this.i18nConfig);
    // use format...
  }
}

This approach improves testability and makes the dependencies explicit.

package.json (1)

49-50: Minor: Dependencies reordered

The order of dependencies has been slightly modified. While this change doesn't affect functionality, it's worth noting that maintaining a consistent ordering (e.g., alphabetical) can improve readability and make future updates easier.

Consider adopting a consistent ordering strategy for all dependencies in the package.json file.

webpack.config.js (1)

Line range hint 1-168: Consider the following improvements to enhance the webpack configuration

While the current configuration is functional, there are a few areas where it could be improved:

  1. Module consistency: The file uses a mix of CommonJS (require) and ES6 (import) module systems. Consider standardizing to use ES6 imports throughout for better consistency.

  2. Code splitting: With multiple entry points, you might benefit from implementing code splitting to optimize bundle sizes. Consider using webpack's SplitChunksPlugin to extract common dependencies.

  3. Environment variables: Instead of using process.env.NODE_ENV directly, consider using webpack's DefinePlugin to define environment variables. This can help with better dead code elimination in production builds.

  4. Optimization: For production builds, consider adding optimization configurations such as minimization and tree shaking.

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

const { DefinePlugin } = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');

// ... (rest of the imports)

module.exports = (env, argv) => {
  const isProduction = argv.mode === 'production';

  return {
    // ... (rest of the config)

    optimization: {
      minimize: isProduction,
      minimizer: [new TerserPlugin()],
      splitChunks: {
        chunks: 'all',
      },
    },

    plugins: [
      ...defaultConfig.plugins,
      new DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(isProduction ? 'production' : 'development'),
      }),
      // ... (rest of the plugins)
    ],

    // ... (rest of the config)
  };
};

These changes would help optimize your build process and improve overall performance.

includes/Assets.php (1)

1086-1086: Approve addition of script translations.

The addition of wp_set_script_translations for each registered script is a positive change that enhances the plugin's internationalization capabilities. This ensures that all registered scripts can be properly translated.

Consider moving the text domain to a constant or class property for easier maintenance:

-            wp_set_script_translations( $handle, 'dokan-lite' );
+            wp_set_script_translations( $handle, self::TEXT_DOMAIN );

Then define TEXT_DOMAIN at the top of the class:

class Assets {
    const TEXT_DOMAIN = 'dokan-lite';
    // ... rest of the class
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4ce4e2d and 118f3ac.

Files selected for processing (4)
  • includes/Assets.php (5 hunks)
  • package.json (1 hunks)
  • src/utils/Mixin.js (1 hunks)
  • webpack.config.js (1 hunks)
Additional comments not posted (7)
package.json (1)

52-53: Addition of @wordpress/i18n dependency

The addition of the @wordpress/i18n package aligns with the PR's objective of fixing JavaScript translation loading issues. This package provides internationalization utilities for WordPress projects.

To ensure this addition is properly utilized, let's verify its usage in the project:

webpack.config.js (3)

Line range hint 1-168: Summary of webpack.config.js review

  1. The main change (adding ...defaultConfig.plugins) has been approved as it follows good practices for including default configurations.
  2. Several suggestions for improving the overall webpack configuration have been provided, including standardizing module imports, implementing code splitting, and optimizing for production builds.
  3. A clarification has been requested regarding how this change relates to the PR's stated objective of fixing JavaScript translation loading issues.

Overall, the configuration appears to be functional, but there's room for optimization and clarity regarding its role in addressing the PR's objectives.


84-84: Clarify the relationship between this change and the PR objectives

The PR objectives mention fixing issues related to JavaScript translation loading in the Dokan plugin. However, the change in this file (adding ...defaultConfig.plugins) doesn't seem to directly address translation loading.

Could you please clarify how this webpack configuration change relates to the stated objective of fixing JavaScript translation loading? Are there any specific plugins in defaultConfig.plugins that are crucial for translation functionality?

To help understand the context better, let's check for any translation-related configurations:

#!/bin/bash
# Description: Search for translation-related configurations

# Test: Look for any translation or internationalization related imports or configurations
rg --type javascript "i18n|translation|localization|gettext"

This will help us identify if there are any translation-related configurations that might be affected by this change.


84-84: Approve the addition of default plugins

The change to include ...defaultConfig.plugins in the plugins array is a good practice. It ensures that all default plugins from the WordPress scripts configuration are included alongside any custom plugins defined in this configuration.

To ensure this change doesn't introduce any conflicts or issues, let's verify the contents of defaultConfig.plugins:

This will help us understand the default plugins being included and ensure there are no conflicts with the custom plugins defined in this file.

includes/Assets.php (3)

Line range hint 1-1186: Summary of Asset Management Changes

The modifications in this file represent a significant shift in how Dokan handles internationalization:

  1. Replaced dokan-i18n-jed with wp-i18n across multiple script dependencies.
  2. Removed the dokan-i18n-jed script registration.
  3. Added wp_set_script_translations for all registered scripts.
  4. Updated the localization target from dokan-i18n-jed to dokan-vue-bootstrap.

These changes collectively improve the plugin's compatibility with WordPress core internationalization functions and enhance its translation capabilities. The consistent application of these changes across the file indicates a well-planned approach to updating the asset management system.

To ensure a smooth transition, please consider the following action items:

  1. Run the suggested verification scripts to catch any missed references to dokan-i18n-jed.
  2. Update any documentation or developer guidelines to reflect the new internationalization approach.
  3. Thoroughly test the plugin's translation functionality in various languages to confirm that these changes have not introduced any regressions.

Line range hint 475-516: Approve consistent updates to script dependencies.

The addition of 'wp-i18n' to multiple script dependencies is consistent with the earlier changes and reinforces the shift towards using WordPress core internationalization functions. This uniform approach across various Dokan scripts is a positive change.

To ensure all necessary scripts have been updated, please run the following script to check for any Dokan scripts that might still be missing the wp-i18n dependency:

#!/bin/bash
# Search for Dokan script registrations without 'wp-i18n' dependency
echo "Searching for Dokan scripts without 'wp-i18n' dependency:"
rg --type php "wp_enqueue_script\(\s*['\"]\w+['\"]" | rg -v "wp-i18n"

638-638: Approve update to script localization target.

The change from dokan-i18n-jed to dokan-vue-bootstrap for script localization is consistent with the earlier modifications to script dependencies. This ensures that the localized data is attached to the correct script after the removal of dokan-i18n-jed.

To ensure the localized data is correctly attached and accessible, please run the following script to check for any remaining references to dokan-i18n-jed in localization calls:

@@ -1,4 +1,4 @@
import { setLocaleData, __, _x, __n, _nx, sprintf } from '@/utils/i18n'
import { setLocaleData, __, _x, __n, _nx, sprintf } from '@wordpress/i18n'
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Import Path Successfully Updated. Review src/utils/i18n.js for Redundancy.

The shell script confirms that there are no remaining imports from @/utils/i18n, and all usages of the internationalization functions are now correctly referencing @wordpress/i18n. However, the src/utils/i18n.js file is still present in the codebase.

  • Action Items:
    • Verify if src/utils/i18n.js is used elsewhere in the project.
    • If unused, consider removing it to maintain a clean and efficient codebase.
Analysis chain

LGTM! Verify consistency across the codebase.

The change from '@/utils/i18n' to '@wordpress/i18n' aligns with the PR objective of fixing JavaScript translation loading. This shift to using WordPress's built-in i18n functions is a good practice for maintaining consistency with WordPress standards.

To ensure this change is consistent across the codebase and doesn't introduce any breaking changes, please run the following verification script:

Additionally, please ensure comprehensive testing is performed to verify that all internationalization functions continue to work as expected after this change.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining imports from '@/utils/i18n' and usages of the imported functions

# Test 1: Check for any remaining imports from '@/utils/i18n'
echo "Checking for remaining imports from '@/utils/i18n':"
rg --type js "from '@/utils/i18n'" src

# Test 2: Check for usages of the imported functions
echo "Checking for usages of imported i18n functions:"
rg --type js -w "setLocaleData|__|_x|__n|_nx|sprintf" src

# Note: Review the output to ensure all occurrences are using '@wordpress/i18n'

Length of output: 73419

includes/Assets.php Outdated Show resolved Hide resolved
@osmansufy
Copy link
Contributor Author

WPML doesn’t automatically translate strings inside JavaScript files. The current issue is that WPML cannot generate the necessary JSON translation files for JavaScript strings, even though WordPress has a built-in function wp_set_script_translations() to handle this.

Refrence : https://wpml.org/errata/translating-strings-from-javascript-files-using-wp_set_script_translations/

@osmansufy osmansufy added Needs: Testing This requires further testing Needs: Dev Review It requires a developer review and approval and removed In Progress The issues is being worked on labels Sep 24, 2024
@osmansufy
Copy link
Contributor Author

osmansufy commented Sep 26, 2024

Migration from dokan-i18n-jed to wp-i18n

Overview

This PR updates the Dokan plugin to use WordPress's built-in wp-i18n package for JavaScript string translations, replacing our custom dokan-i18n-jed package. This change aligns Dokan with WordPress core practices and improves overall consistency.

Key Changes

  1. Updated dependencies in Assets.php:

    • Replaced dokan-i18n-jed with wp-i18n in script dependencies.
    • Modified script loading order to accommodate the new dependency.
  2. Updated package.json:

    • Added @wordpress/i18n as a dependency.
  3. Modified src/utils/Mixin.js:

    • Changed import statement from @/utils/i18n to @wordpress/i18n.
  4. Delete src/utils/utils.js:

    • No longer need after replace import from @/utils/i18n to @wordpress/i18n in src/utils/Mixin.js
  5. Updated webpack.config.js:

    • Added configuration to support wp-i18n.
  6. Maintained backward compatibility:

    • Kept dokan-i18n-jed package for legacy support.
    • Added a comment to remove dokan-i18n-jed in a future release.

Implementation Details

  • Scripts now use wp_set_script_translations() to load translations.
  • The dokan-i18n-jed package is still included but marked for removal in a future release.
  • All JS files using translation functions now import from @wordpress/i18n instead of the custom utility.

Future Considerations

  • Plan to remove dokan-i18n-jed package entirely in a future release.
  • Ensure all plugins and themes dependent on Dokan are updated to use wp-i18n.

Developer Notes

  • When working on JS files, use import { __, _x, __n, _nx, sprintf } from '@wordpress/i18n' for translations.
  • Existing code using the old dokan-i18n-jed package will continue to work but should be updated when possible.
  • Test thoroughly to ensure all translations are working correctly with the new system.

Testing

  • Verify that all JS strings are correctly translated in different languages.
  • Check for any console errors related to missing translation functions.
  • Test on both new installations and upgrades from previous versions.

By adopting wp-i18n, we're aligning Dokan more closely with WordPress core practices, which should lead to better long-term maintainability and compatibility.

@osmansufy osmansufy requested a review from mrabbani September 26, 2024 06:35
@osmansufy
Copy link
Contributor Author

WPML JavaScript Translation Issue

Overview of the Problem

WPML (WordPress Multilingual Plugin) currently has a limitation in its handling of JavaScript translations. While WPML successfully translates strings in PHP files, it does not automatically generate the necessary JSON files for translating strings in JavaScript files.

Detailed Description

  1. WordPress Translation Function: WordPress introduced the wp_set_script_translations() function to facilitate translations for JavaScript files.

  2. WPML's Current Behavior:

    • WPML generates .mo files for PHP strings in the /wp-content/languages/wpml directory.
    • However, WPML does not create the required JSON translation files for JavaScript strings.
  3. Result: JavaScript strings are not automatically translated by WPML, even when properly set up using WordPress's built-in localization functions.

Reference

This issue is documented in WPML's official errata:
WPML Errata: Translating strings from JavaScript files using wp_set_script_translations()

https://wpml.org/errata/woocommerce-checkout-block-fails-to-translate-some-values/

Impact

  • Multilingual websites using WPML may have inconsistent translations, with PHP-based content correctly translated but JavaScript-based content remaining in the original language.
  • This can affect user experience, especially in dynamic parts of the website that rely heavily on JavaScript.

Current Workaround

Until WPML addresses this issue,

Loco Translate: An Alternative Solution:

Unlike WPML, Loco Translate does support the creation of JSON files for JavaScript translations. This makes it a viable alternative for projects that heavily rely on JavaScript and require multilingual support.

  • Install and activate the Loco Translate plugin.
  • In your JavaScript file, use WordPress i18n functions as normal:
  • In PHP file, set up script translations:
  • wp_set_script_translations('your-script-handle', 'your-text-domain', plugin_dir_path(__FILE__) . 'languages');
  • Use Loco Translate's interface to provide translations for your strings.
  • Loco Translate will generate both .mo and .json files in your language directory.

Long-term Solution

The permanent solution to this issue requires action from the WPML development team:

  1. WPML needs to implement support for generating JSON translation files for JavaScript strings.
  2. These JSON files should be automatically created alongside the existing .mo files.
  3. WPML should ensure compatibility with WordPress's wp_set_script_translations() function.

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

Successfully merging this pull request may close these issues.

5 participants