Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@
"phpstan": "phpstan analyse --memory-limit=1G",
"test": "vendor/bin/phpunit -c phpunit.xml.dist",
"test-multisite": "WP_MULTISITE=1 phpunit --exclude-group=ms-excluded",
"pot": "wp i18n make-pot . ./languages/project-name-features.pot --domain=project-name-features --include=\"inc,templates,assets/build/blocks\""
"pot": "wp i18n make-pot . ./languages/project-name-features.pot --domain=project-name-features --include=\"inc,templates,assets/build\""
}
}
4 changes: 3 additions & 1 deletion docs/local-development.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,12 @@ Related scripts from `@rtcamp/wp-tooling`:
| --- | --- |
| `npm run release:bump` | Bump the version in the plugin header and `package.json`. |
| `npm run release:changelog` | Generate `CHANGELOG.md` entries from Conventional Commits. |
| `npm run pot` | Regenerate `languages/<text-domain>.pot` (runs WP-CLI's `i18n make-pot` through Composer). |
| `npm run pot` | Build the production assets, then regenerate `languages/<text-domain>.pot` from the PHP and the built JS (WP-CLI's `i18n make-pot` through Composer; a bare `composer pot` skips the build). JS translations ship as JSON: run `wp i18n make-json languages --no-purge` after updating a `.po`. |

Run each with `-- --help` for the options your installed revision supports.

Classic scripts read their JSON from `languages/` on every supported WordPress version. Block scripts registered from `block.json` find it there from WordPress 6.9; on 6.7 and 6.8, copy their JSON files to `wp-content/languages/plugins/`.

## Troubleshooting

| Symptom | Check and next action |
Expand Down
34 changes: 31 additions & 3 deletions inc/Core/Assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public function register_blocks(): void {
* Assets are registered once centrally and enqueued in modules that need them.
*/
public function register_assets(): void {
$this->register_script( $this->handle( 'frontend' ), 'js/main' );
$this->register_translated_script( $this->handle( 'frontend' ), 'js/main' );
$this->register_style( $this->handle( 'frontend' ), 'css/main' );

wp_enqueue_script( $this->handle( 'frontend' ) );
Expand All @@ -241,7 +241,7 @@ public function register_assets(): void {
* Register assets for the admin.
*/
public function register_admin_assets(): void {
$this->register_script( $this->handle( 'admin' ), 'js/admin' );
$this->register_translated_script( $this->handle( 'admin' ), 'js/admin' );
$this->register_style( $this->handle( 'admin' ), 'css/admin' );
}

Expand All @@ -255,7 +255,7 @@ public function register_admin_assets(): void {
*/
public function register_editor_assets(): void {
if ( $this->has_asset( 'js/editor', 'js' ) ) {
$this->register_script( $this->handle( 'editor' ), 'js/editor' );
$this->register_translated_script( $this->handle( 'editor' ), 'js/editor' );
}

if ( $this->has_asset( 'css/editor', 'css' ) ) {
Expand All @@ -271,4 +271,32 @@ public function register_module_scripts(): void {
wp_enqueue_script_module( '@project-name-features/module' );
}
}

/**
* Register a classic script and point it at the plugin's JS translations.
*
* Translations are set only when the build lists wp-i18n as a dependency (the
* script imports @wordpress/i18n), so a script without strings does not pull
* wp-i18n onto the page. Block scripts need no call: register_block_type()
* sets the textdomain from block.json, and from WordPress 6.9 core finds the
* JSON in the path load_plugin_textdomain() registers.
*
* @param string $handle Script handle.
* @param string $filename Asset path relative to assets/build, without the extension.
*
* @return bool Whether the script was registered.
*/
private function register_translated_script( string $handle, string $filename ): bool {
if ( ! $this->register_script( $handle, $filename ) ) {
return false;
}

$script = wp_scripts()->query( $handle );

if ( $script instanceof \_WP_Dependency && in_array( 'wp-i18n', $script->deps, true ) ) {
wp_set_script_translations( $handle, 'project-name-features', $this->base_dir . 'languages' );
}

return true;
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
"test:php:coverage": "wp-env run --config=.wp-env.tests.json cli --env-cwd=wp-content/plugins/$(basename \"$PWD\") -- vendor/bin/phpunit -c phpunit.xml.dist --coverage-html coverage",
"posttest:php:coverage": "echo \"\\e[1m\\e[32mIf you have run this command with xdbug coverage enabled, you can view the coverage report at /coverage path\\e[0m\"",
"wp-env": "wp-env",
"prepot": "npm run build:prod",
"pot": "composer run pot"
}
}
161 changes: 161 additions & 0 deletions tests/php/AssetsTranslationsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
<?php
/**
* Tests for JS translation loading in the Assets class.
*
* @package Project_Name\Features
*/

declare( strict_types = 1 );

namespace Project_Name\Features\Tests;

use Project_Name\Features\Core\Assets;

/**
* Class AssetsTranslationsTest
*
* CI runs PHPUnit without a build, so each test writes a built js/editor fixture
* and a translation file, then removes them. The starter has no editor entry, so
* the fixture does not collide with a local build.
*
* @since 1.0.2
*/
final class AssetsTranslationsTest extends TestCase {

/**
* Locale the translation fixture is written for.
*/
private const LOCALE = 'zz_ZZ';

/**
* Files and directories this test created, in creation order.
*
* @var array<int, string>
*/
private array $created = [];

/**
* Start from a fresh script registry in the fixture locale.
*/
public function set_up(): void {
parent::set_up();

$GLOBALS['wp_scripts'] = null;

add_filter( 'determine_locale', static fn (): string => self::LOCALE );
}

/**
* Remove the fixtures and the script registry this test created.
*/
public function tear_down(): void {
foreach ( array_reverse( $this->created ) as $path ) {
if ( is_dir( $path ) ) {
rmdir( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- Test fixture cleanup.
} elseif ( file_exists( $path ) ) {
unlink( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Test fixture cleanup.
}
}

$this->created = [];
$GLOBALS['wp_scripts'] = null;

parent::tear_down();
}

/**
* A script built against @wordpress/i18n gets its strings from the plugin's languages/ directory.
*/
public function test_script_using_i18n_loads_plugin_translations(): void {
$this->create_fixtures( [ 'wp-i18n' ] );

$assets = new Assets();
$assets->register_editor_assets();

$translations = wp_scripts()->print_translations( $assets->handle( 'editor' ), false );

$this->assertIsString( $translations );
$this->assertStringContainsString( 'Translated example string', $translations );
}

/**
* A script without i18n strings gets no translations, so wp-i18n stays off the page.
*/
public function test_script_without_i18n_skips_translations(): void {
$this->create_fixtures( [] );

$assets = new Assets();
$assets->register_editor_assets();

$handle = $assets->handle( 'editor' );
$script = wp_scripts()->query( $handle );

$this->assertInstanceOf( \_WP_Dependency::class, $script );
$this->assertNotContains( 'wp-i18n', $script->deps );
$this->assertFalse( wp_scripts()->print_translations( $handle, false ) );
}

/**
* Write assets/build/js/editor.js, its .asset.php manifest, and a translation
* file named the way `wp i18n make-json` names it for that script.
*
* @param array<int, string> $dependencies Dependencies the manifest lists.
*/
private function create_fixtures( array $dependencies ): void {
$build_dir = PROJECT_NAME_FEATURES_PATH . 'assets/build/js';
$json_file = sprintf(
'%slanguages/project-name-features-%s-%s.json',
PROJECT_NAME_FEATURES_PATH,
self::LOCALE,
md5( 'assets/build/js/editor.js' )
);

$manifest = sprintf(
"<?php return array( 'dependencies' => %s, 'version' => 'test' );\n",
var_export( $dependencies, true ) // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export -- Writes a fixture manifest.
);

$translations = (string) wp_json_encode(
[
'domain' => 'messages',
'locale_data' => [
'messages' => [
'' => [
'domain' => 'messages',
'lang' => self::LOCALE,
],
'Example string' => [ 'Translated example string' ],
],
],
]
);

$files = [
"{$build_dir}/editor.js" => '',
"{$build_dir}/editor.asset.php" => $manifest,
$json_file => $translations,
];

foreach ( array_keys( $files ) as $file ) {
if ( file_exists( $file ) ) {
$this->markTestSkipped( "{$file} already exists; this test writes its own fixture there." );
}
}

$missing = [];
$path = $build_dir;
while ( ! is_dir( $path ) ) {
$missing[] = $path;
$path = dirname( $path );
}
foreach ( array_reverse( $missing ) as $new_dir ) {
mkdir( $new_dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir -- Test fixture.
$this->created[] = $new_dir;
}

foreach ( $files as $file => $contents ) {
file_put_contents( $file, $contents ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture.
$this->created[] = $file;
}
}
}
Loading