Skip to content
Closed
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
92 changes: 69 additions & 23 deletions src/wp-includes/class-wp-script-modules.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ class WP_Script_Modules {
*/
private $modules_with_missing_dependencies = array();

/**
* List of handles for scripts encountered which have missing script module dependencies.
*
* A handle is added to this list when it is discovered to have script module dependencies that are not
* registered. At this time, a warning is emitted with {@see _doing_it_wrong()}. The handle is then added to this
* list, so that duplicate warnings don't occur.
*
* @since 7.2.0
* @var string[]
*/
private $scripts_with_missing_module_dependencies = array();

/**
* Registers the script module if no script module with that script module
* identifier has already been registered.
Expand Down Expand Up @@ -367,22 +379,36 @@ public function set_translations( string $id, string $domain = 'default', string
}

/**
* Prints translations for all enqueued script modules.
* Prints translations for the enqueued script modules and for the script
* modules in the import map.
*
* Outputs inline `<script>` tags that call `wp.i18n.setLocaleData()` with
* the translated strings for each script module. This must run before
* the script modules execute.
*
* The translations are printed after the scripts in the footer. A script
* that imports a script module while it executes may evaluate the script
* module before its translations are printed. To avoid that, the script
* can use the 'defer' loading strategy, or import the script module once
* the document has been parsed.
*
* The translations of the enqueued script modules are printed first,
* followed by the translations of the script modules in the import map.
* When two script modules translate the same string of a text domain
* differently, the translation printed last is the one that is used.
*
* Auto-detects the text domain and translation path for each module from
* its source URL. Modules whose text domain or path differs from the
* defaults can opt into a specific domain/path via
* {@see WP_Script_Modules::set_translations()}.
*
* @since 7.0.0
* @since 7.2.0 Translations of the script module dependencies ('module_dependencies') of scripts, and of their
* dependencies, are now printed. The translations of the enqueued script modules are now printed
* first, instead of after the translations of their dependencies.
*/
public function print_script_module_translations(): void {
// Collect all module IDs that will be on the page (enqueued + their dependencies).
$module_ids = $this->get_sorted_dependencies( $this->queue );
$module_ids = $this->get_loadable_script_module_ids();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Besides changing which modules get translations (the fix we need: queue + import map), this also changes the order they are printed (before: sorted, dependencies first / after: queue + import map).

Since every module calls wp.i18n.setLocaleData() on the same domain, the last one printed wins when two modules translate the same string differently. For example:

// my-panel depends on my-dialog, buth use __( 'Close' ) ni the default domain.
wp_register_script_module( 'my-dialog', $url . 'dialog.js' );
wp_register_script_module( 'my-panel',  $url . 'panel.js', array( 'my-dialog' ) );
wp_enqueue_script_module( 'my-panel' );

// Something overrides my-panel's translations only:
add_filter( 'pre_load_script_translations', function ( $json, $file, $handle ) {
        if ( 'my-panel' === $handle ) {
                return '{"locale_data":{"messages":{"":{"lang":"pt"},"Close":["Sair"]}}}';
        }
        return $json;
}, 10, 3 );

Considering my-dialog's language-pack JSON has "Close": ["Fechar"], this is the before/after result:

Order printed Last setLocaleData __( 'Close' ) returns
before: trunk my-dialog, my-panel my-panel Sair
after: pr my-panel, my-dialog my-dialog Fechar

I don't think this happens with language packs: a string with the same context has one translation per project, so every module's JSON agrees. It takes a per-module override like the one above, or a custom path set via set_translations(). So I'd be fine with documenting the new order in the docblock.

Alternatively, we could considering adding back sorting (but differently). I see in 8951e00 that removing get_sorted_dependencies() was intentional.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I see in 8951e00 that removing get_sorted_dependencies() was intentional.

I think that the main criterion here is that classic scripts and script modules should use the same algorithm for the order in which they are printed. And classic scripts are always sorted.

The commit message on 8951e00 says:

WP_Script_Modules::get_loadable_script_module_ids() sorted the script modules with get_sorted_dependencies(). That method leaves out a script module that has an unregistered dependency, although the script module is in the import map and still loads, and it does not finish when the dependencies are circular.

Yes, but that's the same behavior that classic scripts have. The sorting code eliminates unregistered dependencies. Also also apparently triggers an infinite loop for circular dependencies?!

If script modules behave differently, that's an accidental behavior that should not be preserved, but fixed. If there are really crashing circular dependencies, that's a topic for another patch.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Nice catch, I documented the new order in the docblock of print_script_module_translations, including that the translation printed last is the one used.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think that the main criterion here is that classic scripts and script modules should use the same algorithm for the order in which they are printed.

Hi @jsnajdr, I agree that is where we should get to. I did not sort in this PR because print_script_module_data never sorted. Sorting the shared list would stop printing the data of script modules that have an unregistered dependency, which is printed today, and it would not finish for circular dependencies between script modules that scripts import, which work today. I think it is better to fix get_sorted_dependencies first and then sort all the printers in a follow-up.


$set_locale_data_js_function = <<<'JS'
( domain, translations ) => {
Expand Down Expand Up @@ -456,6 +482,10 @@ public function add_hooks() {
* priority 10 via _wp_footer_scripts), but before the script modules
* execute. Script modules with type="module" are deferred by default,
* so inline translation scripts at priority 11 will execute before them.
*
* A script that is not deferred and imports a script module while it
* executes may evaluate that script module before these translations
* are printed.
*/
add_action( 'wp_footer', array( $this, 'print_script_module_translations' ), 21 );
add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_translations' ), 11 );
Expand Down Expand Up @@ -634,7 +664,7 @@ public function print_import_map() {
* Returns the import map array.
*
* @since 6.5.0
* @since 7.0.0 Script module dependencies ('module_dependencies') of classic scripts are now included.
* @since 7.0.0 Script module dependencies ('module_dependencies') of scripts are now included.
*
* @global WP_Scripts $wp_scripts
*
Expand All @@ -646,8 +676,8 @@ private function get_import_map(): array {

$imports = array();

// Identify script modules that are dependencies of classic scripts.
$classic_script_module_dependencies = array();
// Identify script modules that are dependencies of scripts.
$script_module_dependencies = array();
if ( $wp_scripts instanceof WP_Scripts ) {
$handles = array_merge(
$wp_scripts->queue,
Expand Down Expand Up @@ -680,11 +710,14 @@ private function get_import_map(): array {
if ( ! isset( $this->registered[ $id ] ) ) {
$missing_module_dependencies[] = $id;
} else {
$classic_script_module_dependencies[] = $id;
$script_module_dependencies[] = $id;
}
}

if ( count( $missing_module_dependencies ) > 0 ) {
if (
count( $missing_module_dependencies ) > 0 &&
! in_array( $handle, $this->scripts_with_missing_module_dependencies, true )
) {
_doing_it_wrong(
'WP_Scripts::add_data',
sprintf(
Expand All @@ -696,6 +729,7 @@ private function get_import_map(): array {
),
'7.0.0'
);
$this->scripts_with_missing_module_dependencies[] = $handle;
}
}

Expand All @@ -710,8 +744,8 @@ private function get_import_map(): array {
// Note: the script modules in $this->queue are not included in the importmap because they get printed as scripts.
$ids = array_unique(
array_merge(
$classic_script_module_dependencies,
array_keys( $this->get_dependencies( array_merge( $this->queue, $classic_script_module_dependencies ) ) )
$script_module_dependencies,
array_keys( $this->get_dependencies( array_merge( $this->queue, $script_module_dependencies ) ) )
)
);
foreach ( $ids as $id ) {
Expand All @@ -723,6 +757,26 @@ private function get_import_map(): array {
return array( 'imports' => $imports );
}

/**
* Gets the IDs of the enqueued script modules and of the script modules in the import map.
*
* The script modules in the import map are the dependencies of the enqueued script modules, the script module
* dependencies ('module_dependencies') of scripts, and the dependencies of those. The enqueued script modules
* come first, followed by the script modules in the import map.
*
* @since 7.2.0
*
* @return string[] List of script module IDs.
*/
private function get_loadable_script_module_ids(): array {
return array_unique(
array_merge(
$this->queue,
array_keys( $this->get_import_map()['imports'] )

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a previous issue, it can be a follow-up optimization.

I've realized get_import_map calls doing_it_wrong. On trunk, it already runs twice per page (print_script_module_data and print_import_map), with this change it'll run three times.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, the notice is now triggered once per script, so it does not repeat.

)
);
}

/**
* Retrieves the list of script modules marked for enqueue.
*
Expand Down Expand Up @@ -1014,21 +1068,13 @@ private function get_src( string $id ): string {
* form `wp-script-module-data-{$module_id}`.
*/
public function print_script_module_data(): void {
$modules = array();
foreach ( array_unique( $this->queue ) as $id ) {
if ( '@wordpress/a11y' === $id ) {
$this->a11y_available = true;
}
$modules[ $id ] = true;
}
foreach ( array_keys( $this->get_import_map()['imports'] ) as $id ) {
if ( '@wordpress/a11y' === $id ) {
$this->a11y_available = true;
}
$modules[ $id ] = true;
$module_ids = $this->get_loadable_script_module_ids();

if ( in_array( '@wordpress/a11y', $module_ids, true ) ) {
$this->a11y_available = true;
}

foreach ( array_keys( $modules ) as $module_id ) {
foreach ( $module_ids as $module_id ) {
/**
* Filters data associated with a given Script Module.
*
Expand Down
6 changes: 6 additions & 0 deletions src/wp-includes/functions.wp-scripts.php
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,9 @@ function wp_add_inline_script( $handle, $data, $position = 'after' ) {
* `in_footer` set to true) or use a deferred loading `strategy` (`defer`),
* so that the script modules import map is printed before the script
* is evaluated. Otherwise dynamic imports may fail to resolve.
* The translations of these script modules are printed after the scripts
* in the footer. A script that is not deferred should import them once
* the document has been parsed, so that their translations are available.
* }
* @return bool Whether the script has been registered. True on success, false on failure.
*
Expand Down Expand Up @@ -458,6 +461,9 @@ function wp_deregister_script( $handle ) {
* `in_footer` set to true) or use a deferred loading `strategy` (`defer`),
* so that the script modules import map is printed before the script
* is evaluated. Otherwise dynamic imports may fail to resolve.
* The translations of these script modules are printed after the scripts
* in the footer. A script that is not deferred should import them once
* the document has been parsed, so that their translations are available.
* }
*
* @phpstan-param non-empty-string $handle
Expand Down
Loading
Loading