Interactivity API: Do not print state if it’s an empty array.

This prunes stores and configurations that are empty arrays, as stores are expected to be JSON objects.
By not printing empty configurations, less redundant data is serialized into the HTML.

Props jonsurrell, luisherranz, darerodz, gziolo, swissspidy.
Fixes #60761.
Built from https://develop.svn.wordpress.org/trunk@57841


git-svn-id: http://core.svn.wordpress.org/trunk@57342 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Pascal Birchler 2024-03-15 12:12:09 +00:00
parent 038465b836
commit bf346251a3
2 changed files with 26 additions and 10 deletions

View File

@ -140,20 +140,36 @@ final class WP_Interactivity_API {
* @since 6.5.0
*/
public function print_client_interactivity_data() {
$store = array();
$has_state = ! empty( $this->state_data );
$has_config = ! empty( $this->config_data );
if ( empty( $this->state_data ) && empty( $this->config_data ) ) {
return;
}
if ( $has_state || $has_config ) {
if ( $has_config ) {
$store['config'] = $this->config_data;
$interactivity_data = array();
$config = array();
foreach ( $this->config_data as $key => $value ) {
if ( ! empty( $value ) ) {
$config[ $key ] = $value;
}
if ( $has_state ) {
$store['state'] = $this->state_data;
}
if ( ! empty( $config ) ) {
$interactivity_data['config'] = $config;
}
$state = array();
foreach ( $this->state_data as $key => $value ) {
if ( ! empty( $value ) ) {
$state[ $key ] = $value;
}
}
if ( ! empty( $state ) ) {
$interactivity_data['state'] = $state;
}
if ( ! empty( $interactivity_data ) ) {
wp_print_inline_script_tag(
wp_json_encode(
$store,
$interactivity_data,
JSON_HEX_TAG | JSON_HEX_AMP
),
array(

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '6.6-alpha-57840';
$wp_version = '6.6-alpha-57841';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.