diff --git a/src/wp-includes/interactivity-api/class-wp-interactivity-api-directives-processor.php b/src/wp-includes/interactivity-api/class-wp-interactivity-api-directives-processor.php index bac24fba19526..f3aeae5d7df30 100644 --- a/src/wp-includes/interactivity-api/class-wp-interactivity-api-directives-processor.php +++ b/src/wp-includes/interactivity-api/class-wp-interactivity-api-directives-processor.php @@ -71,30 +71,52 @@ public function get_content_between_balanced_template_tags() { * @return bool Whether the content was successfully replaced. */ public function set_content_between_balanced_tags( string $new_content ): bool { - return $this->set_raw_content_between_balanced_tags( esc_html( $new_content ) ); + $positions = $this->get_after_opener_tag_and_before_closer_tag_positions( true ); + if ( ! $positions ) { + return false; + } + list( $after_opener_tag, $before_closer_tag ) = $positions; + + $this->lexical_updates[] = new WP_HTML_Text_Replacement( + $after_opener_tag, + $before_closer_tag - $after_opener_tag, + esc_html( $new_content ) + ); + + return true; } /** - * Sets the content between two balanced tags, writing it as given. + * Moves to the matching closer tag of the current opener tag and replaces + * the content between them. * - * Unlike {@see WP_Interactivity_API_Directives_Processor::set_content_between_balanced_tags()}, - * it does not escape the content. Like it, it replaces the content between - * the current opener tag and its matching closer tag, and it rewinds to the - * opener tag. + * The matching closer tag is found as in + * {@see WP_Interactivity_API_Directives_Processor::next_balanced_tag_closer_tag()}. + * The new content is written as given. Unlike + * {@see WP_Interactivity_API_Directives_Processor::set_content_between_balanced_tags()}, + * it neither applies the pending updates nor seeks back to the opener tag, + * so it can be called any number of times on the same processor. * * @since 7.2.0 * * @access private * - * @param string $new_content The markup to replace the content between the matching tags. It is written as is. - * @return bool Whether the content was successfully replaced. + * @param string $new_content The markup to replace the content between the matching tags with. + * @return bool Whether the matching closer tag was found. When it is not found, the cursor is at the end + * of the HTML and nothing is replaced. */ - public function set_raw_content_between_balanced_tags( string $new_content ): bool { - $positions = $this->get_after_opener_tag_and_before_closer_tag_positions( true ); - if ( ! $positions ) { + public function skip_to_balanced_tag_closer( string $new_content ): bool { + $bookmarks = $this->get_balanced_tag_bookmarks(); + if ( ! $bookmarks ) { return false; } - list( $after_opener_tag, $before_closer_tag ) = $positions; + list( $opener_tag, $closer_tag ) = $bookmarks; + + $after_opener_tag = $this->bookmarks[ $opener_tag ]->start + $this->bookmarks[ $opener_tag ]->length; + $before_closer_tag = $this->bookmarks[ $closer_tag ]->start; + + $this->release_bookmark( $opener_tag ); + $this->release_bookmark( $closer_tag ); $this->lexical_updates[] = new WP_HTML_Text_Replacement( $after_opener_tag, diff --git a/src/wp-includes/interactivity-api/class-wp-interactivity-api.php b/src/wp-includes/interactivity-api/class-wp-interactivity-api.php index d8f11e2d05fe3..1dd83a5eab7b4 100644 --- a/src/wp-includes/interactivity-api/class-wp-interactivity-api.php +++ b/src/wp-includes/interactivity-api/class-wp-interactivity-api.php @@ -52,6 +52,15 @@ final class WP_Interactivity_API { 'data-wp-each' => 'data_wp_each_processor', ); + /** + * Matches a directive value that names its namespace, as in + * `myPlugin::state.foo`, capturing the namespace and the rest of the value. + * + * @since 7.2.0 + * @var string + */ + private const NAMESPACED_VALUE_REGEX = '/^([\w\/-]+)::(.+)$/D'; + /** * Holds the initial state of the different Interactivity API stores. * @@ -130,6 +139,27 @@ final class WP_Interactivity_API { */ private $namespace_stack = null; + /** + * Stack of the namespaces that `data-wp-interactive` directives name, in + * step with the namespace stack, as the client reads them. + * + * This is only available during directive processing, otherwise it is `null`. + * + * Unlike the namespace stack, the entry of an element that carries the + * attribute named exactly `data-wp-interactive` never falls back to an + * enclosing namespace. It is `null` when the attribute names none: it has no + * value or an empty one, its JSON object holds no string `namespace`, or the + * namespace is `__proto__`, `constructor` or `prototype`. An element with + * only suffixed or unique-ID entries is no island, so its entry repeats the + * enclosing one. Only `data-wp-html` reads it, as the client resolves every + * directive. + * + * @since 7.2.0 + * @var array|null + * @phpstan-var list|null + */ + private $island_namespace_stack = null; + /** * Stack of contexts defined by `data-wp-context` directives, in * the order they are processed. @@ -153,7 +183,8 @@ final class WP_Interactivity_API { /** * Marker that makes the placeholders of the current `process_directives()` - * call recognizable. It occurs nowhere in the HTML that call received. + * call recognizable. It occurs nowhere in the HTML that call received, and + * it differs from the marker of any call that the current one runs inside. * * @since 7.2.0 * @var string @@ -483,6 +514,9 @@ public function add_client_navigation_support_to_script_module( string $script_m * @since 6.5.0 * @since 7.2.0 The output includes the trusted HTML that `data-wp-html` renders. That HTML is * added once the whole call has finished, so it is never processed. + * @since 7.2.0 It can be called while another call is processing, as from a derived-state + * closure that renders markup. That call processes its HTML on its own, and the + * processing of the other call continues as before it once it returns. * * @param string $html The HTML content to process. * @return string The processed HTML content. It returns the original content when the HTML contains unbalanced tags. @@ -492,30 +526,49 @@ public function process_directives( string $html ): string { return $html; } - $this->namespace_stack = array(); - $this->context_stack = array(); + $caller_state = array( + $this->namespace_stack, + $this->island_namespace_stack, + $this->context_stack, + $this->current_element, + $this->html_placeholder_marker, + $this->html_placeholders, + ); + + $this->namespace_stack = array(); + $this->island_namespace_stack = array(); + $this->context_stack = array(); + $this->current_element = null; /* * The trusted HTML of `data-wp-html` hosts never takes part in the * processing: each host receives a placeholder comment, and the comments * are replaced by their HTML once the result is known. The marker that * identifies them is chosen so that it occurs nowhere in the input, which - * makes it impossible for the input to contain a placeholder. + * makes it impossible for the input to contain a placeholder. It is also + * longer than the marker of any call this one runs inside, so their + * placeholders never coincide. */ - $marker = 'wp-interactivity-dangerous-html'; + $marker = '' === $this->html_placeholder_marker ? 'wp-interactivity-dangerous-html' : $this->html_placeholder_marker . '_'; while ( str_contains( $html, $marker ) ) { $marker .= '_'; } $this->html_placeholder_marker = $marker; $this->html_placeholders = array(); - $result = $this->_process_directives( $html ); - - $this->namespace_stack = null; - $this->context_stack = null; - - $placeholders = $this->html_placeholders; - $this->html_placeholders = array(); + try { + $result = $this->_process_directives( $html ); + $placeholders = $this->html_placeholders; + } finally { + list( + $this->namespace_stack, + $this->island_namespace_stack, + $this->context_stack, + $this->current_element, + $this->html_placeholder_marker, + $this->html_placeholders + ) = $caller_state; + } if ( null === $result ) { return $html; @@ -530,7 +583,7 @@ public function process_directives( string $html ): string { * and updates the markup accordingly. * * It uses the WP_Interactivity_API instance's context and namespace stacks, - * which are shared between all calls. + * which every call made during one `process_directives()` call shares. * * This method returns null if the HTML contains unbalanced tags. * @@ -551,8 +604,9 @@ private function _process_directives( string $html ) { * Save the current size for each stack to restore them in case * the processing finds unbalanced tags. */ - $namespace_stack_size = count( $this->namespace_stack ); - $context_stack_size = count( $this->context_stack ); + $namespace_stack_size = count( $this->namespace_stack ); + $island_namespace_stack_size = count( $this->island_namespace_stack ); + $context_stack_size = count( $this->context_stack ); while ( $p->next_tag( array( 'tag_closers' => 'visit' ) ) ) { $tag_name = $p->get_tag(); @@ -652,7 +706,15 @@ private function _process_directives( string $html ) { 'attributes' => $element_attrs, ); + $is_content_consumed = false; + foreach ( $modes as $mode => $should_run ) { + // An element whose content was consumed is completed as at its closer tag. + if ( 'exit' === $mode && $is_content_consumed ) { + array_pop( $tag_stack ); + $should_run = true; + } + if ( ! $should_run ) { continue; } @@ -671,6 +733,16 @@ private function _process_directives( string $html ) { : array( $this, self::$directive_processors[ $directive_prefix ] ); call_user_func_array( $func, array( $p, $mode, &$tag_stack ) ); + + /* + * A processor that consumes the content of the element it enters + * leaves the cursor on the element's closer tag, where no other + * processor enters. `data-wp-each` completes its `template` itself. + */ + if ( 'enter' === $mode && $p->is_tag_closer() ) { + $is_content_consumed = 'data-wp-each' !== $directive_prefix; + break; + } } } @@ -681,6 +753,7 @@ private function _process_directives( string $html ) { if ( $unbalanced ) { // Reset the namespace and context stacks to their previous values. array_splice( $this->namespace_stack, $namespace_stack_size ); + array_splice( $this->island_namespace_stack, $island_namespace_stack_size ); array_splice( $this->context_stack, $context_stack_size ); } @@ -1065,14 +1138,16 @@ function ( $matches ) { * stack so that it's available for the nested interactivity elements. * * @since 6.5.0 + * @since 7.2.0 Also records the namespace that the directive itself names, for `data-wp-html`. * * @param WP_Interactivity_API_Directives_Processor $p The directives processor instance. * @param string $mode Whether the processing is entering or exiting the tag. */ private function data_wp_interactive_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) { - // When exiting tags, it removes the last namespace from the stack. + // When exiting tags, it removes the last namespace from the stacks. if ( 'exit' === $mode ) { array_pop( $this->namespace_stack ); + array_pop( $this->island_namespace_stack ); return; } @@ -1088,6 +1163,7 @@ private function data_wp_interactive_processor( WP_Interactivity_API_Directives_ * contained a valid namespace. */ $new_namespace = null; + $decoded_json = null; if ( is_string( $attribute_value ) && ! empty( $attribute_value ) ) { $decoded_json = json_decode( $attribute_value, true ); if ( is_array( $decoded_json ) ) { @@ -1099,6 +1175,25 @@ private function data_wp_interactive_processor( WP_Interactivity_API_Directives_ $this->namespace_stack[] = ( $new_namespace && 1 === preg_match( '/^([\w\-_\/]+)/', $new_namespace ) ) ? $new_namespace : end( $this->namespace_stack ); + + /* + * Only the attribute named exactly `data-wp-interactive` makes an island, + * so an element with only suffixed or unique-ID entries keeps the + * enclosing island's namespace. The client reads a JSON object only when + * the value starts with `{`, and keeps any other value as given. + */ + if ( null === $attribute_value ) { + $this->island_namespace_stack[] = array_last( $this->island_namespace_stack ); + return; + } + $island_namespace = is_string( $attribute_value ) ? $attribute_value : null; + if ( is_array( $decoded_json ) && 1 === preg_match( '/^\s*\{/', $attribute_value ) ) { + $island_namespace = is_string( $decoded_json['namespace'] ?? null ) ? $decoded_json['namespace'] : null; + } + if ( '' === $island_namespace || ( null !== $island_namespace && self::is_reserved_word( $island_namespace ) ) ) { + $island_namespace = null; + } + $this->island_namespace_stack[] = $island_namespace; } /** @@ -1518,18 +1613,27 @@ private function data_wp_text_processor( WP_Interactivity_API_Directives_Process /** * Processes the `data-wp-html` directive. * - * It sets the content of the current HTML element to the HTML of the token - * that its associated reference resolves to. The HTML is written as given and - * the directives inside it are not processed. See + * Only an entry without a suffix or a unique ID controls the content: the + * HTML of the token its reference resolves to, written as given, or nothing + * for any other value. No directive inside that content is processed. See * {@see wp_interactivity_as_dangerous_html()} for the risks of marking HTML * as trusted. * - * The element is left as it would be without the directive, and a notice - * reports the reason, when the reference does not resolve to a token, the - * element cannot hold content, or the element also carries `data-wp-text` or, - * for a `template`, `data-wp-each`. A reference that resolves to `null` - * declines without a notice. Only the entry without a suffix or a unique ID - * is processed. + * HTML that closes the element, or that the browser moves out of it, such + * as a `div` in a `p`, is still written as given. The browser places the part + * that escapes after the element, where the client hydrates it as ordinary + * markup although the server did not process its directives. + * + * A value other than a token or `null` raises a notice. A reference that + * resolves to nothing does not. + * + * The element is processed as if it had no `data-wp-html` directive when it + * also carries `data-wp-text`, `data-wp-each` or `data-wp-router-region`, which + * raises a notice, or when its entries all have a suffix or unique ID or are + * dropped by the client. The directive is also ignored, with a notice, on void + * elements and on `script`, `style`, `textarea`, `title`, `iframe`, `xmp`, + * `noembed` and `noframes` elements. Their content is preserved and the + * reference is not evaluated. * * @since 7.2.0 * @@ -1541,27 +1645,40 @@ private function data_wp_html_processor( WP_Interactivity_API_Directives_Process return; } - // Get the first valid `data-wp-html` entry without suffix or unique ID. - $valid_entry = array_find( - $this->get_directive_entries( $p, 'html' ), - fn( $entry ) => null === $entry['suffix'] && null === $entry['unique_id'] && ! empty( $entry['value'] ) - ); + $directives = $this->get_client_directives( $p ); + if ( empty( $directives['html'] ) ) { + return; + } - if ( null === $valid_entry ) { + foreach ( array( 'text', 'each', 'router-region' ) as $conflicting_prefix ) { + if ( ! empty( $directives[ $conflicting_prefix ] ) ) { + _doing_it_wrong( + __METHOD__, + sprintf( + /* translators: %s: The directive combined with data-wp-html, such as data-wp-text. */ + __( 'The "data-wp-html" directive cannot be combined with the "%s" directive on the same element. The "data-wp-html" directive is ignored.' ), + esc_html( 'data-wp-' . $conflicting_prefix ) + ), + '7.2.0' + ); + return; + } + } + + $host_entry = array_find( + $directives['html'], + fn( $entry ) => null === $entry['suffix'] && null === $entry['unique_id'] + ); + if ( null === $host_entry ) { return; } - /* - * The structural reasons decline without evaluating the reference, so - * their notice does not depend on the value and no derived state runs - * for a result that would be discarded. - */ if ( ! $p->has_and_visits_its_closer_tag() ) { _doing_it_wrong( __METHOD__, sprintf( /* translators: %s: The HTML tag name of the element, in lowercase. */ - __( 'The "data-wp-html" directive cannot set the content of a <%s> element because it cannot hold content. The element is left as it is.' ), + __( 'The "data-wp-html" directive is not supported on <%s> elements. The directive is ignored.' ), esc_html( strtolower( $p->get_tag() ) ) ), '7.2.0' @@ -1569,43 +1686,19 @@ private function data_wp_html_processor( WP_Interactivity_API_Directives_Process return; } - $combined_directive = null; - if ( array_find( $this->get_directive_entries( $p, 'text' ), fn( $entry ) => null === $entry['suffix'] && null === $entry['unique_id'] ) ) { - $combined_directive = 'data-wp-text'; - } elseif ( 'TEMPLATE' === $p->get_tag() && ! empty( $this->get_directive_entries( $p, 'each' ) ) ) { - $combined_directive = 'data-wp-each'; - } - if ( null !== $combined_directive ) { + $result = $this->resolve_html_reference( $host_entry['value'] ); + $html = WP_Interactivity_Dangerous_HTML::get_html( $result ); + + if ( null === $html && null !== $result ) { _doing_it_wrong( __METHOD__, - sprintf( - /* translators: %s: The directive combined with data-wp-html, such as data-wp-text. */ - __( 'The "data-wp-html" directive cannot be combined with the "%s" directive on the same element. The "data-wp-html" directive is ignored.' ), - esc_html( $combined_directive ) - ), + __( 'The "data-wp-html" directive requires a reference that resolves to the value returned by wp_interactivity_as_dangerous_html(). Other values, such as strings of HTML, are not rendered and the content of the element is removed.' ), '7.2.0' ); - return; - } - - /* - * An entry value that is not a string is a JSON literal written in the - * markup, which no store property can be named by, so it is not evaluated. - */ - $result = is_string( $valid_entry['value'] ) ? $this->evaluate( $valid_entry ) : $valid_entry['value']; - - // Unresolved references and `null` values keep the element as it is, as they do in the client. - if ( null === $result ) { - return; } - $html = WP_Interactivity_Dangerous_HTML::get_html( $result ); if ( null === $html ) { - _doing_it_wrong( - __METHOD__, - __( 'The "data-wp-html" directive requires a reference that resolves to the value returned by wp_interactivity_as_dangerous_html(). Other values, such as strings of HTML, are not rendered and the element is left as it is.' ), - '7.2.0' - ); + $p->skip_to_balanced_tag_closer( '' ); return; } @@ -1615,11 +1708,132 @@ private function data_wp_html_processor( WP_Interactivity_API_Directives_Process * processors, and the marker in it occurs nowhere in the input. */ $placeholder = ''; - if ( $p->set_raw_content_between_balanced_tags( $placeholder ) ) { + if ( $p->skip_to_balanced_tag_closer( $placeholder ) ) { $this->html_placeholders[ $placeholder ] = $html; } } + /** + * Gets the directives on the current element that the client keeps. + * + * The client drops a directive when a reserved word (`__proto__`, + * `constructor` or `prototype`) is its prefix, any `--`-separated part of its + * suffix or its unique ID, ignoring case and leading and trailing dashes, or + * when its value names a reserved word as its namespace. + * + * @since 7.2.0 + * + * @param WP_Interactivity_API_Directives_Processor $p The directives processor instance. + * @return array[] The directives by prefix, such as `html`, each in the order of the element's attributes, + * with their raw values. + * @phpstan-return array> + */ + private function get_client_directives( WP_Interactivity_API_Directives_Processor $p ): array { + $directives = array(); + foreach ( $p->get_attribute_names_with_prefix( 'data-wp-' ) ?? array() as $attribute_name ) { + $parsed_directive = $this->parse_directive_name( $attribute_name ); + if ( null === $parsed_directive ) { + continue; + } + + $name_parts = array( $parsed_directive['prefix'] ); + if ( null !== $parsed_directive['suffix'] ) { + array_push( $name_parts, ...explode( '--', $parsed_directive['suffix'] ) ); + } + if ( null !== $parsed_directive['unique_id'] ) { + $name_parts[] = $parsed_directive['unique_id']; + } + foreach ( $name_parts as $name_part ) { + if ( self::is_reserved_word( strtolower( trim( $name_part, '-' ) ) ) ) { + continue 2; + } + } + + $value = $p->get_attribute( $attribute_name ); + if ( is_string( $value ) && 1 === preg_match( self::NAMESPACED_VALUE_REGEX, $value, $matches ) && self::is_reserved_word( $matches[1] ) ) { + continue; + } + + $directives[ $parsed_directive['prefix'] ][] = array( + 'suffix' => $parsed_directive['suffix'], + 'unique_id' => $parsed_directive['unique_id'], + 'value' => $value, + ); + } + return $directives; + } + + /** + * Resolves the reference of a `data-wp-html` directive as the client does. + * + * The reference is the raw attribute value, never decoded as JSON: an + * optional `::`, an optional `!` and a dot-separated path. + * Without `::`, the namespace is the one that the nearest + * `data-wp-interactive` directive names, never one inherited from a further + * one. When it names none, the reference resolves to `null`. It also + * resolves to `null`, without being evaluated, when its path is empty or + * starts with a second `!`, which names no property, or when a segment of + * its path is a reserved word (`__proto__`, `constructor` or `prototype`). + * The `!` applies after that, so `!state.x.constructor` resolves to `true`. + * + * @since 7.2.0 + * + * @param string|true $reference The attribute value. It is `true` when the attribute has no value. + * @return mixed The value the reference resolves to, or `null` if it resolves to nothing. + */ + private function resolve_html_reference( $reference ) { + if ( ! is_string( $reference ) ) { + return null; + } + + if ( 1 === preg_match( self::NAMESPACED_VALUE_REGEX, $reference, $matches ) ) { + list( , $namespace, $path ) = $matches; + } else { + $namespace = array_last( $this->island_namespace_stack ?? array() ); + $path = $reference; + } + + $should_negate_value = false; + if ( str_starts_with( $path, '!' ) ) { + $path = substr( $path, 1 ); + $should_negate_value = '' !== $path; + } + + if ( + '' === $path || + str_starts_with( $path, '!' ) || + null !== array_find( explode( '.', $path ), fn( $segment ) => self::is_reserved_word( $segment ) ) + ) { + $value = null; + } else { + $value = $this->evaluate( + array( + 'namespace' => $namespace, + 'value' => $path, + ) + ); + } + + return $should_negate_value ? ! $value : $value; + } + + /** + * Checks whether a name is one the client never resolves or keeps as a + * directive name part, because it would reach the prototype of an object. + * + * @since 7.2.0 + * + * @param string $name The name. + * @return bool Whether the name is `__proto__`, `constructor` or `prototype`. + */ + private static function is_reserved_word( string $name ): bool { + return '__proto__' === $name || 'constructor' === $name || 'prototype' === $name; + } + /** * Returns the CSS styles for animating the top loading bar in the router. * diff --git a/tests/phpunit/tests/interactivity-api/wpInteractivityAPI-wp-html.php b/tests/phpunit/tests/interactivity-api/wpInteractivityAPI-wp-html.php index ac6dc6625b67b..dee43176fa721 100644 --- a/tests/phpunit/tests/interactivity-api/wpInteractivityAPI-wp-html.php +++ b/tests/phpunit/tests/interactivity-api/wpInteractivityAPI-wp-html.php @@ -28,12 +28,13 @@ class Tests_WP_Interactivity_API_WP_Html extends WP_UnitTestCase { const MARKER_HTML = 'marker-7f3a'; /** - * Children with directives, for a host that declines to keep and process. + * Children with directives, for an element whose content is processed or + * replaced. */ const CHILDREN = 'xy'; /** - * The children of a declining host once processed. + * The children once processed. */ const PROCESSED_CHILDREN = 'processedy'; @@ -353,9 +354,9 @@ public function test_host_resolves_in_its_own_context() { } /** - * Tests that a value that is not a token keeps the host's content, with the - * directives in it processed, and raises exactly one notice, which names the - * function that creates tokens. + * Tests that a value that is not a token empties the host without processing + * its content, and raises exactly one notice, which names the function that + * creates tokens. * * @ticket 66246 * @@ -364,72 +365,183 @@ public function test_host_resolves_in_its_own_context() { * * @dataProvider data_values_that_are_not_tokens * - * @param mixed $value The value of `state.html`. + * @param string $attributes The attributes of the host. + * @param array $state The state of the `test` namespace. */ - public function test_value_that_is_not_a_token_declines_with_one_notice( $value ) { + public function test_value_that_is_not_a_token_empties_the_host_with_one_notice( string $attributes, array $state ) { $this->setExpectedIncorrectUsage( self::NOTICE_SOURCE ); - $this->set_state( array( 'html' => $value ) ); + $this->set_state( $state ); - $output = wp_interactivity_process_directives( $this->page( '
' . self::CHILDREN . '
' ) ); + $output = wp_interactivity_process_directives( $this->page( '
' . self::CHILDREN . '
' ) ); - $this->assertSame( - $this->processed_page( '
' . self::PROCESSED_CHILDREN . '
' ), - $output - ); + $this->assertSame( $this->processed_page( '
' ), $output ); $this->assertCount( 1, $this->html_notice_messages(), 'Expected exactly one data-wp-html notice.' ); $this->assertCount( 1, $this->notices, 'Expected no other notice.' ); $this->assertStringContainsString( 'wp_interactivity_as_dangerous_html()', $this->html_notice_messages()[0] ); + $this->assertSame( array(), $this->announced_paths(), 'Expected no closure to run.' ); } /** * Data provider. * - * @return array Data provider. + * @return array Data provider. */ public static function data_values_that_are_not_tokens(): array { + $token = wp_interactivity_as_dangerous_html( '

Hi

' ); + return array( - 'string of HTML' => array( '

Hi

' ), - 'empty string' => array( '' ), - 'integer' => array( 1 ), - 'boolean' => array( true ), - 'false' => array( false ), - 'array' => array( array( '

Hi

' ) ), - 'array with an html key' => array( array( 'html' => '

Hi

' ) ), - 'stdClass' => array( new stdClass() ), - 'json_decode object' => array( json_decode( '{"html":"

Hi

"}' ) ), - 'other object' => array( new ArrayObject( array( '

Hi

' ) ) ), - 'json_decode of a token' => array( json_decode( wp_json_encode( new WP_Interactivity_Dangerous_HTML( '

Hi

' ) ) ) ), - 'marker decoded as an array' => array( json_decode( '{"wpServerHtml":true}', true ) ), - 'closure returning a string' => array( - static function () { - return '

Hi

'; + 'string of HTML' => array( 'data-wp-html="state.html"', array( 'html' => '

Hi

' ) ), + 'integer' => array( 'data-wp-html="state.html"', array( 'html' => 1 ) ), + 'false' => array( 'data-wp-html="state.html"', array( 'html' => false ) ), + 'list' => array( 'data-wp-html="state.html"', array( 'html' => array( '

Hi

' ) ) ), + 'marker imitated by an array' => array( 'data-wp-html="state.html"', array( 'html' => array( 'wpServerHtml' => true ) ) ), + 'marker imitated by an object' => array( + 'data-wp-html="state.html"', + array( + 'html' => new class() implements JsonSerializable { + public function jsonSerialize(): array { + return array( 'wpServerHtml' => true ); + } + }, + ), + ), + 'negated token' => array( 'data-wp-html="!state.html"', array( 'html' => $token ) ), + 'negated reserved path segment' => array( 'data-wp-html="test::!state.obj.constructor"', array( 'obj' => array( 'constructor' => $token ) ) ), + 'doubly negated closure' => array( + 'data-wp-html="!!state.html"', + array( + 'html' => static function () use ( $token ) { + return $token; + }, + ), + ), + 'string in context' => array( 'data-wp-context=\'{"h":"

Hi

"}\' data-wp-html="context.h"', array() ), + ); + } + + /** + * Tests that a reference that resolves to `null` or to nothing empties the + * host without processing its content, and without a notice. + * + * @ticket 66246 + * + * @covers ::process_directives + * + * @dataProvider data_references_that_resolve_to_nothing + * + * @param string $attributes The attributes of the host. + */ + public function test_reference_that_resolves_to_nothing_empties_the_host_without_notice( string $attributes ) { + $token = $this->token(); + $this->set_state( + array( + 'html' => $token, + 'nul' => null, + 'constructor' => $token, + ) + ); + + $output = wp_interactivity_process_directives( $this->page( '
' . self::CHILDREN . '
' ) ); + + $this->assertSame( $this->processed_page( '
' ), $output ); + $this->assertSame( array(), $this->notices, 'Expected no notice.' ); + } + + /** + * Data provider. + * + * @return array Data provider. + */ + public static function data_references_that_resolve_to_nothing(): array { + return array( + 'null in state' => array( 'data-wp-html="state.nul"' ), + 'missing path' => array( 'data-wp-html="state.missing"' ), + 'reserved path segment' => array( 'data-wp-html="state.constructor"' ), + 'quoted reference' => array( 'data-wp-html=\'"state.html"\'' ), + 'empty value' => array( 'data-wp-html=""' ), + 'no value' => array( 'data-wp-html' ), + ); + } + + /** + * Tests that a reference whose evaluation fails empties the host with only + * the notice of the evaluation: a derived-state closure that throws, a host + * processed apart from the `data-wp-interactive` element that gives it its + * namespace, and a host whose `data-wp-interactive` names a reserved word. + * + * @ticket 66246 + * + * @covers ::process_directives + * + * @dataProvider data_references_whose_evaluation_fails + * + * @param string $input The HTML to process. + * @param string $expected The expected output. + */ + public function test_failed_evaluation_empties_the_host_without_a_data_wp_html_notice( string $input, string $expected ) { + $this->setExpectedIncorrectUsage( 'WP_Interactivity_API::evaluate' ); + $this->set_state( + array( + 'html' => $this->token(), + 'throws' => static function () { + throw new Exception( 'Failed.' ); }, + ) + ); + + $this->assertSame( $expected, wp_interactivity_process_directives( $input ) ); + $this->assertSame( array( 'WP_Interactivity_API::evaluate' ), array_column( $this->notices, 'source' ), 'Expected only the notice of the evaluation.' ); + } + + /** + * Data provider. + * + * @return array Data provider. + */ + public static function data_references_whose_evaluation_fails(): array { + return array( + 'throwing closure' => array( + '
' . self::CHILDREN . '
', + '
', + ), + 'no namespace' => array( + '
' . self::CHILDREN . '
', + '
', + ), + 'reserved namespace' => array( + '
' . self::CHILDREN . '
', + '
', ), ); } /** - * Tests that a `null` value and an unresolved reference keep the host's - * content, with the directives in it processed, without a notice. + * Tests that a host under a `data-wp-interactive` directive that names no + * namespace is emptied, with only the notice of the missing namespace, even + * though an enclosing one names a namespace. Other directives there still + * resolve in the enclosing namespace. * * @ticket 66246 * * @covers ::process_directives * - * @dataProvider data_null_references + * @dataProvider data_islands_that_name_no_namespace * - * @param string $reference The reference. + * @param string $island The attributes of the inner `data-wp-interactive` element. */ - public function test_null_and_unresolved_references_decline_without_notice( string $reference ) { - $this->set_state( array( 'html' => null ) ); + public function test_host_under_an_island_that_names_no_namespace_is_emptied( string $island ) { + $this->setExpectedIncorrectUsage( 'WP_Interactivity_API::evaluate' ); + $this->set_state( array( 'html' => $this->token() ) ); - $output = wp_interactivity_process_directives( $this->page( '
' . self::CHILDREN . '
' ) ); + $output = wp_interactivity_process_directives( + $this->page( '

' . self::CHILDREN . '

x
' ) + ); $this->assertSame( - $this->processed_page( '
' . self::PROCESSED_CHILDREN . '
' ), + $this->processed_page( '

processed
' ), $output ); - $this->assertSame( array(), $this->notices, 'Expected no notice.' ); + $this->assertSame( array( 'WP_Interactivity_API::evaluate' ), array_column( $this->notices, 'source' ), 'Expected only the notice of the missing namespace.' ); } /** @@ -437,19 +549,40 @@ public function test_null_and_unresolved_references_decline_without_notice( stri * * @return array Data provider. */ - public static function data_null_references(): array { + public static function data_islands_that_name_no_namespace(): array { return array( - 'null in state' => array( 'state.html' ), - 'unresolved reference' => array( 'state.missing' ), - 'unknown namespace' => array( 'other::state.html' ), + 'no value' => array( 'data-wp-interactive' ), + 'object without a namespace' => array( 'data-wp-interactive=\'{"a":1}\'' ), + ); + } + + /** + * Tests that an element whose only `data-wp-interactive` directive has a + * unique ID is not an island, so a host inside it resolves its reference + * in the enclosing namespace. + * + * @ticket 66246 + * + * @covers ::process_directives + */ + public function test_host_under_a_unique_id_interactive_directive_keeps_the_enclosing_namespace() { + $this->set_state( array( 'html' => $this->token() ) ); + + $output = wp_interactivity_process_directives( + $this->page( '

Fallback

' ) + ); + + $this->assertSame( + $this->processed_page( '

' . self::MARKER_HTML . '

' ), + $output ); + $this->assertSame( array(), $this->notices, 'Expected no notice.' ); } /** - * Tests that a host that cannot hold content, or that carries a directive - * `data-wp-html` cannot be combined with, declines with one notice naming - * the reason, without resolving its reference, and that its other - * directives still run. + * Tests that a directive the client cannot combine with `data-wp-html` + * makes the element render as if it had no `data-wp-html` directive, with + * one notice naming that directive, and without resolving the reference. * * A reference that was resolved through a derived-state closure would be * listed in the client data, so an empty list shows it was not. @@ -458,13 +591,13 @@ public static function data_null_references(): array { * * @covers ::process_directives * - * @dataProvider data_structurally_declining_hosts + * @dataProvider data_directives_that_conflict * * @param string $host The host markup. * @param string $expected The expected host markup. - * @param string $reason Text the notice contains to name the reason. + * @param string $name The name of the conflicting directive. */ - public function test_structural_decline_names_its_reason_without_resolving_the_reference( string $host, string $expected, string $reason ) { + public function test_conflicting_directive_ignores_data_wp_html_with_one_notice( string $host, string $expected, string $name ) { $this->setExpectedIncorrectUsage( self::NOTICE_SOURCE ); $token = $this->token(); $this->set_state( @@ -480,7 +613,7 @@ public function test_structural_decline_names_its_reason_without_resolving_the_r $this->assertSame( $this->processed_page( $expected ), $output ); $this->assertCount( 1, $this->html_notice_messages(), 'Expected exactly one data-wp-html notice.' ); - $this->assertStringContainsString( $reason, $this->html_notice_messages()[0], 'Expected the notice to name the reason.' ); + $this->assertStringContainsString( '"' . $name . '"', $this->html_notice_messages()[0], 'Expected the notice to name the directive.' ); $this->assertSame( array(), $this->announced_paths(), 'Expected the reference not to be resolved.' ); } @@ -489,75 +622,251 @@ public function test_structural_decline_names_its_reason_without_resolving_the_r * * @return array Data provider. */ - public static function data_structurally_declining_hosts(): array { + public static function data_directives_that_conflict(): array { return array( - 'void element' => array( - '', - '', - '', - ), - 'element with raw content' => array( - '', - '', - 'B' ), + 'html' => static function () use ( $token, &$calls ) { + ++$calls; + return $token; + }, + ) + ); + $output = wp_interactivity_process_directives( $this->page( $host ) ); + + $this->assertSame( $this->processed_page( $expected ), $output ); + $this->assertCount( 1, $this->notices, 'Expected exactly one notice.' ); + $this->assertCount( 1, $this->html_notice_messages(), 'Expected a data-wp-html notice.' ); + $this->assertStringContainsString( $notice, $this->html_notice_messages()[0] ); + $this->assertSame( 0, $calls, 'Expected the reference not to be evaluated.' ); + $this->assertSame( array(), $this->announced_paths(), 'Expected no closure to be listed.' ); } /** * Data provider. * - * @return array Data provider. + * @return array Data provider. */ - public static function data_authored_literals(): array { - return array( - 'JSON object' => array( '{"a":"b"}' ), - 'namespaced integer' => array( 'test::42' ), + public static function data_hosts_that_cannot_hold_html(): array { + $cases = array(); + $attributes = array( + 'null' => 'data-wp-html="state.nul"', + 'string' => 'data-wp-html="state.str"', + 'token' => 'data-wp-html="state.token"', + 'closing token' => 'data-wp-html="state.closer"', + 'closure' => 'data-wp-html="state.html"', + 'missing path' => 'data-wp-html="state.missing"', + 'empty value' => 'data-wp-html=""', + 'no value' => 'data-wp-html', ); + + foreach ( array( 'textarea', 'title', 'script', 'style', 'iframe', 'xmp', 'noembed', 'noframes', 'img', 'input' ) as $tag ) { + $content = in_array( $tag, array( 'img', 'input' ), true ) ? '' : 'Fallback & as written'; + foreach ( $attributes as $name => $attribute ) { + $markup = $attribute . ' data-wp-bind--title="state.text">' . $content; + $cases[ $tag . ' with ' . $name ] = array( + '<' . $tag . ' ' . $markup, + '<' . $tag . ' title="processed" ' . $markup, + 'not supported on <' . $tag . '> elements', + ); + } + } + + return $cases; } /** * Tests that only the default entry renders, and that entries with a suffix - * or a unique ID, and empty entries, are ignored without a notice. + * or a unique ID are ignored without a notice. * * @ticket 66246 * @@ -565,8 +874,7 @@ public static function data_authored_literals(): array { */ public function test_only_the_default_entry_renders() { $this->set_state( array( 'html' => $this->token() ) ); - $ignored = '
Fallback
' . - '
Fallback
Fallback
'; + $ignored = '
Fallback
'; $output = wp_interactivity_process_directives( $this->page( $ignored . '
Fallback
' ) @@ -579,6 +887,121 @@ public function test_only_the_default_entry_renders() { $this->assertSame( array(), $this->notices, 'Expected no notice.' ); } + /** + * Tests that a call holding more hosts than the HTML API allows seeking + * renders every host and processes the directives after them. + * + * @ticket 66246 + * + * @covers ::process_directives + */ + public function test_hosts_beyond_the_seek_limit_render() { + $count = WP_HTML_Tag_Processor::MAX_SEEK_OPS + 1; + $this->set_state( array( 'html' => $this->token() ) ); + + $output = wp_interactivity_process_directives( + $this->page( str_repeat( '
Fallback
', $count ) . '

z

' ) + ); + + $this->assertSame( + $this->processed_page( + str_repeat( '
' . self::MARKER_HTML . '
', $count ) . + '

z

' + ), + $output + ); + } + + /** + * Tests that a call made while another call is processing returns its own + * processed markup, and that the other call then completes as without it: + * every host holds its token's HTML, and the directives after the nested + * call resolve in the namespace and context in effect there. + * + * @ticket 66246 + * + * @covers ::process_directives + * + * @dataProvider data_ways_to_make_a_nested_call + * + * @param callable $make_value Callable that receives a callable making the nested call, and + * returns the value of `state.inner` whose `markup` is its result. + */ + public function test_nested_call_keeps_the_outer_call_processing( callable $make_value ) { + $this->set_state( + array( + 'html' => $this->token(), + 'inner' => $make_value( + static function () { + return wp_interactivity_process_directives( 'Inner' ); + } + ), + ) + ); + $host = '

Fallback

'; + + $output = wp_interactivity_process_directives( + '
' . $host . + 'x' . $host . + 'z
' + ); + + $rendered = '

' . self::MARKER_HTML . '

'; + $this->assertSame( + '
' . $rendered . + '' . esc_html( '' . self::MARKER_HTML . '' ) . '' . $rendered . + 'z
', + $output + ); + $this->assertStringNotContainsString( 'wp-interactivity-dangerous-html', $output, 'Expected no placeholder to be left.' ); + } + + /** + * Data provider. + * + * @return array Data provider. + */ + public static function data_ways_to_make_a_nested_call(): array { + return array( + 'derived-state closure' => array( + static function ( callable $render ) { + return static function () use ( $render ) { + return array( 'markup' => $render() ); + }; + }, + ), + 'state value read during the call' => array( + function ( callable $render ) { + return new class( $render ) implements ArrayAccess { + /** + * Makes the nested call. + * + * @var callable + */ + private $render; + + public function __construct( callable $render ) { + $this->render = $render; + } + + public function offsetExists( $offset ): bool { + return 'markup' === $offset; + } + + #[ReturnTypeWillChange] + public function offsetGet( $offset ) { + return ( $this->render )(); + } + + public function offsetSet( $offset, $value ): void {} + + public function offsetUnset( $offset ): void {} + }; + }, + ), + ); + } + /** * Tests that inside `data-wp-each` each item renders the HTML its reference * resolves to, with the item in context, and only the item's top-level @@ -736,10 +1159,10 @@ public function test_unbalanced_markup_returns_input_unchanged() { /** * Tests that a token restored by unserialization does not render but prints - * as the marker like any other token: the host keeps its fallback, exactly - * one notice is raised for the unserialization and one for the decline, and - * the markup after the host is processed. The token that was serialized - * still renders. + * as the marker like any other token: the host is emptied, exactly one + * notice is raised for the unserialization and one for the value that is + * not a token, and the markup after the host is processed. The token that + * was serialized still renders. * * @ticket 66246 * @@ -747,7 +1170,7 @@ public function test_unbalanced_markup_returns_input_unchanged() { * @covers ::filter_script_module_interactivity_data * @covers WP_Interactivity_Dangerous_HTML::__wakeup */ - public function test_unserialized_token_declines_as_not_a_token() { + public function test_unserialized_token_is_not_a_token() { $this->setExpectedIncorrectUsage( 'WP_Interactivity_Dangerous_HTML::__wakeup' ); $this->setExpectedIncorrectUsage( self::NOTICE_SOURCE ); @@ -772,12 +1195,12 @@ public function test_unserialized_token_declines_as_not_a_token() { ); $this->assertSame( - $this->processed_page( '
Fallback
' . self::MARKER_HTML . '
' ), + $this->processed_page( '
' . self::MARKER_HTML . '
' ), $output, - 'Expected the unserialized token to decline and the serialized one to render.' + 'Expected the unserialized token to empty its host and the serialized one to render.' ); $this->assertCount( 1, $this->html_notice_messages(), 'Expected exactly one data-wp-html notice.' ); - $this->assertCount( 2, $this->notices, 'Expected no notice besides those of the unserialization and the decline.' ); + $this->assertCount( 2, $this->notices, 'Expected no notice besides those of the unserialization and of the value.' ); // Keep assertEquals() because the objects are intentionally compared by value. $this->assertEquals( (object) array( 'wpServerHtml' => true ), @@ -810,7 +1233,7 @@ public function test_token_in_context_helper_reaches_no_output_or_client_data() $this->assertSame( $wrapper . - '
Fallback
' . + '
' . '
z
' . 'processed', $output, @@ -819,12 +1242,12 @@ public function test_token_in_context_helper_reaches_no_output_or_client_data() $this->assertStringContainsString( '{"h":{"wpServerHtml":true}}', $output, 'Expected the token to print as the marker in the context attribute.' ); $this->assertStringNotContainsString( 'marker-7f3a', $output ); $this->assertStringNotContainsString( 'marker-7f3a', $this->printed_client_data() ); - $this->assertCount( 1, $this->html_notice_messages(), 'Expected the value read from context to decline as not a token.' ); + $this->assertCount( 1, $this->html_notice_messages(), 'Expected the value read from context not to be a token.' ); } /** * Tests that every host renders the token its reference reaches through - * state, at any depth and in any namespace. + * state, at any depth, through an object property, and in any namespace. * * @ticket 66246 * @@ -833,8 +1256,9 @@ public function test_token_in_context_helper_reaches_no_output_or_client_data() public function test_tokens_render_at_any_depth_and_namespace() { $this->set_state( array( - 'html' => $this->token(), - 'deep' => array( 'er' => array( 'html' => $this->token() ) ), + 'html' => $this->token(), + 'deep' => array( 'er' => array( 'html' => $this->token() ) ), + 'object' => (object) array( 'html' => $this->token() ), ) ); wp_interactivity_state( @@ -847,7 +1271,7 @@ public function test_tokens_render_at_any_depth_and_namespace() { $hosts = ''; $rendered = ''; - foreach ( array( 'state.deep.er.html', 'state.deep.er.html', 'state.html', 'other::state.html', 'other::state.deep.er.html', 'other::state.deep.er.html' ) as $reference ) { + foreach ( array( 'state.deep.er.html', 'state.deep.er.html', 'state.html', 'state.object.html', 'other::state.html', 'other::state.deep.er.html', 'other::state.deep.er.html' ) as $reference ) { $hosts .= '
Fallback
'; $rendered .= '
' . self::MARKER_HTML . '
'; } diff --git a/tests/phpunit/tests/interactivity-api/wpInteractivityAPIDirectivesProcessor.php b/tests/phpunit/tests/interactivity-api/wpInteractivityAPIDirectivesProcessor.php index f6c3beb79b620..c351da6fdcf90 100644 --- a/tests/phpunit/tests/interactivity-api/wpInteractivityAPIDirectivesProcessor.php +++ b/tests/phpunit/tests/interactivity-api/wpInteractivityAPIDirectivesProcessor.php @@ -389,6 +389,72 @@ public function test_set_content_between_balanced_tags_with_unbalanced_tags() { $this->assertSame( '
New text
', $p->get_updated_html() ); } + /** + * Tests that the `skip_to_balanced_tag_closer` method replaces exactly the + * content between the opener tag and its matching closer tag, writing it as + * given, and leaves the cursor on that closer tag without scanning the new + * content. + * + * @ticket 66246 + * + * @covers ::skip_to_balanced_tag_closer + */ + public function test_skip_to_balanced_tag_closer_replaces_the_content() { + $p = new WP_Interactivity_API_Directives_Processor( '
Nested

Text

After
' ); + $p->next_tag(); + + $this->assertTrue( $p->skip_to_balanced_tag_closer( 'New
' ) ); + $this->assertSame( 'DIV', $p->get_tag() ); + $this->assertTrue( $p->is_tag_closer() ); + + $p->next_tag(); + $this->assertSame( 'after', $p->get_attribute( 'id' ), 'Expected the next tag to be the one after the closer tag.' ); + $this->assertSame( '
New
After
', $p->get_updated_html() ); + } + + /** + * Tests that the `skip_to_balanced_tag_closer` method reports a missing + * closer tag and replaces nothing. + * + * @ticket 66246 + * + * @covers ::skip_to_balanced_tag_closer + */ + public function test_skip_to_balanced_tag_closer_without_a_matching_closer_tag() { + $content = '
Missing closing div
'; + $p = new WP_Interactivity_API_Directives_Processor( $content ); + $p->next_tag(); + + $this->assertFalse( $p->skip_to_balanced_tag_closer( 'New text' ) ); + $this->assertFalse( $p->next_tag(), 'Expected the cursor to be at the end of the HTML.' ); + $this->assertSame( $content, $p->get_updated_html() ); + } + + /** + * Tests that the `skip_to_balanced_tag_closer` method replaces the content + * of every element of a long document in one processor: more often than the + * HTML API allows seeking, while the processor applies its queue of updates + * on its own, and after an attribute update on each opener tag. + * + * @ticket 66246 + * + * @covers ::skip_to_balanced_tag_closer + */ + public function test_skip_to_balanced_tag_closer_replaces_every_content_of_a_long_document() { + $count = 2 * WP_HTML_Tag_Processor::MAX_SEEK_OPS; + $p = new WP_Interactivity_API_Directives_Processor( str_repeat( '
Old text
', $count ) ); + $expected = ''; + + for ( $i = 0; $i < $count; $i++ ) { + $this->assertTrue( $p->next_tag( 'div' ) ); + $p->set_attribute( 'data-index', (string) $i ); + $this->assertTrue( $p->skip_to_balanced_tag_closer( "{$i}" ) ); + $expected .= "
{$i}
"; + } + + $this->assertSame( $expected, $p->get_updated_html() ); + } + /** * Tests the `has_and_visits_its_closer_tag` method. *