From 3806b25058372d8311ae20d859cd1d881348ac4a Mon Sep 17 00:00:00 2001 From: Jb Audras Date: Thu, 13 Jun 2024 08:55:47 +0000 Subject: [PATCH] HTML API: Revert using regex in block bindings HTML replacement logic. This changeset reverts part of the changes made in [58298] to avoid using regex that can cause potential bugs. It is indeed safer to revert these changes for now and do the refactoring once the HTML API supports CSS selectors and provides a way to set inner content. It also adds a unit test to cover the regression experienced in https://github.com/WordPress/gutenberg/issues/62347. Follow-up to [58298]. Props santosguillamot, gziolo. Fixes #61385. See #61351. git-svn-id: https://develop.svn.wordpress.org/trunk@58398 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-block.php | 75 ++++++++++++++----- tests/phpunit/tests/block-bindings/render.php | 36 +++++++++ 2 files changed, 94 insertions(+), 17 deletions(-) diff --git a/src/wp-includes/class-wp-block.php b/src/wp-includes/class-wp-block.php index be73c13070149..c6ca8a3bd42be 100644 --- a/src/wp-includes/class-wp-block.php +++ b/src/wp-includes/class-wp-block.php @@ -333,27 +333,68 @@ private function replace_html( string $block_content, string $attribute_name, $s switch ( $block_type->attributes[ $attribute_name ]['source'] ) { case 'html': case 'rich-text': - // Hardcode the selectors and processing until the HTML API is able to read CSS selectors and replace inner HTML. - // TODO: Use the HTML API instead. - if ( 'core/paragraph' === $this->name && 'content' === $attribute_name ) { - $selector = 'p'; - } - if ( 'core/heading' === $this->name && 'content' === $attribute_name ) { - $selector = 'h[1-6]'; + $block_reader = new WP_HTML_Tag_Processor( $block_content ); + + // TODO: Support for CSS selectors whenever they are ready in the HTML API. + // In the meantime, support comma-separated selectors by exploding them into an array. + $selectors = explode( ',', $block_type->attributes[ $attribute_name ]['selector'] ); + // Add a bookmark to the first tag to be able to iterate over the selectors. + $block_reader->next_tag(); + $block_reader->set_bookmark( 'iterate-selectors' ); + + // TODO: This shouldn't be needed when the `set_inner_html` function is ready. + // Store the parent tag and its attributes to be able to restore them later in the button. + // The button block has a wrapper while the paragraph and heading blocks don't. + if ( 'core/button' === $this->name ) { + $button_wrapper = $block_reader->get_tag(); + $button_wrapper_attribute_names = $block_reader->get_attribute_names_with_prefix( '' ); + $button_wrapper_attrs = array(); + foreach ( $button_wrapper_attribute_names as $name ) { + $button_wrapper_attrs[ $name ] = $block_reader->get_attribute( $name ); + } } - if ( 'core/button' === $this->name && 'text' === $attribute_name ) { - // Check if it is a