<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[59444] trunk: HTML API: Add method to create fragment at node.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="https://core.trac.wordpress.org/changeset/59444">59444</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"https://core.trac.wordpress.org/changeset/59444","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>Bernhard Reiter</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2024-11-21 13:27:58 +0000 (Thu, 21 Nov 2024)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>HTML API: Add method to create fragment at node.

HTML Fragment parsing always happens with a context node, which may impact how a fragment of HTML is parsed. HTML Fragment Processors can be instantiated with a `BODY` context node via `WP_HTML_Processor::create_fragment( $html )`.

This changeset adds a static method called `create_fragment_at_current_node( string $html_fragment )`. It can only be called when the processor is paused at a `#tag`, with some additional constraints:

- The opening and closing tags must appear in the HTML input (no virtual tokens).
- No "self-contained" elements are allowed ( `IFRAME`, `SCRIPT`, `TITLE`, etc.).

If successful, the method will return a `WP_HTML_Processor` instance whose context is inherited from the node that the method was called from.

Props jonsurrell, bernhard-reiter, gziolo.
Fixes <a href="https://core.trac.wordpress.org/ticket/62357">#62357</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludeshtmlapiclasswphtmlprocessorphp">trunk/src/wp-includes/html-api/class-wp-html-processor.php</a></li>
<li><a href="#trunktestsphpunittestshtmlapiwpHtmlProcessorphp">trunk/tests/phpunit/tests/html-api/wpHtmlProcessor.php</a></li>
<li><a href="#trunktestsphpunittestshtmlapiwpHtmlProcessorHtml5libphp">trunk/tests/phpunit/tests/html-api/wpHtmlProcessorHtml5lib.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludeshtmlapiclasswphtmlprocessorphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/html-api/class-wp-html-processor.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/html-api/class-wp-html-processor.php        2024-11-21 13:16:07 UTC (rev 59443)
+++ trunk/src/wp-includes/html-api/class-wp-html-processor.php  2024-11-21 13:27:58 UTC (rev 59444)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -425,6 +425,120 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Creates a fragment processor at the current node.
+        *
+        * HTML Fragment parsing always happens with a context node. HTML Fragment Processors can be
+        * instantiated with a `BODY` context node via `WP_HTML_Processor::create_fragment( $html )`.
+        *
+        * The context node may impact how a fragment of HTML is parsed. For example, consider the HTML
+        * fragment `<td />Inside TD?</td>`.
+        *
+        * A BODY context node will produce the following tree:
+        *
+        *     └─#text Inside TD?
+        *
+        * Notice that the `<td>` tags are completely ignored.
+        *
+        * Compare that with an SVG context node that produces the following tree:
+        *
+        *     ├─svg:td
+        *     └─#text Inside TD?
+        *
+        * Here, a `td` node in the `svg` namespace is created, and its self-closing flag is respected.
+        * This is a peculiarity of parsing HTML in foreign content like SVG.
+        *
+        * Finally, consider the tree produced with a TABLE context node:
+        *
+        *     └─TBODY
+        *       └─TR
+        *         └─TD
+        *           └─#text Inside TD?
+        *
+        * These examples demonstrate how important the context node may be when processing an HTML
+        * fragment. Special care must be taken when processing fragments that are expected to appear
+        * in specific contexts. SVG and TABLE are good examples, but there are others.
+        *
+        * @see https://html.spec.whatwg.org/multipage/parsing.html#html-fragment-parsing-algorithm
+        *
+        * @param string $html Input HTML fragment to process.
+        * @return static|null The created processor if successful, otherwise null.
+        */
+       public function create_fragment_at_current_node( string $html ) {
+               if ( $this->get_token_type() !== '#tag' ) {
+                       return null;
+               }
+
+               $namespace = $this->current_element->token->namespace;
+
+               /*
+                * Prevent creating fragments at nodes that require a special tokenizer state.
+                * This is unsupported by the HTML Processor.
+                */
+               if (
+                       'html' === $namespace &&
+                       in_array( $this->current_element->token->node_name, array( 'IFRAME', 'NOEMBED', 'NOFRAMES', 'SCRIPT', 'STYLE', 'TEXTAREA', 'TITLE', 'XMP', 'PLAINTEXT' ), true )
+               ) {
+                       return null;
+               }
+
+               $fragment_processor = static::create_fragment( $html );
+               if ( null === $fragment_processor ) {
+                       return null;
+               }
+
+               $fragment_processor->compat_mode = $this->compat_mode;
+
+               $fragment_processor->context_node                = clone $this->state->current_token;
+               $fragment_processor->context_node->bookmark_name = 'context-node';
+               $fragment_processor->context_node->on_destroy    = null;
+
+               $fragment_processor->state->context_node = array( $fragment_processor->context_node->node_name, array() );
+
+               $attribute_names = $this->get_attribute_names_with_prefix( '' );
+               if ( null !== $attribute_names ) {
+                       foreach ( $attribute_names as $name ) {
+                               $fragment_processor->state->context_node[1][ $name ] = $this->get_attribute( $name );
+                       }
+               }
+
+               $fragment_processor->breadcrumbs = array( 'HTML', $fragment_processor->context_node->node_name );
+
+               if ( 'TEMPLATE' === $fragment_processor->context_node->node_name ) {
+                       $fragment_processor->state->stack_of_template_insertion_modes[] = WP_HTML_Processor_State::INSERTION_MODE_IN_TEMPLATE;
+               }
+
+               $fragment_processor->reset_insertion_mode_appropriately();
+
+               /*
+                * > Set the parser's form element pointer to the nearest node to the context element that
+                * > is a form element (going straight up the ancestor chain, and including the element
+                * > itself, if it is a form element), if any. (If there is no such form element, the
+                * > form element pointer keeps its initial value, null.)
+                */
+               foreach ( $this->state->stack_of_open_elements->walk_up() as $element ) {
+                       if ( 'FORM' === $element->node_name && 'html' === $element->namespace ) {
+                               $fragment_processor->state->form_element                = clone $element;
+                               $fragment_processor->state->form_element->bookmark_name = null;
+                               $fragment_processor->state->form_element->on_destroy    = null;
+                               break;
+                       }
+               }
+
+               $fragment_processor->state->encoding_confidence = 'irrelevant';
+
+               /*
+                * Update the parsing namespace near the end of the process.
+                * This is important so that any push/pop from the stack of open
+                * elements does not change the parsing namespace.
+                */
+               $fragment_processor->change_parsing_namespace(
+                       $this->current_element->token->integration_node_type ? 'html' : $namespace
+               );
+
+               return $fragment_processor;
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Stops the parser and terminates its execution when encountering unsupported markup.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @throws WP_HTML_Unsupported_Exception Halts execution of the parser.
</span></span></pre></div>
<a id="trunktestsphpunittestshtmlapiwpHtmlProcessorphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/html-api/wpHtmlProcessor.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/html-api/wpHtmlProcessor.php    2024-11-21 13:16:07 UTC (rev 59443)
+++ trunk/tests/phpunit/tests/html-api/wpHtmlProcessor.php      2024-11-21 13:27:58 UTC (rev 59444)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1044,6 +1044,66 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * @ticket 62357
+        */
+       public function test_create_fragment_at_current_node_in_foreign_content() {
+               $processor = WP_HTML_Processor::create_full_parser( '<svg>' );
+               $this->assertTrue( $processor->next_tag( 'SVG' ) );
+
+               $fragment = $processor->create_fragment_at_current_node( "\0preceded-by-nul-byte<rect /><circle></circle><foreignobject><div></div></foreignobject><g>" );
+
+               $this->assertSame( 'svg', $fragment->get_namespace() );
+               $this->assertTrue( $fragment->next_token() );
+
+               /*
+                * In HTML parsing, a nul byte would be ignored.
+                * In SVG it should be replaced with a replacement character.
+                */
+               $this->assertSame( '#text', $fragment->get_token_type() );
+               $this->assertSame( "\u{FFFD}", $fragment->get_modifiable_text() );
+
+               $this->assertTrue( $fragment->next_tag( 'RECT' ) );
+               $this->assertSame( 'svg', $fragment->get_namespace() );
+
+               $this->assertTrue( $fragment->next_tag( 'CIRCLE' ) );
+               $this->assertSame( array( 'HTML', 'SVG', 'CIRCLE' ), $fragment->get_breadcrumbs() );
+               $this->assertTrue( $fragment->next_tag( 'foreignObject' ) );
+               $this->assertSame( 'svg', $fragment->get_namespace() );
+       }
+
+       /**
+        * @ticket 62357
+        */
+       public function test_create_fragment_at_current_node_in_foreign_content_integration_point() {
+               $processor = WP_HTML_Processor::create_full_parser( '<svg><foreignObject>' );
+               $this->assertTrue( $processor->next_tag( 'foreignObject' ) );
+
+               $fragment = $processor->create_fragment_at_current_node( "<image>\0not-preceded-by-nul-byte<rect />" );
+
+               // Nothing has been processed, the html namespace should be used for parsing as an integration point.
+               $this->assertSame( 'html', $fragment->get_namespace() );
+
+               // HTML parsing transforms IMAGE into IMG.
+               $this->assertTrue( $fragment->next_tag( 'IMG' ) );
+
+               $this->assertTrue( $fragment->next_token() );
+
+               // In HTML parsing, the nul byte is ignored and the text is reached.
+               $this->assertSame( '#text', $fragment->get_token_type() );
+               $this->assertSame( 'not-preceded-by-nul-byte', $fragment->get_modifiable_text() );
+
+               /*
+                * svg:foreignObject is an HTML integration point, so the processor should be in the HTML namespace.
+                * RECT is an HTML element here, meaning it may have the self-closing flag but does not self-close.
+                */
+               $this->assertTrue( $fragment->next_tag( 'RECT' ) );
+               $this->assertSame( array( 'HTML', 'FOREIGNOBJECT', 'RECT' ), $fragment->get_breadcrumbs() );
+               $this->assertSame( 'html', $fragment->get_namespace() );
+               $this->assertTrue( $fragment->has_self_closing_flag() );
+               $this->assertTrue( $fragment->expects_closer() );
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Ensure that lowercased tag_name query matches tags case-insensitively.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @group 62427
</span></span></pre></div>
<a id="trunktestsphpunittestshtmlapiwpHtmlProcessorHtml5libphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/html-api/wpHtmlProcessorHtml5lib.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/html-api/wpHtmlProcessorHtml5lib.php    2024-11-21 13:16:07 UTC (rev 59443)
+++ trunk/tests/phpunit/tests/html-api/wpHtmlProcessorHtml5lib.php      2024-11-21 13:27:58 UTC (rev 59444)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -138,10 +138,6 @@
</span><span class="cx" style="display: block; padding: 0 10px">         * @return bool True if the test case should be skipped. False otherwise.
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><span class="cx" style="display: block; padding: 0 10px">        private static function should_skip_test( ?string $test_context_element, string $test_name ): bool {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                if ( null !== $test_context_element && 'body' !== $test_context_element ) {
-                       return true;
-               }
-
</del><span class="cx" style="display: block; padding: 0 10px">                 if ( array_key_exists( $test_name, self::SKIP_TESTS ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                        return true;
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -157,18 +153,79 @@
</span><span class="cx" style="display: block; padding: 0 10px">         * @return string|null Tree structure of parsed HTML, if supported, else null.
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><span class="cx" style="display: block; padding: 0 10px">        private static function build_tree_representation( ?string $fragment_context, string $html ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $processor = $fragment_context
-                       ? WP_HTML_Processor::create_fragment( $html, "<{$fragment_context}>" )
-                       : WP_HTML_Processor::create_full_parser( $html );
-               if ( null === $processor ) {
-                       throw new WP_HTML_Unsupported_Exception( "Could not create a parser with the given fragment context: {$fragment_context}.", '', 0, '', array(), array() );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $processor = null;
+               if ( $fragment_context ) {
+                       if ( 'body' === $fragment_context ) {
+                               $processor = WP_HTML_Processor::create_fragment( $html );
+                       } else {
+
+                               /*
+                                * If the string of characters starts with "svg ", the context
+                                * element is in the SVG namespace and the substring after
+                                * "svg " is the local name. If the string of characters starts
+                                * with "math ", the context element is in the MathML namespace
+                                * and the substring after "math " is the local name.
+                                * Otherwise, the context element is in the HTML namespace and
+                                * the string is the local name.
+                                */
+                               if ( str_starts_with( $fragment_context, 'svg ' ) ) {
+                                       $tag_name = substr( $fragment_context, 4 );
+                                       if ( 'svg' === $tag_name ) {
+                                               $parent_processor = WP_HTML_Processor::create_full_parser( '<!DOCTYPE html><svg>' );
+                                       } else {
+                                               $parent_processor = WP_HTML_Processor::create_full_parser( "<!DOCTYPE html><svg><{$tag_name}>" );
+                                       }
+                                       $parent_processor->next_tag( $tag_name );
+                               } elseif ( str_starts_with( $fragment_context, 'math ' ) ) {
+                                       $tag_name = substr( $fragment_context, 5 );
+                                       if ( 'math' === $tag_name ) {
+                                               $parent_processor = WP_HTML_Processor::create_full_parser( '<!DOCTYPE html><math>' );
+                                       } else {
+                                               $parent_processor = WP_HTML_Processor::create_full_parser( "<!DOCTYPE html><math><{$tag_name}>" );
+                                       }
+                                       $parent_processor->next_tag( $tag_name );
+                               } else {
+                                       if ( in_array(
+                                               $fragment_context,
+                                               array(
+                                                       'caption',
+                                                       'col',
+                                                       'colgroup',
+                                                       'tbody',
+                                                       'td',
+                                                       'tfoot',
+                                                       'th',
+                                                       'thead',
+                                                       'tr',
+                                               ),
+                                               true
+                                       ) ) {
+                                               $parent_processor = WP_HTML_Processor::create_full_parser( "<!DOCTYPE html><table><{$fragment_context}>" );
+                                               $parent_processor->next_tag();
+                                       } else {
+                                               $parent_processor = WP_HTML_Processor::create_full_parser( "<!DOCTYPE html><{$fragment_context}>" );
+                                       }
+                                       $parent_processor->next_tag( $fragment_context );
+                               }
+                               if ( null !== $parent_processor->get_unsupported_exception() ) {
+                                       throw $parent_processor->get_unsupported_exception();
+                               }
+                               if ( null !== $parent_processor->get_last_error() ) {
+                                       throw new Exception( $parent_processor->get_last_error() );
+                               }
+                               $processor = $parent_processor->create_fragment_at_current_node( $html );
+                       }
+
+                       if ( null === $processor ) {
+                               throw new WP_HTML_Unsupported_Exception( "Could not create a parser with the given fragment context: {$fragment_context}.", '', 0, '', array(), array() );
+                       }
+               } else {
+                       $processor = WP_HTML_Processor::create_full_parser( $html );
+                       if ( null === $processor ) {
+                               throw new Exception( 'Could not create a full parser.' );
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                /*
-                * The fragment parser will start in 2 levels deep at: html > body > [position]
-                * and requires adjustment to initial parameters.
-                * The full parser will not.
-                */
</del><span class="cx" style="display: block; padding: 0 10px">                 $output       = '';
</span><span class="cx" style="display: block; padding: 0 10px">                $indent_level = 0;
</span><span class="cx" style="display: block; padding: 0 10px">                $was_text     = null;
</span></span></pre>
</div>
</div>

</body>
</html>