| [ 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 * @phpstan-ignore method.unused (Kept for plugins that call it through the Reflection API.) 792 */ 793 private function get_marked_for_enqueue(): array { 794 return wp_array_slice_assoc( 795 $this->registered, 796 $this->queue 797 ); 798 } 799 800 /** 801 * Retrieves all the dependencies for the given script module identifiers, filtered by import types. 802 * 803 * It will consolidate an array containing a set of unique dependencies based 804 * on the requested import types: 'static', 'dynamic', or both. This method is 805 * recursive and also retrieves dependencies of the dependencies. 806 * 807 * @since 6.5.0 808 * 809 * @param string[] $ids The identifiers of the script modules for which to gather dependencies. 810 * @param string[] $import_types Optional. Import types of dependencies to retrieve: 'static', 'dynamic', or both. 811 * Default is both. 812 * @return array<string, array<string, mixed>> List of dependencies, keyed by script module identifier. 813 * @phpstan-return array<string, ScriptModule> 814 */ 815 private function get_dependencies( array $ids, array $import_types = array( 'static', 'dynamic' ) ): array { 816 $all_dependencies = array(); 817 $id_queue = $ids; 818 819 while ( ! empty( $id_queue ) ) { 820 $id = array_shift( $id_queue ); 821 if ( ! isset( $this->registered[ $id ] ) ) { 822 continue; 823 } 824 825 foreach ( $this->registered[ $id ]['dependencies'] as $dependency ) { 826 if ( 827 ! isset( $all_dependencies[ $dependency['id'] ] ) && 828 in_array( $dependency['import'], $import_types, true ) && 829 isset( $this->registered[ $dependency['id'] ] ) 830 ) { 831 $all_dependencies[ $dependency['id'] ] = $this->registered[ $dependency['id'] ]; 832 833 // Add this dependency to the list to get dependencies for. 834 $id_queue[] = $dependency['id']; 835 } 836 } 837 } 838 839 return $all_dependencies; 840 } 841 842 /** 843 * Gets all dependents of a script module. 844 * 845 * This is not recursive. 846 * 847 * @since 6.9.0 848 * 849 * @see WP_Scripts::get_dependents() 850 * 851 * @param string $id The script ID. 852 * @return string[] Script module IDs. 853 */ 854 private function get_dependents( string $id ): array { 855 // Check if dependents map for the handle in question is present. If so, use it. 856 if ( isset( $this->dependents_map[ $id ] ) ) { 857 return $this->dependents_map[ $id ]; 858 } 859 860 $dependents = array(); 861 862 // Iterate over all registered scripts, finding dependents of the script passed to this method. 863 foreach ( $this->registered as $registered_id => $args ) { 864 if ( in_array( $id, wp_list_pluck( $args['dependencies'], 'id' ), true ) ) { 865 $dependents[] = $registered_id; 866 } 867 } 868 869 // Add the module's dependents to the map to ease future lookups. 870 $this->dependents_map[ $id ] = $dependents; 871 872 return $dependents; 873 } 874 875 /** 876 * Gets all recursive dependents of a script module. 877 * 878 * @since 6.9.0 879 * 880 * @see WP_Scripts::get_dependents() 881 * 882 * @param string $id The script ID. 883 * @return string[] Script module IDs. 884 */ 885 private function get_recursive_dependents( string $id ): array { 886 $dependents = array(); 887 $id_queue = array( $id ); 888 $processed = array(); 889 890 while ( ! empty( $id_queue ) ) { 891 $current_id = array_shift( $id_queue ); 892 893 // Skip unregistered or already-processed script modules. 894 if ( ! isset( $this->registered[ $current_id ] ) || isset( $processed[ $current_id ] ) ) { 895 continue; 896 } 897 898 // Mark as processed to guard against infinite loops from circular dependencies. 899 $processed[ $current_id ] = true; 900 901 // Find the direct dependents of the current script. 902 foreach ( $this->get_dependents( $current_id ) as $dependent_id ) { 903 // Only add the dependent if we haven't found it before. 904 if ( ! isset( $dependents[ $dependent_id ] ) ) { 905 $dependents[ $dependent_id ] = true; 906 907 // Add dependency to the queue. 908 $id_queue[] = $dependent_id; 909 } 910 } 911 } 912 913 return array_keys( $dependents ); 914 } 915 916 /** 917 * Sorts the given script module identifiers based on their dependencies. 918 * 919 * It will return a list of script module identifiers sorted in the order 920 * they should be printed, so that dependencies are printed before the script 921 * modules that depend on them. 922 * 923 * @since 6.9.0 924 * 925 * @param string[] $ids The identifiers of the script modules to sort. 926 * @param string[] $import_types Optional. Import types of dependencies to retrieve: 'static', 'dynamic', or both. 927 * Default is both. 928 * @return string[] Sorted list of script module identifiers. 929 */ 930 private function get_sorted_dependencies( array $ids, array $import_types = array( 'static', 'dynamic' ) ): array { 931 $sorted = array(); 932 933 foreach ( $ids as $id ) { 934 $this->sort_item_dependencies( $id, $import_types, $sorted ); 935 } 936 937 return array_unique( $sorted ); 938 } 939 940 /** 941 * Recursively sorts the dependencies for a single script module identifier. 942 * 943 * @since 6.9.0 944 * 945 * @param string $id The identifier of the script module to sort. 946 * @param string[] $import_types Optional. Import types of dependencies to retrieve: 'static', 'dynamic', or both. 947 * @param string[] &$sorted The array of sorted identifiers, passed by reference. 948 * @return bool True on success, false on failure (e.g., missing dependency). 949 */ 950 private function sort_item_dependencies( string $id, array $import_types, array &$sorted ): bool { 951 // If already processed, don't do it again. 952 if ( in_array( $id, $sorted, true ) ) { 953 return true; 954 } 955 956 // If the item doesn't exist, fail. 957 if ( ! isset( $this->registered[ $id ] ) ) { 958 return false; 959 } 960 961 $dependency_ids = array(); 962 foreach ( $this->registered[ $id ]['dependencies'] as $dependency ) { 963 if ( in_array( $dependency['import'], $import_types, true ) ) { 964 $dependency_ids[] = $dependency['id']; 965 } 966 } 967 968 // If the item requires dependencies that do not exist, fail. 969 $missing_dependencies = array_diff( $dependency_ids, array_keys( $this->registered ) ); 970 if ( count( $missing_dependencies ) > 0 ) { 971 if ( ! in_array( $id, $this->modules_with_missing_dependencies, true ) ) { 972 _doing_it_wrong( 973 get_class( $this ) . '::register', 974 sprintf( 975 /* translators: 1: Script module ID, 2: List of missing dependency IDs. */ 976 __( 'The script module with the ID "%1$s" was enqueued with dependencies that are not registered: %2$s.' ), 977 $id, 978 implode( wp_get_list_item_separator(), $missing_dependencies ) 979 ), 980 '6.9.1' 981 ); 982 $this->modules_with_missing_dependencies[] = $id; 983 } 984 985 return false; 986 } 987 988 // Recursively process dependencies. 989 foreach ( $dependency_ids as $dependency_id ) { 990 if ( ! $this->sort_item_dependencies( $dependency_id, $import_types, $sorted ) ) { 991 // A dependency failed to resolve, so this branch fails. 992 return false; 993 } 994 } 995 996 // All dependencies are sorted, so we can now add the current item. 997 $sorted[] = $id; 998 999 return true; 1000 } 1001 1002 /** 1003 * Gets the data for a registered script module. 1004 * 1005 * @since 7.0.0 1006 * 1007 * @param string $id The script module identifier. 1008 * @return array|null The script module data, or null if not registered. 1009 * @phpstan-return ScriptModule|null 1010 */ 1011 public function get_registered( string $id ): ?array { 1012 return $this->registered[ $id ] ?? null; 1013 } 1014 1015 /** 1016 * Gets the versioned URL for a script module src. 1017 * 1018 * If $version is set to false, the version number is the currently installed 1019 * WordPress version. If $version is set to null, no version is added. 1020 * Otherwise, the string passed in $version is used. 1021 * 1022 * @since 6.5.0 1023 * 1024 * @param string $id The script module identifier. 1025 * @return string The script module src with a version if relevant. 1026 */ 1027 private function get_src( string $id ): string { 1028 if ( ! isset( $this->registered[ $id ] ) ) { 1029 return ''; 1030 } 1031 1032 $script_module = $this->registered[ $id ]; 1033 $src = $script_module['src']; 1034 1035 if ( '' !== $src ) { 1036 if ( false === $script_module['version'] ) { 1037 $src = add_query_arg( 'ver', get_bloginfo( 'version' ), $src ); 1038 } elseif ( null !== $script_module['version'] ) { 1039 $src = add_query_arg( 'ver', $script_module['version'], $src ); 1040 } 1041 } 1042 1043 /** 1044 * Filters the script module source. 1045 * 1046 * @since 6.5.0 1047 * 1048 * @param string $src Module source URL. 1049 * @param string $id Module identifier. 1050 */ 1051 $src = apply_filters( 'script_module_loader_src', $src, $id ); 1052 if ( ! is_string( $src ) ) { 1053 $src = ''; 1054 } 1055 1056 return $src; 1057 } 1058 1059 /** 1060 * Print data associated with Script Modules. 1061 * 1062 * The data will be embedded in the page HTML and can be read by Script Modules on page load. 1063 * 1064 * @since 6.7.0 1065 * 1066 * Data can be associated with a Script Module via the 1067 * {@see "script_module_data_{$module_id}"} filter. 1068 * 1069 * The data for a Script Module will be serialized as JSON in a script tag with an ID of the 1070 * form `wp-script-module-data-{$module_id}`. 1071 */ 1072 public function print_script_module_data(): void { 1073 $module_ids = $this->get_loadable_script_module_ids(); 1074 1075 if ( in_array( '@wordpress/a11y', $module_ids, true ) ) { 1076 $this->a11y_available = true; 1077 } 1078 1079 foreach ( $module_ids as $module_id ) { 1080 /** 1081 * Filters data associated with a given Script Module. 1082 * 1083 * Script Modules may require data that is required for initialization or is essential 1084 * to have immediately available on page load. These are suitable use cases for 1085 * this data. 1086 * 1087 * The dynamic portion of the hook name, `$module_id`, refers to the Script Module ID 1088 * that the data is associated with. 1089 * 1090 * This is best suited to pass essential data that must be available to the module for 1091 * initialization or immediately on page load. It does not replace the REST API or 1092 * fetching data from the client. 1093 * 1094 * Example: 1095 * 1096 * add_filter( 1097 * 'script_module_data_MyScriptModuleID', 1098 * function ( array $data ): array { 1099 * $data['dataForClient'] = 'ok'; 1100 * return $data; 1101 * } 1102 * ); 1103 * 1104 * If the filter returns no data (an empty array), nothing will be embedded in the page. 1105 * 1106 * The data for a given Script Module, if provided, will be JSON serialized in a script 1107 * tag with an ID of the form `wp-script-module-data-{$module_id}`. 1108 * 1109 * The data can be read on the client with a pattern like the following; you are encouraged 1110 * to use this pattern _verbatim_ to avoid common pitfalls or vulnerabilities: 1111 * 1112 * Example: 1113 * 1114 * const dataContainer = document.querySelector( 'script[id="wp-script-module-data-MyScriptModuleID"]' ); 1115 * let data = {}; 1116 * if ( dataContainer instanceof HTMLScriptElement ) { 1117 * try { 1118 * data = JSON.parse( dataContainer.text ); 1119 * } catch {} 1120 * } 1121 * // data.dataForClient === 'ok'; 1122 * initMyScriptModuleWithData( data ); 1123 * 1124 * @since 6.7.0 1125 * 1126 * @param array $data The data associated with the Script Module. 1127 */ 1128 $data = apply_filters( "script_module_data_{$module_id}", array() ); 1129 1130 if ( is_array( $data ) && array() !== $data ) { 1131 /* 1132 * This data will be printed as JSON inside a script tag like this: 1133 * <script type="application/json"></script> 1134 * 1135 * A script tag must be closed by a sequence beginning with `</`. It's impossible to 1136 * close a script tag without using `<`. We ensure that `<` is escaped and `/` can 1137 * remain unescaped, so `</script>` will be printed as `\u003C/script\u00E3`. 1138 * 1139 * - JSON_HEX_TAG: All < and > are converted to \u003C and \u003E. 1140 * - JSON_UNESCAPED_SLASHES: Don't escape /. 1141 * 1142 * If the page will use UTF-8 encoding, it's safe to print unescaped unicode: 1143 * 1144 * - JSON_UNESCAPED_UNICODE: Encode multibyte Unicode characters literally (instead of as `\uXXXX`). 1145 * - JSON_UNESCAPED_LINE_TERMINATORS: The line terminators are kept unescaped when 1146 * JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was 1147 * before PHP 7.1 without this constant. Available as of PHP 7.1.0. 1148 * 1149 * The JSON specification requires encoding in UTF-8, so if the generated HTML page 1150 * is not encoded in UTF-8 then it's not safe to include those literals. They must 1151 * be escaped to avoid encoding issues. 1152 * 1153 * @link https://www.rfc-editor.org/rfc/rfc8259.html for details on encoding requirements. 1154 * @link https://www.php.net/manual/en/json.constants.php for details on these constants. 1155 * @link https://html.spec.whatwg.org/#script-data-state for details on script tag parsing. 1156 */ 1157 $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS; 1158 if ( ! is_utf8_charset() ) { 1159 $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES; 1160 } 1161 1162 wp_print_inline_script_tag( 1163 (string) wp_json_encode( 1164 $data, 1165 $json_encode_flags 1166 ), 1167 array( 1168 'type' => 'application/json', 1169 'id' => "wp-script-module-data-{$module_id}", 1170 ) 1171 ); 1172 } 1173 } 1174 } 1175 1176 /** 1177 * @access private This is only intended to be called by the registered actions. 1178 * 1179 * @since 6.7.0 1180 */ 1181 public function print_a11y_script_module_html() { 1182 if ( ! $this->a11y_available ) { 1183 return; 1184 } 1185 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;">' 1186 . '<p id="a11y-speak-intro-text" class="a11y-speak-intro-text" hidden>' . esc_html__( 'Notifications' ) . '</p>' 1187 . '<div id="a11y-speak-assertive" class="a11y-speak-region" aria-live="assertive" aria-relevant="additions text" aria-atomic="true"></div>' 1188 . '<div id="a11y-speak-polite" class="a11y-speak-region" aria-live="polite" aria-relevant="additions text" aria-atomic="true"></div>' 1189 . '</div>'; 1190 } 1191 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Wed Dec 2 08:20:02 2026 | Cross-referenced by PHPXref |