<!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>[57768] trunk: HTML API: Ensure that breadcrumbs are properly retained after seeking.</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/57768">57768</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/57768","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>dmsnell</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2024-03-05 05:32:19 +0000 (Tue, 05 Mar 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: Ensure that breadcrumbs are properly retained after seeking.

In some cases, it's possible to seek back into a location found inside
an element which has been closed before the point in the document where
the `seek()` was made. In these cases the breadcrumb stack is lost, and
calling `get_breadcrumbs()` after the seek will return the wrong information.

In this patch, the HTML Processor takes a conservative approach and
moves to the front of the document, then reparses the document until
it reaches the sought-after location. This ensures consistency on
the stack of open elements and active formats, and preserves
breadcrumbs.

Developed in https://github.com/WordPress/wordpress-develop/pull/6185
Discussed in https://core.trac.wordpress.org/ticket/60687

Props jonsurrell.
Follow-up to <a href="https://core.trac.wordpress.org/changeset/60687">[60687]</a>.
See <a href="https://core.trac.wordpress.org/ticket/58517">#58517</a>.
Fixes <a href="https://core.trac.wordpress.org/ticket/60687">#60687</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="#trunktestsphpunittestshtmlapiwpHtmlProcessorBreadcrumbsphp">trunk/tests/phpunit/tests/html-api/wpHtmlProcessorBreadcrumbs.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-03-05 03:01:09 UTC (rev 57767)
+++ trunk/src/wp-includes/html-api/class-wp-html-processor.php  2024-03-05 05:32:19 UTC (rev 57768)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -241,15 +241,15 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        return null;
</span><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">-                $p                        = new self( $html, self::CONSTRUCTOR_UNLOCK_CODE );
-               $p->state->context_node   = array( 'BODY', array() );
-               $p->state->insertion_mode = WP_HTML_Processor_State::INSERTION_MODE_IN_BODY;
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $processor                        = new self( $html, self::CONSTRUCTOR_UNLOCK_CODE );
+               $processor->state->context_node   = array( 'BODY', array() );
+               $processor->state->insertion_mode = WP_HTML_Processor_State::INSERTION_MODE_IN_BODY;
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                // @todo Create "fake" bookmarks for non-existent but implied nodes.
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $p->bookmarks['root-node']    = new WP_HTML_Span( 0, 0 );
-               $p->bookmarks['context-node'] = new WP_HTML_Span( 0, 0 );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $processor->bookmarks['root-node']    = new WP_HTML_Span( 0, 0 );
+               $processor->bookmarks['context-node'] = new WP_HTML_Span( 0, 0 );
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $p->state->stack_of_open_elements->push(
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $processor->state->stack_of_open_elements->push(
</ins><span class="cx" style="display: block; padding: 0 10px">                         new WP_HTML_Token(
</span><span class="cx" style="display: block; padding: 0 10px">                                'root-node',
</span><span class="cx" style="display: block; padding: 0 10px">                                'HTML',
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -257,15 +257,15 @@
</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><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $p->state->stack_of_open_elements->push(
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $processor->state->stack_of_open_elements->push(
</ins><span class="cx" style="display: block; padding: 0 10px">                         new WP_HTML_Token(
</span><span class="cx" style="display: block; padding: 0 10px">                                'context-node',
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                                $p->state->context_node[0],
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                         $processor->state->context_node[0],
</ins><span class="cx" style="display: block; padding: 0 10px">                                 false
</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><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                return $p;
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         return $processor;
</ins><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><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1226,6 +1226,10 @@
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="cx" style="display: block; padding: 0 10px">         * Moves the internal cursor in the HTML Processor to a given bookmark's location.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Be careful! Seeking backwards to a previous location resets the parser to the
+        * start of the document and reparses the entire contents up until it finds the
+        * sought-after bookmarked location.
+        *
</ins><span class="cx" style="display: block; padding: 0 10px">          * In order to prevent accidental infinite loops, there's a
</span><span class="cx" style="display: block; padding: 0 10px">         * maximum limit on the number of times seek() can be called.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1247,44 +1251,73 @@
</span><span class="cx" style="display: block; padding: 0 10px">                $bookmark_starts_at   = $this->bookmarks[ $actual_bookmark_name ]->start;
</span><span class="cx" style="display: block; padding: 0 10px">                $direction            = $bookmark_starts_at > $processor_started_at ? 'forward' : 'backward';
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                switch ( $direction ) {
-                       case 'forward':
-                               // When moving forwards, reparse the document until reaching the same location as the original bookmark.
-                               while ( $this->step() ) {
-                                       if ( $bookmark_starts_at === $this->bookmarks[ $this->state->current_token->bookmark_name ]->start ) {
-                                               return true;
-                                       }
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         /*
+                * If seeking backwards, it's possible that the sought-after bookmark exists within an element
+                * which has been closed before the current cursor; in other words, it has already been removed
+                * from the stack of open elements. This means that it's insufficient to simply pop off elements
+                * from the stack of open elements which appear after the bookmarked location and then jump to
+                * that location, as the elements which were open before won't be re-opened.
+                *
+                * In order to maintain consistency, the HTML Processor rewinds to the start of the document
+                * and reparses everything until it finds the sought-after bookmark.
+                *
+                * There are potentially better ways to do this: cache the parser state for each bookmark and
+                * restore it when seeking; store an immutable and idempotent register of where elements open
+                * and close.
+                *
+                * If caching the parser state it will be essential to properly maintain the cached stack of
+                * open elements and active formatting elements when modifying the document. This could be a
+                * tedious and time-consuming process as well, and so for now will not be performed.
+                *
+                * It may be possible to track bookmarks for where elements open and close, and in doing so
+                * be able to quickly recalculate breadcrumbs for any element in the document. It may even
+                * be possible to remove the stack of open elements and compute it on the fly this way.
+                * If doing this, the parser would need to track the opening and closing locations for all
+                * tokens in the breadcrumb path for any and all bookmarks. By utilizing bookmarks themselves
+                * this list could be automatically maintained while modifying the document. Finding the
+                * breadcrumbs would then amount to traversing that list from the start until the token
+                * being inspected. Once an element closes, if there are no bookmarks pointing to locations
+                * within that element, then all of these locations may be forgotten to save on memory use
+                * and computation time.
+                */
+               if ( 'backward' === $direction ) {
+                       /*
+                        * Instead of clearing the parser state and starting fresh, calling the stack methods
+                        * maintains the proper flags in the parser.
+                        */
+                       foreach ( $this->state->stack_of_open_elements->walk_up() as $item ) {
+                               if ( 'context-node' === $item->bookmark_name ) {
+                                       break;
</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">-                                return false;
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                         $this->state->stack_of_open_elements->remove_node( $item );
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        case 'backward':
-                               /*
-                                * When moving backwards, clear out all existing stack entries which appear after the destination
-                                * bookmark. These could be stored for later retrieval, but doing so would require additional
-                                * memory overhead and also demand that references and bookmarks are updated as the document
-                                * changes. In time this could be a valuable optimization, but it's okay to give up that
-                                * optimization in exchange for more CPU time to recompute the stack, to re-parse the
-                                * document that may have already been parsed once.
-                                */
-                               foreach ( $this->state->stack_of_open_elements->walk_up() as $item ) {
-                                       if ( $bookmark_starts_at >= $this->bookmarks[ $item->bookmark_name ]->start ) {
-                                               break;
-                                       }
-
-                                       $this->state->stack_of_open_elements->remove_node( $item );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 foreach ( $this->state->active_formatting_elements->walk_up() as $item ) {
+                               if ( 'context-node' === $item->bookmark_name ) {
+                                       break;
</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">-                                foreach ( $this->state->active_formatting_elements->walk_up() as $item ) {
-                                       if ( $bookmark_starts_at >= $this->bookmarks[ $item->bookmark_name ]->start ) {
-                                               break;
-                                       }
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                         $this->state->active_formatting_elements->remove_node( $item );
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                                        $this->state->active_formatting_elements->remove_node( $item );
-                               }
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 parent::seek( 'context-node' );
+                       $this->state->insertion_mode = WP_HTML_Processor_State::INSERTION_MODE_IN_BODY;
+                       $this->state->frameset_ok    = true;
+               }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                                return parent::seek( $actual_bookmark_name );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         // When moving forwards, reparse the document until reaching the same location as the original bookmark.
+               if ( $bookmark_starts_at === $this->bookmarks[ $this->state->current_token->bookmark_name ]->start ) {
+                       return true;
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+               while ( $this->step() ) {
+                       if ( $bookmark_starts_at === $this->bookmarks[ $this->state->current_token->bookmark_name ]->start ) {
+                               return true;
+                       }
+               }
+
+               return false;
</ins><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></span></pre></div>
<a id="trunktestsphpunittestshtmlapiwpHtmlProcessorBreadcrumbsphp"></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/wpHtmlProcessorBreadcrumbs.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/html-api/wpHtmlProcessorBreadcrumbs.php 2024-03-05 03:01:09 UTC (rev 57767)
+++ trunk/tests/phpunit/tests/html-api/wpHtmlProcessorBreadcrumbs.php   2024-03-05 05:32:19 UTC (rev 57768)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -545,4 +545,26 @@
</span><span class="cx" style="display: block; padding: 0 10px">                $processor->seek( 'second' );
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertTrue( $processor->get_attribute( 'two' ) );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+       /**
+        * Ensures that breadcrumbs are properly reported after seeking backward to a location
+        * inside an element which has been fully closed before the seek.
+        *
+        * @ticket 60687
+        */
+       public function test_retains_proper_bookmarks_after_seeking_back_to_closed_element() {
+               $processor = WP_HTML_Processor::create_fragment( '<div><img></div><div><hr></div>' );
+
+               $processor->next_tag( 'IMG' );
+               $processor->set_bookmark( 'first' );
+
+               $processor->next_tag( 'HR' );
+
+               $processor->seek( 'first' );
+               $this->assertSame(
+                       array( 'HTML', 'BODY', 'DIV', 'IMG' ),
+                       $processor->get_breadcrumbs(),
+                       'Should have retained breadcrumbs from bookmarked location after seeking backwards to it.'
+               );
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span></span></pre>
</div>
</div>

</body>
</html>