| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Script Modules API: WP_Script_Modules class. 4 * 5 * Native support for ES Modules and Import Maps. 6 * 7 * @package WordPress 8 * @subpackage Script Modules 9 */ 10 11 /** 12 * Core class used to register script modules. 13 * 14 * @since 6.5.0 15 * 16 * @phpstan-type ScriptModule array{ 17 * src: string, 18 * version: string|false|null, 19 * dependencies: array<int, array{ id: string, import: 'static'|'dynamic' }>, 20 * in_footer: bool, 21 * fetchpriority: 'auto'|'low'|'high', 22 * textdomain?: string, 23 * translations_path?: string, 24 * } 25 */ 26 class WP_Script_Modules { 27 /** 28 * Holds the registered script modules, keyed by script module identifier. 29 * 30 * @since 6.5.0 31 * @var array<string, array<string, mixed>> 32 * @phpstan-var array<string, ScriptModule> 33 */ 34 private $registered = array(); 35 36 /** 37 * An array of IDs for queued script modules. 38 * 39 * @since 6.9.0 40 * @var string[] 41 */ 42 private $queue = array(); 43 44 /** 45 * Holds the script module identifiers that have been printed. 46 * 47 * @since 6.9.0 48 * @var string[] 49 */ 50 private $done = array(); 51 52 /** 53 * Tracks whether the @wordpress/a11y script module is available. 54 * 55 * Some additional HTML is required on the page for the module to work. Track 56 * whether it's available to print at the appropriate time. 57 * 58 * @since 6.7.0 59 * @var bool 60 */ 61 private $a11y_available = false; 62 63 /** 64 * Holds a mapping of dependents (as IDs) for a given script ID. 65 * Used to optimize recursive dependency tree checks. 66 * 67 * @since 6.9.0 68 * @var array<string, string[]> 69 */ 70 private $dependents_map = array(); 71 72 /** 73 * Holds the valid values for fetchpriority. 74 * 75 * @since 6.9.0 76 * @var string[] 77 */ 78 private $priorities = array( 79 'low', 80 'auto', 81 'high', 82 ); 83 84 /** 85 * List of IDs for script modules encountered which have missing dependencies. 86 * 87 * An ID is added to this list when it is discovered to have missing dependencies. At this time, a warning is 88 * emitted with {@see _doing_it_wrong()}. The ID is then added to this list, so that duplicate warnings don't occur. 89 * 90 * @since 6.9.1 91 * @var string[] 92 */ 93 private $modules_with_missing_dependencies = array(); 94 95 /** 96 * List of handles for scripts encountered which have missing script module dependencies. 97 * 98 * A handle is added to this list when it is discovered to have script module dependencies that are not 99 * registered. At this time, a warning is emitted with {@see _doing_it_wrong()}. The handle is then added to this 100 * list, so that duplicate warnings don't occur. 101 * 102 * @since 7.2.0 103 * @var string[] 104 */ 105 private $scripts_with_missing_module_dependencies = array(); 106 107 /** 108 * Registers the script module if no script module with that script module 109 * identifier has already been registered. 110 * 111 * @since 6.5.0 112 * @since 6.9.0 Added the $args parameter. 113 * 114 * @param string $id The identifier of the script module. Should be unique. It will be used in the 115 * final import map. 116 * @param string $src Optional. Full URL of the script module, or path of the script module relative 117 * to the WordPress root directory. If it is provided and the script module has 118 * not been registered yet, it will be registered. 119 * @param array<string|array<string, string>> $deps { 120 * Optional. List of dependencies. 121 * 122 * @type string|array<string, string> ...$0 { 123 * An array of script module identifiers of the dependencies of this script 124 * module. The dependencies can be strings or arrays. If they are arrays, 125 * they need an `id` key with the script module identifier, and can contain 126 * an `import` key with either `static` or `dynamic`. By default, 127 * dependencies that don't contain an `import` key are considered static. 128 * 129 * @type string $id The script module identifier. 130 * @type string $import Optional. Import type. May be either `static` or 131 * `dynamic`. Defaults to `static`. 132 * } 133 * } 134 * @param string|false|null $version Optional. String specifying the script module version number. Defaults to false. 135 * It is added to the URL as a query string for cache busting purposes. If $version 136 * is set to false, the version number is the currently installed WordPress version. 137 * If $version is set to null, no version is added. 138 * @param array<string, string|bool> $args { 139 * Optional. An array of additional args. Default empty array. 140 * 141 * @type bool $in_footer Whether to print the script module in the footer. Only relevant to block themes. Default 'false'. Optional. 142 * @type 'auto'|'low'|'high' $fetchpriority Fetch priority. Default 'auto'. Optional. 143 * } 144 */ 145 public function register( string $id, string $src, array $deps = array(), $version = false, array $args = array() ) { 146 if ( '' === $id ) { 147 _doing_it_wrong( __METHOD__, __( 'Non-empty string required for id.' ), '6.9.0' ); 148 return; 149 } 150 151 if ( ! isset( $this->registered[ $id ] ) ) { 152 $dependencies = array(); 153 foreach ( $deps as $dependency ) { 154 if ( is_array( $dependency ) ) { 155 if ( ! isset( $dependency['id'] ) || ! is_string( $dependency['id'] ) ) { 156 _doing_it_wrong( __METHOD__, __( 'Missing required id key in entry among dependencies array.' ), '6.5.0' ); 157 continue; 158 } 159 $dependencies[] = array( 160 'id' => $dependency['id'], 161 'import' => isset( $dependency['import'] ) && 'dynamic' === $dependency['import'] ? 'dynamic' : 'static', 162 ); 163 } elseif ( is_string( $dependency ) ) { 164 $dependencies[] = array( 165 'id' => $dependency, 166 'import' => 'static', 167 ); 168 } else { 169 _doing_it_wrong( __METHOD__, __( 'Entries in dependencies array must be either strings or arrays with an id key.' ), '6.5.0' ); 170 } 171 } 172 173 $in_footer = isset( $args['in_footer'] ) && (bool) $args['in_footer']; 174 175 $fetchpriority = 'auto'; 176 if ( isset( $args['fetchpriority'] ) ) { 177 if ( $this->is_valid_fetchpriority( $args['fetchpriority'] ) ) { 178 $fetchpriority = $args['fetchpriority']; 179 } else { 180 _doing_it_wrong( 181 __METHOD__, 182 sprintf( 183 /* translators: 1: $fetchpriority, 2: $id */ 184 __( 'Invalid fetchpriority `%1$s` defined for `%2$s` during script registration.' ), 185 is_string( $args['fetchpriority'] ) ? $args['fetchpriority'] : gettype( $args['fetchpriority'] ), 186 $id 187 ), 188 '6.9.0' 189 ); 190 } 191 } 192 193 $this->registered[ $id ] = array( 194 'src' => $src, 195 'version' => $version, 196 'dependencies' => $dependencies, 197 'in_footer' => $in_footer, 198 'fetchpriority' => $fetchpriority, 199 ); 200 } 201 } 202 203 /** 204 * Gets IDs for queued script modules. 205 * 206 * @since 6.9.0 207 * 208 * @return string[] Script module IDs. 209 */ 210 public function get_queue(): array { 211 return $this->queue; 212 } 213 214 /** 215 * Checks if the provided fetchpriority is valid. 216 * 217 * @since 6.9.0 218 * 219 * @param string|mixed $priority Fetch priority. 220 * @return bool Whether valid fetchpriority. 221 */ 222 private function is_valid_fetchpriority( $priority ): bool { 223 return in_array( $priority, $this->priorities, true ); 224 } 225 226 /** 227 * Sets the fetch priority for a script module. 228 * 229 * @since 6.9.0 230 * 231 * @param string $id Script module identifier. 232 * @param 'auto'|'low'|'high' $priority Fetch priority for the script module. 233 * @return bool Whether setting the fetchpriority was successful. 234 */ 235 public function set_fetchpriority( string $id, string $priority ): bool { 236 if ( ! isset( $this->registered[ $id ] ) ) { 237 return false; 238 } 239 240 if ( '' === $priority ) { 241 $priority = 'auto'; 242 } 243 244 if ( ! $this->is_valid_fetchpriority( $priority ) ) { 245 _doing_it_wrong( 246 __METHOD__, 247 /* translators: %s: Invalid fetchpriority. */ 248 sprintf( __( 'Invalid fetchpriority: %s' ), $priority ), 249 '6.9.0' 250 ); 251 return false; 252 } 253 254 $this->registered[ $id ]['fetchpriority'] = $priority; 255 return true; 256 } 257 258 /** 259 * Sets whether a script module should be printed in the footer. 260 * 261 * This is only relevant in block themes. 262 * 263 * @since 6.9.0 264 * 265 * @param string $id Script module identifier. 266 * @param bool $in_footer Whether to print in the footer. 267 * @return bool Whether setting the printing location was successful. 268 */ 269 public function set_in_footer( string $id, bool $in_footer ): bool { 270 if ( ! isset( $this->registered[ $id ] ) ) { 271 return false; 272 } 273 $this->registered[ $id ]['in_footer'] = $in_footer; 274 return true; 275 } 276 277 /** 278 * Marks the script module to be enqueued in the page. 279 * 280 * If a src is provided and the script module has not been registered yet, it 281 * will be registered. 282 * 283 * @since 6.5.0 284 * @since 6.9.0 Added the $args parameter. 285 * 286 * @param string $id The identifier of the script module. Should be unique. It will be used in the 287 * final import map. 288 * @param string $src Optional. Full URL of the script module, or path of the script module relative 289 * to the WordPress root directory. If it is provided and the script module has 290 * not been registered yet, it will be registered. 291 * @param array<string|array<string, string>> $deps { 292 * Optional. List of dependencies. 293 * 294 * @type string|array<string, string> ...$0 { 295 * An array of script module identifiers of the dependencies of this script 296 * module. The dependencies can be strings or arrays. If they are arrays, 297 * they need an `id` key with the script module identifier, and can contain 298 * an `import` key with either `static` or `dynamic`. By default, 299 * dependencies that don't contain an `import` key are considered static. 300 * 301 * @type string $id The script module identifier. 302 * @type string $import Optional. Import type. May be either `static` or 303 * `dynamic`. Defaults to `static`. 304 * } 305 * } 306 * @param string|false|null $version Optional. String specifying the script module version number. Defaults to false. 307 * It is added to the URL as a query string for cache busting purposes. If $version 308 * is set to false, the version number is the currently installed WordPress version. 309 * If $version is set to null, no version is added. 310 * @param array<string, string|bool> $args { 311 * Optional. An array of additional args. Default empty array. 312 * 313 * @type bool $in_footer Whether to print the script module in the footer. Only relevant to block themes. Default 'false'. Optional. 314 * @type 'auto'|'low'|'high' $fetchpriority Fetch priority. Default 'auto'. Optional. 315 * } 316 */ 317 public function enqueue( string $id, string $src = '', array $deps = array(), $version = false, array $args = array() ) { 318 if ( '' === $id ) { 319 _doing_it_wrong( __METHOD__, __( 'Non-empty string required for id.' ), '6.9.0' ); 320 return; 321 } 322 323 if ( ! in_array( $id, $this->queue, true ) ) { 324 $this->queue[] = $id; 325 } 326 if ( ! isset( $this->registered[ $id ] ) && $src ) { 327 $this->register( $id, $src, $deps, $version, $args ); 328 } 329 } 330 331 /** 332 * Unmarks the script module so it will no longer be enqueued in the page. 333 * 334 * @since 6.5.0 335 * 336 * @param string $id The identifier of the script module. 337 */ 338 public function dequeue( string $id ) { 339 $this->queue = array_values( array_diff( $this->queue, array( $id ) ) ); 340 } 341 342 /** 343 * Removes a registered script module. 344 * 345 * @since 6.5.0 346 * 347 * @param string $id The identifier of the script module. 348 */ 349 public function deregister( string $id ) { 350 $this->dequeue( $id ); 351 unset( $this->registered[ $id ] ); 352 } 353 354 /** 355 * Overrides the text domain and path used to load translations for a script module. 356 * 357 * This is only needed for modules whose text domain differs from 'default' 358 * or whose translation files live outside the standard locations, for 359 * example plugin modules that register their own text domain. Translations 360 * for modules that use the default domain are loaded automatically by 361 * {@see WP_Script_Modules::print_script_module_translations()}. 362 * 363 * @since 7.0.0 364 * 365 * @param string $id The identifier of the script module. 366 * @param string $domain Optional. Text domain. Default 'default'. 367 * @param string $path Optional. The full file path to the directory containing translation files. 368 * @return bool True if the text domain was registered, false if the module is not registered. 369 */ 370 public function set_translations( string $id, string $domain = 'default', string $path = '' ): bool { 371 if ( ! isset( $this->registered[ $id ] ) ) { 372 return false; 373 } 374 375 $this->registered[ $id ]['textdomain'] = $domain; 376 $this->registered[ $id ]['translations_path'] = $path; 377 378 return true; 379 } 380 381 /** 382 * Prints translations for the enqueued script modules and for the script 383 * modules in the import map. 384 * 385 * Outputs inline `<script>` tags that call `wp.i18n.setLocaleData()` with 386 * the translated strings for each script module. This must run before 387 * the script modules execute. 388 * 389 * The translations are printed after the scripts in the footer. A script 390 * that imports a script module while it executes may evaluate the script 391 * module before its translations are printed. To avoid that, the script 392 * can use the 'defer' loading strategy, or import the script module once 393 * the document has been parsed. 394 * 395 * The translations of the enqueued script modules are printed first, 396 * followed by the translations of the script modules in the import map. 397 * When two script modules translate the same string of a text domain 398 * differently, the translation printed last is the one that is used. 399 * 400 * Auto-detects the text domain and translation path for each module from 401 * its source URL. Modules whose text domain or path differs from the 402 * defaults can opt into a specific domain/path via 403 * {@see WP_Script_Modules::set_translations()}. 404 * 405 * @since 7.0.0 406 * @since 7.2.0 Translations of the script module dependencies ('module_dependencies') of scripts, and of their 407 * dependencies, are now printed. The translations of the enqueued script modules are now printed 408 * first, instead of after the translations of their dependencies. 409 */ 410 public function print_script_module_translations(): void { 411 $module_ids = $this->get_loadable_script_module_ids(); 412 413 $set_locale_data_js_function = <<<'JS' 414 ( domain, translations ) => { 415 const localeData = translations.locale_data[ domain ] || translations.locale_data.messages; 416 localeData[""].domain = domain; 417 wp.i18n.setLocaleData( localeData, domain ); 418 } 419 JS; 420 421 foreach ( $module_ids as $id ) { 422 $domain = $this->registered[ $id ]['textdomain'] ?? 'default'; 423 $path = $this->registered[ $id ]['translations_path'] ?? ''; 424 425 $json_translations = load_script_module_textdomain( $id, $domain, $path ); 426 427 if ( ! $json_translations ) { 428 continue; 429 } 430 431 $output = sprintf( 432 '( %s )( %s, %s );', 433 $set_locale_data_js_function, 434 wp_json_encode( $domain, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ), 435 $json_translations 436 ); 437 $script_id = "wp-script-module-translation-data-{$id}"; 438 $output .= "\n//# sourceURL=" . rawurlencode( $script_id ); 439 440 // Ensure wp-i18n is printed; the inline script below relies on wp.i18n.setLocaleData(). 441 if ( ! wp_script_is( 'wp-i18n', 'done' ) ) { 442 wp_scripts()->do_items( array( 'wp-i18n' ) ); 443 } 444 445 wp_print_inline_script_tag( $output, array( 'id' => $script_id ) ); 446 } 447 } 448 449 /** 450 * Adds the hooks to print the import map, enqueued script modules and script 451 * module preloads. 452 * 453 * In classic themes, the script modules used by the blocks are not yet known 454 * when the `wp_head` actions is fired, so it needs to print everything in the 455 * footer. 456 * 457 * @since 6.5.0 458 */ 459 public function add_hooks() { 460 $is_block_theme = wp_is_block_theme(); 461 $position = $is_block_theme ? 'wp_head' : 'wp_footer'; 462 add_action( $position, array( $this, 'print_import_map' ) ); 463 if ( $is_block_theme ) { 464 /* 465 * Modules can only be printed in the head for block themes because only with 466 * block themes will import map be fully populated by modules discovered by 467 * rendering the block template. In classic themes, modules are enqueued during 468 * template rendering, thus the import map must be printed in the footer, 469 * followed by all enqueued modules. 470 */ 471 add_action( 'wp_head', array( $this, 'print_head_enqueued_script_modules' ) ); 472 } 473 add_action( 'wp_footer', array( $this, 'print_enqueued_script_modules' ) ); 474 add_action( $position, array( $this, 'print_script_module_preloads' ) ); 475 476 add_action( 'admin_print_footer_scripts', array( $this, 'print_import_map' ), 9 ); 477 add_action( 'admin_print_footer_scripts', array( $this, 'print_enqueued_script_modules' ) ); 478 add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_preloads' ) ); 479 480 /* 481 * Print translations after classic scripts like wp-i18n are loaded (at 482 * priority 10 via _wp_footer_scripts), but before the script modules 483 * execute. Script modules with type="module" are deferred by default, 484 * so inline translation scripts at priority 11 will execute before them. 485 * 486 * A script that is not deferred and imports a script module while it 487 * executes may evaluate that script module before these translations 488 * are printed. 489 */ 490 add_action( 'wp_footer', array( $this, 'print_script_module_translations' ), 21 ); 491 add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_translations' ), 11 ); 492 493 add_action( 'wp_footer', array( $this, 'print_script_module_data' ) ); 494 add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_data' ) ); 495 add_action( 'wp_footer', array( $this, 'print_a11y_script_module_html' ), 20 ); 496 add_action( 'admin_print_footer_scripts', array( $this, 'print_a11y_script_module_html' ), 20 ); 497 } 498 499 /** 500 * Gets the highest fetch priority for the provided script IDs. 501 * 502 * @since 6.9.0 503 * 504 * @param string[] $ids Script module IDs. 505 * @return 'auto'|'low'|'high' Highest fetch priority for the provided script module IDs. 506 */ 507 private function get_highest_fetchpriority( array $ids ): string { 508 static $high_priority_index = null; 509 if ( null === $high_priority_index ) { 510 $high_priority_index = count( $this->priorities ) - 1; 511 } 512 513 $highest_priority_index = 0; 514 foreach ( $ids as $id ) { 515 if ( isset( $this->registered[ $id ] ) ) { 516 $highest_priority_index = (int) max( 517 $highest_priority_index, 518 (int) array_search( $this->registered[ $id ]['fetchpriority'], $this->priorities, true ) 519 ); 520 if ( $high_priority_index === $highest_priority_index ) { 521 break; 522 } 523 } 524 } 525 526 return $this->priorities[ $highest_priority_index ]; 527 } 528 529 /** 530 * Prints the enqueued script modules in head. 531 * 532 * This is only used in block themes. 533 * 534 * @since 6.9.0 535 */ 536 public function print_head_enqueued_script_modules() { 537 foreach ( $this->get_sorted_dependencies( $this->queue ) as $id ) { 538 if ( 539 isset( $this->registered[ $id ] ) && 540 ! $this->registered[ $id ]['in_footer'] 541 ) { 542 // If any dependency is set to be printed in footer, skip printing this module in head. 543 $dependencies = array_keys( $this->get_dependencies( array( $id ) ) ); 544 foreach ( $dependencies as $dependency_id ) { 545 if ( 546 in_array( $dependency_id, $this->queue, true ) && 547 isset( $this->registered[ $dependency_id ] ) && 548 $this->registered[ $dependency_id ]['in_footer'] 549 ) { 550 continue 2; 551 } 552 } 553 $this->print_script_module( $id ); 554 } 555 } 556 } 557 558 /** 559 * Prints the enqueued script modules in footer. 560 * 561 * @since 6.5.0 562 */ 563 public function print_enqueued_script_modules() { 564 foreach ( $this->get_sorted_dependencies( $this->queue ) as $id ) { 565 $this->print_script_module( $id ); 566 } 567 } 568 569 /** 570 * Prints the enqueued script module using script tags with type="module" 571 * attributes. 572 * 573 * @since 6.9.0 574 * 575 * @param string $id The script module identifier. 576 */ 577 private function print_script_module( string $id ) { 578 if ( in_array( $id, $this->done, true ) || ! in_array( $id, $this->queue, true ) ) { 579 return; 580 } 581 582 $this->done[] = $id; 583 584 $src = $this->get_src( $id ); 585 if ( '' === $src ) { 586 return; 587 } 588 589 $attributes = array( 590 'type' => 'module', 591 'src' => $src, 592 'id' => $id . '-js-module', 593 ); 594 595 $script_module = $this->registered[ $id ]; 596 $queued_dependents = array_intersect( $this->queue, $this->get_recursive_dependents( $id ) ); 597 $fetchpriority = $this->get_highest_fetchpriority( array_merge( array( $id ), $queued_dependents ) ); 598 if ( 'auto' !== $fetchpriority ) { 599 $attributes['fetchpriority'] = $fetchpriority; 600 } 601 if ( $fetchpriority !== $script_module['fetchpriority'] ) { 602 $attributes['data-wp-fetchpriority'] = $script_module['fetchpriority']; 603 } 604 wp_print_script_tag( $attributes ); 605 } 606 607 /** 608 * Prints the static dependencies of the enqueued script modules using 609 * link tags with rel="modulepreload" attributes. 610 * 611 * If a script module is marked for enqueue, it will not be preloaded. 612 * 613 * @since 6.5.0 614 */ 615 public function print_script_module_preloads() { 616 $dependency_ids = $this->get_sorted_dependencies( $this->queue, array( 'static' ) ); 617 foreach ( $dependency_ids as $id ) { 618 // Don't preload if it's marked for enqueue. 619 if ( in_array( $id, $this->queue, true ) ) { 620 continue; 621 } 622 623 $src = $this->get_src( $id ); 624 if ( '' === $src ) { 625 continue; 626 } 627 628 $enqueued_dependents = array_intersect( $this->get_recursive_dependents( $id ), $this->queue ); 629 $highest_fetchpriority = $this->get_highest_fetchpriority( $enqueued_dependents ); 630 printf( 631 '<link rel="modulepreload" href="%s" id="%s"', 632 esc_url( $src ), 633 esc_attr( $id . '-js-modulepreload' ) 634 ); 635 if ( 'auto' !== $highest_fetchpriority ) { 636 printf( ' fetchpriority="%s"', esc_attr( $highest_fetchpriority ) ); 637 } 638 if ( $highest_fetchpriority !== $this->registered[ $id ]['fetchpriority'] && 'auto' !== $this->registered[ $id ]['fetchpriority'] ) { 639 printf( ' data-wp-fetchpriority="%s"', esc_attr( $this->registered[ $id ]['fetchpriority'] ) ); 640 } 641 echo ">\n"; 642 } 643 } 644 645 /** 646 * Prints the import map using a script tag with a type="importmap" attribute. 647 * 648 * @since 6.5.0 649 */ 650 public function print_import_map() { 651 $import_map = $this->get_import_map(); 652 if ( ! empty( $import_map['imports'] ) ) { 653 wp_print_inline_script_tag( 654 (string) wp_json_encode( $import_map, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ), 655 array( 656 'type' => 'importmap', 657 'id' => 'wp-importmap', 658 ) 659 ); 660 } 661 } 662 663 /** 664 * Returns the import map array. 665 * 666 * @since 6.5.0 667 * @since 7.0.0 Script module dependencies ('module_dependencies') of scripts are now included. 668 * 669 * @global WP_Scripts $wp_scripts 670 * 671 * @return array<string, array<string, string>> Array with an `imports` key mapping to an array of script module 672 * identifiers and their respective URLs, including the version query. 673 */ 674 private function get_import_map(): array { 675 global $wp_scripts; 676 677 $imports = array(); 678 679 // Identify script modules that are dependencies of scripts. 680 $script_module_dependencies = array(); 681 if ( $wp_scripts instanceof WP_Scripts ) { 682 $handles = array_merge( 683 $wp_scripts->queue, 684 $wp_scripts->to_do, 685 $wp_scripts->done 686 ); 687 688 $processed = array(); 689 while ( ! empty( $handles ) ) { 690 $handle = array_pop( $handles ); 691 if ( isset( $processed[ $handle ] ) || ! isset( $wp_scripts->registered[ $handle ] ) ) { 692 continue; 693 } 694 $processed[ $handle ] = true; 695 696 $module_dependencies = $wp_scripts->get_data( $handle, 'module_dependencies' ); 697 if ( is_array( $module_dependencies ) ) { 698 $missing_module_dependencies = array(); 699 foreach ( $module_dependencies as $module ) { 700 if ( is_string( $module ) ) { 701 $id = $module; 702 } elseif ( is_array( $module ) && isset( $module['id'] ) && is_string( $module['id'] ) ) { 703 $id = $module['id']; 704 } else { 705 // Invalid module dependency was supplied by direct manipulation of the extra data. 706 // Normally, this error scenario would be caught when WP_Scripts::add_data() is called. 707 continue; 708 } 709 710 if ( ! isset( $this->registered[ $id ] ) ) { 711 $missing_module_dependencies[] = $id; 712 } else { 713 $script_module_dependencies[] = $id; 714 } 715 } 716 717 if ( 718 count( $missing_module_dependencies ) > 0 && 719 ! in_array( $handle, $this->scripts_with_missing_module_dependencies, true ) 720 ) { 721 _doing_it_wrong( 722 'WP_Scripts::add_data', 723 sprintf( 724 /* translators: 1: Script handle, 2: 'module_dependencies', 3: List of missing dependency IDs. */ 725 __( 'The script with the handle "%1$s" was enqueued with script module dependencies ("%2$s") that are not registered: %3$s.' ), 726 $handle, 727 'module_dependencies', 728 implode( wp_get_list_item_separator(), $missing_module_dependencies ) 729 ), 730 '7.0.0' 731 ); 732 $this->scripts_with_missing_module_dependencies[] = $handle; 733 } 734 } 735 736 foreach ( $wp_scripts->registered[ $handle ]->deps as $dep ) { 737 if ( ! isset( $processed[ $dep ] ) ) { 738 $handles[] = $dep; 739 } 740 } 741 } 742 } 743 744 // Note: the script modules in $this->queue are not included in the importmap because they get printed as scripts. 745 $ids = array_unique( 746 array_merge( 747 $script_module_dependencies, 748 array_keys( $this->get_dependencies( array_merge( $this->queue, $script_module_dependencies ) ) ) 749 ) 750 ); 751 foreach ( $ids as $id ) { 752 $src = $this->get_src( $id ); 753 if ( '' !== $src ) { 754 $imports[ $id ] = $src; 755 } 756 } 757 return array( 'imports' => $imports ); 758 } 759 760 /** 761 * Gets the IDs of the enqueued script modules and of the script modules in the import map. 762 * 763 * The script modules in the import map are the dependencies of the enqueued script modules, the script module 764 * dependencies ('module_dependencies') of scripts, and the dependencies of those. The enqueued script modules 765 * come first, followed by the script modules in the import map. 766 * 767 * @since 7.2.0 768 * 769 * @return string[] List of script module IDs. 770 */ 771 private function get_loadable_script_module_ids(): array { 772 return array_unique( 773 array_merge( 774 $this->queue, 775 array_keys( $this->get_import_map()['imports'] ) 776 ) 777 ); 778 } 779 780 /** 781 * Retrieves the list of script modules marked for enqueue. 782 * 783 * Even though this is a private method and is unused in core, there are ecosystem plugins accessing it via the 784 * Reflection API. The ecosystem should rather use {@see self::get_queue()}. 785 * 786 * @since 6.5.0 787 * 788 * @return array<string, array<string, mixed>> Script modules marked for enqueue, keyed by script module identifier. 789 * @phpstan-return array<string, ScriptModule> 790 */ 791 private function get_marked_for_enqueue(): array { 792 return wp_array_slice_assoc( 793 $this->registered, 794 $this->queue 795 ); 796 } 797 798 /** 799 * Retrieves all the dependencies for the given script module identifiers, filtered by import types. 800 * 801 * It will consolidate an array containing a set of unique dependencies based 802 * on the requested import types: 'static', 'dynamic', or both. This method is 803 * recursive and also retrieves dependencies of the dependencies. 804 * 805 * @since 6.5.0 806 * 807 * @param string[] $ids The identifiers of the script modules for which to gather dependencies. 808 * @param string[] $import_types Optional. Import types of dependencies to retrieve: 'static', 'dynamic', or both. 809 * Default is both. 810 * @return array<string, array<string, mixed>> List of dependencies, keyed by script module identifier. 811 * @phpstan-return array<string, ScriptModule> 812 */ 813 private function get_dependencies( array $ids, array $import_types = array( 'static', 'dynamic' ) ): array { 814 $all_dependencies = array(); 815 $id_queue = $ids; 816 817 while ( ! empty( $id_queue ) ) { 818 $id = array_shift( $id_queue ); 819 if ( ! isset( $this->registered[ $id ] ) ) { 820 continue; 821 } 822 823 foreach ( $this->registered[ $id ]['dependencies'] as $dependency ) { 824 if ( 825 ! isset( $all_dependencies[ $dependency['id'] ] ) && 826 in_array( $dependency['import'], $import_types, true ) && 827 isset( $this->registered[ $dependency['id'] ] ) 828 ) { 829 $all_dependencies[ $dependency['id'] ] = $this->registered[ $dependency['id'] ]; 830 831 // Add this dependency to the list to get dependencies for. 832 $id_queue[] = $dependency['id']; 833 } 834 } 835 } 836 837 return $all_dependencies; 838 } 839 840 /** 841 * Gets all dependents of a script module. 842 * 843 * This is not recursive. 844 * 845 * @since 6.9.0 846 * 847 * @see WP_Scripts::get_dependents() 848 * 849 * @param string $id The script ID. 850 * @return string[] Script module IDs. 851 */ 852 private function get_dependents( string $id ): array { 853 // Check if dependents map for the handle in question is present. If so, use it. 854 if ( isset( $this->dependents_map[ $id ] ) ) { 855 return $this->dependents_map[ $id ]; 856 } 857 858 $dependents = array(); 859 860 // Iterate over all registered scripts, finding dependents of the script passed to this method. 861 foreach ( $this->registered as $registered_id => $args ) { 862 if ( in_array( $id, wp_list_pluck( $args['dependencies'], 'id' ), true ) ) { 863 $dependents[] = $registered_id; 864 } 865 } 866 867 // Add the module's dependents to the map to ease future lookups. 868 $this->dependents_map[ $id ] = $dependents; 869 870 return $dependents; 871 } 872 873 /** 874 * Gets all recursive dependents of a script module. 875 * 876 * @since 6.9.0 877 * 878 * @see WP_Scripts::get_dependents() 879 * 880 * @param string $id The script ID. 881 * @return string[] Script module IDs. 882 */ 883 private function get_recursive_dependents( string $id ): array { 884 $dependents = array(); 885 $id_queue = array( $id ); 886 $processed = array(); 887 888 while ( ! empty( $id_queue ) ) { 889 $current_id = array_shift( $id_queue ); 890 891 // Skip unregistered or already-processed script modules. 892 if ( ! isset( $this->registered[ $current_id ] ) || isset( $processed[ $current_id ] ) ) { 893 continue; 894 } 895 896 // Mark as processed to guard against infinite loops from circular dependencies. 897 $processed[ $current_id ] = true; 898 899 // Find the direct dependents of the current script. 900 foreach ( $this->get_dependents( $current_id ) as $dependent_id ) { 901 // Only add the dependent if we haven't found it before. 902 if ( ! isset( $dependents[ $dependent_id ] ) ) { 903 $dependents[ $dependent_id ] = true; 904 905 // Add dependency to the queue. 906 $id_queue[] = $dependent_id; 907 } 908 } 909 } 910 911 return array_keys( $dependents ); 912 } 913 914 /** 915 * Sorts the given script module identifiers based on their dependencies. 916 * 917 * It will return a list of script module identifiers sorted in the order 918 * they should be printed, so that dependencies are printed before the script 919 * modules that depend on them. 920 * 921 * @since 6.9.0 922 * 923 * @param string[] $ids The identifiers of the script modules to sort. 924 * @param string[] $import_types Optional. Import types of dependencies to retrieve: 'static', 'dynamic', or both. 925 * Default is both. 926 * @return string[] Sorted list of script module identifiers. 927 */ 928 private function get_sorted_dependencies( array $ids, array $import_types = array( 'static', 'dynamic' ) ): array { 929 $sorted = array(); 930 931 foreach ( $ids as $id ) { 932 $this->sort_item_dependencies( $id, $import_types, $sorted ); 933 } 934 935 return array_unique( $sorted ); 936 } 937 938 /** 939 * Recursively sorts the dependencies for a single script module identifier. 940 * 941 * @since 6.9.0 942 * 943 * @param string $id The identifier of the script module to sort. 944 * @param string[] $import_types Optional. Import types of dependencies to retrieve: 'static', 'dynamic', or both. 945 * @param string[] &$sorted The array of sorted identifiers, passed by reference. 946 * @return bool True on success, false on failure (e.g., missing dependency). 947 */ 948 private function sort_item_dependencies( string $id, array $import_types, array &$sorted ): bool { 949 // If already processed, don't do it again. 950 if ( in_array( $id, $sorted, true ) ) { 951 return true; 952 } 953 954 // If the item doesn't exist, fail. 955 if ( ! isset( $this->registered[ $id ] ) ) { 956 return false; 957 } 958 959 $dependency_ids = array(); 960 foreach ( $this->registered[ $id ]['dependencies'] as $dependency ) { 961 if ( in_array( $dependency['import'], $import_types, true ) ) { 962 $dependency_ids[] = $dependency['id']; 963 } 964 } 965 966 // If the item requires dependencies that do not exist, fail. 967 $missing_dependencies = array_diff( $dependency_ids, array_keys( $this->registered ) ); 968 if ( count( $missing_dependencies ) > 0 ) { 969 if ( ! in_array( $id, $this->modules_with_missing_dependencies, true ) ) { 970 _doing_it_wrong( 971 get_class( $this ) . '::register', 972 sprintf( 973 /* translators: 1: Script module ID, 2: List of missing dependency IDs. */ 974 __( 'The script module with the ID "%1$s" was enqueued with dependencies that are not registered: %2$s.' ), 975 $id, 976 implode( wp_get_list_item_separator(), $missing_dependencies ) 977 ), 978 '6.9.1' 979 ); 980 $this->modules_with_missing_dependencies[] = $id; 981 } 982 983 return false; 984 } 985 986 // Recursively process dependencies. 987 foreach ( $dependency_ids as $dependency_id ) { 988 if ( ! $this->sort_item_dependencies( $dependency_id, $import_types, $sorted ) ) { 989 // A dependency failed to resolve, so this branch fails. 990 return false; 991 } 992 } 993 994 // All dependencies are sorted, so we can now add the current item. 995 $sorted[] = $id; 996 997 return true; 998 } 999 1000 /** 1001 * Gets the data for a registered script module. 1002 * 1003 * @since 7.0.0 1004 * 1005 * @param string $id The script module identifier. 1006 * @return array|null The script module data, or null if not registered. 1007 * @phpstan-return ScriptModule|null 1008 */ 1009 public function get_registered( string $id ): ?array { 1010 return $this->registered[ $id ] ?? null; 1011 } 1012 1013 /** 1014 * Gets the versioned URL for a script module src. 1015 * 1016 * If $version is set to false, the version number is the currently installed 1017 * WordPress version. If $version is set to null, no version is added. 1018 * Otherwise, the string passed in $version is used. 1019 * 1020 * @since 6.5.0 1021 * 1022 * @param string $id The script module identifier. 1023 * @return string The script module src with a version if relevant. 1024 */ 1025 private function get_src( string $id ): string { 1026 if ( ! isset( $this->registered[ $id ] ) ) { 1027 return ''; 1028 } 1029 1030 $script_module = $this->registered[ $id ]; 1031 $src = $script_module['src']; 1032 1033 if ( '' !== $src ) { 1034 if ( false === $script_module['version'] ) { 1035 $src = add_query_arg( 'ver', get_bloginfo( 'version' ), $src ); 1036 } elseif ( null !== $script_module['version'] ) { 1037 $src = add_query_arg( 'ver', $script_module['version'], $src ); 1038 } 1039 } 1040 1041 /** 1042 * Filters the script module source. 1043 * 1044 * @since 6.5.0 1045 * 1046 * @param string $src Module source URL. 1047 * @param string $id Module identifier. 1048 */ 1049 $src = apply_filters( 'script_module_loader_src', $src, $id ); 1050 if ( ! is_string( $src ) ) { 1051 $src = ''; 1052 } 1053 1054 return $src; 1055 } 1056 1057 /** 1058 * Print data associated with Script Modules. 1059 * 1060 * The data will be embedded in the page HTML and can be read by Script Modules on page load. 1061 * 1062 * @since 6.7.0 1063 * 1064 * Data can be associated with a Script Module via the 1065 * {@see "script_module_data_{$module_id}"} filter. 1066 * 1067 * The data for a Script Module will be serialized as JSON in a script tag with an ID of the 1068 * form `wp-script-module-data-{$module_id}`. 1069 */ 1070 public function print_script_module_data(): void { 1071 $module_ids = $this->get_loadable_script_module_ids(); 1072 1073 if ( in_array( '@wordpress/a11y', $module_ids, true ) ) { 1074 $this->a11y_available = true; 1075 } 1076 1077 foreach ( $module_ids as $module_id ) { 1078 /** 1079 * Filters data associated with a given Script Module. 1080 * 1081 * Script Modules may require data that is required for initialization or is essential 1082 * to have immediately available on page load. These are suitable use cases for 1083 * this data. 1084 * 1085 * The dynamic portion of the hook name, `$module_id`, refers to the Script Module ID 1086 * that the data is associated with. 1087 * 1088 * This is best suited to pass essential data that must be available to the module for 1089 * initialization or immediately on page load. It does not replace the REST API or 1090 * fetching data from the client. 1091 * 1092 * Example: 1093 * 1094 * add_filter( 1095 * 'script_module_data_MyScriptModuleID', 1096 * function ( array $data ): array { 1097 * $data['dataForClient'] = 'ok'; 1098 * return $data; 1099 * } 1100 * ); 1101 * 1102 * If the filter returns no data (an empty array), nothing will be embedded in the page. 1103 * 1104 * The data for a given Script Module, if provided, will be JSON serialized in a script 1105 * tag with an ID of the form `wp-script-module-data-{$module_id}`. 1106 * 1107 * The data can be read on the client with a pattern like the following; you are encouraged 1108 * to use this pattern _verbatim_ to avoid common pitfalls or vulnerabilities: 1109 * 1110 * Example: 1111 * 1112 * const dataContainer = document.querySelector( 'script[id="wp-script-module-data-MyScriptModuleID"]' ); 1113 * let data = {}; 1114 * if ( dataContainer instanceof HTMLScriptElement ) { 1115 * try { 1116 * data = JSON.parse( dataContainer.text ); 1117 * } catch {} 1118 * } 1119 * // data.dataForClient === 'ok'; 1120 * initMyScriptModuleWithData( data ); 1121 * 1122 * @since 6.7.0 1123 * 1124 * @param array $data The data associated with the Script Module. 1125 */ 1126 $data = apply_filters( "script_module_data_{$module_id}", array() ); 1127 1128 if ( is_array( $data ) && array() !== $data ) { 1129 /* 1130 * This data will be printed as JSON inside a script tag like this: 1131 * <script type="application/json"></script> 1132 * 1133 * A script tag must be closed by a sequence beginning with `</`. It's impossible to 1134 * close a script tag without using `<`. We ensure that `<` is escaped and `/` can 1135 * remain unescaped, so `</script>` will be printed as `\u003C/script\u00E3`. 1136 * 1137 * - JSON_HEX_TAG: All < and > are converted to \u003C and \u003E. 1138 * - JSON_UNESCAPED_SLASHES: Don't escape /. 1139 * 1140 * If the page will use UTF-8 encoding, it's safe to print unescaped unicode: 1141 * 1142 * - JSON_UNESCAPED_UNICODE: Encode multibyte Unicode characters literally (instead of as `\uXXXX`). 1143 * - JSON_UNESCAPED_LINE_TERMINATORS: The line terminators are kept unescaped when 1144 * JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was 1145 * before PHP 7.1 without this constant. Available as of PHP 7.1.0. 1146 * 1147 * The JSON specification requires encoding in UTF-8, so if the generated HTML page 1148 * is not encoded in UTF-8 then it's not safe to include those literals. They must 1149 * be escaped to avoid encoding issues. 1150 * 1151 * @link https://www.rfc-editor.org/rfc/rfc8259.html for details on encoding requirements. 1152 * @link https://www.php.net/manual/en/json.constants.php for details on these constants. 1153 * @link https://html.spec.whatwg.org/#script-data-state for details on script tag parsing. 1154 */ 1155 $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS; 1156 if ( ! is_utf8_charset() ) { 1157 $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES; 1158 } 1159 1160 wp_print_inline_script_tag( 1161 (string) wp_json_encode( 1162 $data, 1163 $json_encode_flags 1164 ), 1165 array( 1166 'type' => 'application/json', 1167 'id' => "wp-script-module-data-{$module_id}", 1168 ) 1169 ); 1170 } 1171 } 1172 } 1173 1174 /** 1175 * @access private This is only intended to be called by the registered actions. 1176 * 1177 * @since 6.7.0 1178 */ 1179 public function print_a11y_script_module_html() { 1180 if ( ! $this->a11y_available ) { 1181 return; 1182 } 1183 echo '<div style="position:absolute;margin:-1px;padding:0;height:1px;width:1px;overflow:hidden;clip-path:inset(50%);border:0;word-wrap:normal !important;">' 1184 . '<p id="a11y-speak-intro-text" class="a11y-speak-intro-text" hidden>' . esc_html__( 'Notifications' ) . '</p>' 1185 . '<div id="a11y-speak-assertive" class="a11y-speak-region" aria-live="assertive" aria-relevant="additions text" aria-atomic="true"></div>' 1186 . '<div id="a11y-speak-polite" class="a11y-speak-region" aria-live="polite" aria-relevant="additions text" aria-atomic="true"></div>' 1187 . '</div>'; 1188 } 1189 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Tue Nov 17 08:20:01 2026 | Cross-referenced by PHPXref |