Make WordPress Core


Ignore:
Timestamp:
05/23/2024 11:35:52 PM (9 months ago)
Author:
dmsnell
Message:

HTML API: Add method to report depth of currently-matched node.

The HTML Processor maintains a stack of open elements, where every element,
every #text node, every HTML comment, and other node is pushed and popped while
traversing the document. The "depth" of each of these nodes represents how deep
that stack is where the node appears. Unfortunately this information isn't
exposed to calling code, which has led different projects to attempt to
calculate this value externally. This isn't always trivial, but the HTML
Processor could make it so by exposing the internal knowledge in a new method.

In this patch the get_current_depth() method returns just that. Since the
processor always exists within a context, the depth includes nesting from the
always-present html element and also the body, since currently the HTML
Processor only supports parsing in the IN BODY context.

This means that the depth reported for the DIV in <div> is 3, not 1, because
its breadcrumbs path is HTML > BODY > DIV.

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

Fixes #61255.
Props dmsnell, jonsurrell.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/html-api/class-wp-html-processor.php

    r58190 r58191  
    622622
    623623        return $breadcrumbs;
     624    }
     625
     626    /**
     627     * Returns the nesting depth of the current location in the document.
     628     *
     629     * Example:
     630     *
     631     *     $processor = WP_HTML_Processor::create_fragment( '<div><p></p></div>' );
     632     *     // The processor starts in the BODY context, meaning it has depth from the start: HTML > BODY.
     633     *     2 === $processor->get_current_depth();
     634     *
     635     *     // Opening the DIV element increases the depth.
     636     *     $processor->next_token();
     637     *     3 === $processor->get_current_depth();
     638     *
     639     *     // Opening the P element increases the depth.
     640     *     $processor->next_token();
     641     *     4 === $processor->get_current_depth();
     642     *
     643     *     // The P element is closed during `next_token()` so the depth is decreased to reflect that.
     644     *     $processor->next_token();
     645     *     3 === $processor->get_current_depth();
     646     *
     647     * @since 6.6.0
     648     *
     649     * @return int Nesting-depth of current location in the document.
     650     */
     651    public function get_current_depth() {
     652        return $this->state->stack_of_open_elements->count();
    624653    }
    625654
Note: See TracChangeset for help on using the changeset viewer.