Make WordPress Core

Changeset 57627


Ignore:
Timestamp:
02/13/2024 03:10:21 PM (9 months ago)
Author:
Bernhard Reiter
Message:

Block Hooks: Set ignoredHookedBlocks metadata upon saving.

Decouple hooked blocks insertion from setting the metadata.ignoredHookedBlocks attribute on anchor blocks, and perform the latter step upon saving a template or template part to the database. This ensures that anchor blocks that have been newly added to a template (or part) on the client side will also get ignoredHookedBlocks metadata set correctly, thus preserving editor/front-end parity. Hooked block insertion, on the other hand, will continue to happen upon reading a template (or part).

Props gziolo, tomjcafferkey.
Fixes #60506.

Location:
trunk
Files:
1 added
1 deleted
8 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/block-template-utils.php

    r57594 r57627  
    14331433    return $template_hierarchy;
    14341434}
     1435/**
     1436 * Inject ignoredHookedBlocks metadata attributes into a template or template part.
     1437 *
     1438 * Given a `wp_template` or `wp_template_part` post object, locate all blocks that have
     1439 * hooked blocks, and inject a `metadata.ignoredHookedBlocks` attribute into the anchor
     1440 * blocks to reflect the latter.
     1441 *
     1442 * @param WP_Post $post A post object with post type set to `wp_template` or `wp_template_part`.
     1443 * @return WP_Post The updated post object.
     1444 */
     1445function inject_ignored_hooked_blocks_metadata_attributes( $post ) {
     1446    $hooked_blocks = get_hooked_blocks();
     1447    if ( empty( $hooked_blocks ) && ! has_filter( 'hooked_block_types' ) ) {
     1448        return;
     1449    }
     1450
     1451    // At this point, the post has already been created.
     1452    // We need to build the corresponding `WP_Block_Template` object as context argument for the visitor.
     1453    // To that end, we need to suppress hooked blocks from getting inserted into the template.
     1454    add_filter( 'hooked_block_types', '__return_empty_array', 99999, 0 );
     1455    $template = _build_block_template_result_from_post( $post );
     1456    remove_filter( 'hooked_block_types', '__return_empty_array', 99999 );
     1457
     1458    $before_block_visitor = make_before_block_visitor( $hooked_blocks, $template, 'set_ignored_hooked_blocks_metadata' );
     1459    $after_block_visitor  = make_after_block_visitor( $hooked_blocks, $template, 'set_ignored_hooked_blocks_metadata' );
     1460
     1461    $blocks  = parse_blocks( $template->content );
     1462    $content = traverse_and_serialize_blocks( $blocks, $before_block_visitor, $after_block_visitor );
     1463
     1464    wp_update_post(
     1465        array(
     1466            'ID'            => $post->ID,
     1467            'post_content'  => $content,
     1468        )
     1469    );
     1470}
  • trunk/src/wp-includes/blocks.php

    r57590 r57627  
    852852
    853853/**
    854  * Conditionally returns the markup for a given hooked block.
    855  *
    856  * Accepts three arguments: A hooked block, its type, and a reference to an anchor block.
    857  * If the anchor block has already been processed, and the given hooked block type is in the list
    858  * of ignored hooked blocks, an empty string is returned.
    859  *
    860  * The hooked block type is specified separately as it's possible that a filter might've modified
    861  * the hooked block such that `$hooked_block['blockName']` does no longer reflect the original type.
    862  *
    863  * This function is meant for internal use only.
    864  *
    865  * @since 6.5.0
    866  * @access private
    867  *
    868  * @param array  $hooked_block      The hooked block, represented as a parsed block array.
    869  * @param string $hooked_block_type The type of the hooked block. This could be different from
    870  *                                  $hooked_block['blockName'], as a filter might've modified the latter.
    871  * @param array  $anchor_block      The anchor block, represented as a parsed block array.
    872  *                                  Passed by reference.
    873  * @return string The markup for the given hooked block, or an empty string if the block is ignored.
    874  */
    875 function get_hooked_block_markup( $hooked_block, $hooked_block_type, &$anchor_block ) {
    876     if ( ! isset( $anchor_block['attrs']['metadata']['ignoredHookedBlocks'] ) ) {
    877         $anchor_block['attrs']['metadata']['ignoredHookedBlocks'] = array();
    878     }
    879 
    880     if ( in_array( $hooked_block_type, $anchor_block['attrs']['metadata']['ignoredHookedBlocks'], true ) ) {
    881         return '';
    882     }
    883 
    884     // The following is only needed for the REST API endpoint.
    885     // However, its presence does not affect the frontend.
    886     $anchor_block['attrs']['metadata']['ignoredHookedBlocks'][] = $hooked_block_type;
    887 
    888     return serialize_block( $hooked_block );
    889 }
    890 
    891 /**
    892854 * Returns the markup for blocks hooked to the given anchor block in a specific relative position.
    893855 *
     
    947909
    948910        // It's possible that the `hooked_block_{$hooked_block_type}` filter returned a block of a different type,
    949         // so we need to pass the original $hooked_block_type as well.
    950         $markup .= get_hooked_block_markup( $parsed_hooked_block, $hooked_block_type, $parsed_anchor_block );
     911        // so we explicitly look for the original `$hooked_block_type` in the `ignoredHookedBlocks` metadata.
     912        if (
     913            ! isset( $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] ) ||
     914            ! in_array( $hooked_block_type, $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'], true )
     915        ) {
     916            $markup .= serialize_block( $parsed_hooked_block );
     917        }
    951918    }
    952919
    953920    return $markup;
     921}
     922
     923/**
     924 * Adds a list of hooked block types to an anchor block's ignored hooked block types.
     925 *
     926 * This function is meant for internal use only.
     927 *
     928 * @since 6.5.0
     929 * @access private
     930 *
     931 * @param array                   $parsed_anchor_block The anchor block, in parsed block array format.
     932 * @param string                  $relative_position   The relative position of the hooked blocks.
     933 *                                                     Can be one of 'before', 'after', 'first_child', or 'last_child'.
     934 * @param array                   $hooked_blocks       An array of hooked block types, grouped by anchor block and relative position.
     935 * @param WP_Block_Template|array $context             The block template, template part, or pattern that the anchor block belongs to.
     936 * @return string An empty string.
     937 */
     938function set_ignored_hooked_blocks_metadata( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
     939    $anchor_block_type  = $parsed_anchor_block['blockName'];
     940    $hooked_block_types = isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] )
     941        ? $hooked_blocks[ $anchor_block_type ][ $relative_position ]
     942        : array();
     943
     944    /** This filter is documented in wp-includes/blocks.php */
     945    $hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context );
     946    if ( empty( $hooked_block_types ) ) {
     947        return '';
     948    }
     949
     950    $previously_ignored_hooked_blocks = isset( $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] )
     951        ? $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks']
     952        : array();
     953
     954    $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] = array_unique(
     955        array_merge(
     956            $previously_ignored_hooked_blocks,
     957            $hooked_block_types
     958        )
     959    );
     960
     961    // Markup for the hooked blocks has already been created (in `insert_hooked_blocks`).
     962    return '';
    954963}
    955964
     
    964973 *
    965974 * @since 6.4.0
     975 * @since 6.5.0 Added $callback argument.
    966976 * @access private
    967977 *
     
    969979 * @param WP_Block_Template|WP_Post|array $context       A block template, template part, `wp_navigation` post object,
    970980 *                                                       or pattern that the blocks belong to.
     981 * @param callable                        $callback      A function that will be called for each block to generate
     982 *                                                       the markup for a given list of blocks that are hooked to it.
     983 *                                                       Default: 'insert_hooked_blocks'.
    971984 * @return callable A function that returns the serialized markup for the given block,
    972985 *                  including the markup for any hooked blocks before it.
    973986 */
    974 function make_before_block_visitor( $hooked_blocks, $context ) {
     987function make_before_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) {
    975988    /**
    976989     * Injects hooked blocks before the given block, injects the `theme` attribute into Template Part blocks, and returns the serialized markup.
     
    985998     * @return string The serialized markup for the given block, with the markup for any hooked blocks prepended to it.
    986999     */
    987     return function ( &$block, &$parent_block = null, $prev = null ) use ( $hooked_blocks, $context ) {
     1000    return function ( &$block, &$parent_block = null, $prev = null ) use ( $hooked_blocks, $context, $callback ) {
    9881001        _inject_theme_attribute_in_template_part_block( $block );
    9891002
     
    9921005        if ( $parent_block && ! $prev ) {
    9931006            // Candidate for first-child insertion.
    994             $markup .= insert_hooked_blocks( $parent_block, 'first_child', $hooked_blocks, $context );
    995         }
    996 
    997         $markup .= insert_hooked_blocks( $block, 'before', $hooked_blocks, $context );
     1007            $markup .= call_user_func_array(
     1008                $callback,
     1009                array( &$parent_block, 'first_child', $hooked_blocks, $context )
     1010            );
     1011        }
     1012
     1013        $markup .= call_user_func_array(
     1014            $callback,
     1015            array( &$block, 'before', $hooked_blocks, $context )
     1016        );
    9981017
    9991018        return $markup;
     
    10111030 *
    10121031 * @since 6.4.0
     1032 * @since 6.5.0 Added $callback argument.
    10131033 * @access private
    10141034 *
     
    10161036 * @param WP_Block_Template|WP_Post|array $context       A block template, template part, `wp_navigation` post object,
    10171037 *                                                       or pattern that the blocks belong to.
     1038 * @param callable                        $callback      A function that will be called for each block to generate
     1039 *                                                       the markup for a given list of blocks that are hooked to it.
     1040 *                                                       Default: 'insert_hooked_blocks'.
    10181041 * @return callable A function that returns the serialized markup for the given block,
    10191042 *                  including the markup for any hooked blocks after it.
    10201043 */
    1021 function make_after_block_visitor( $hooked_blocks, $context ) {
     1044function make_after_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) {
    10221045    /**
    10231046     * Injects hooked blocks after the given block, and returns the serialized markup.
     
    10311054     * @return string The serialized markup for the given block, with the markup for any hooked blocks appended to it.
    10321055     */
    1033     return function ( &$block, &$parent_block = null, $next = null ) use ( $hooked_blocks, $context ) {
    1034         $markup = insert_hooked_blocks( $block, 'after', $hooked_blocks, $context );
     1056    return function ( &$block, &$parent_block = null, $next = null ) use ( $hooked_blocks, $context, $callback ) {
     1057        $markup = call_user_func_array(
     1058            $callback,
     1059            array( &$block, 'after', $hooked_blocks, $context )
     1060        );
    10351061
    10361062        if ( $parent_block && ! $next ) {
    10371063            // Candidate for last-child insertion.
    1038             $markup .= insert_hooked_blocks( $parent_block, 'last_child', $hooked_blocks, $context );
     1064            $markup .= call_user_func_array(
     1065                $callback,
     1066                array( &$parent_block, 'last_child', $hooked_blocks, $context )
     1067            );
    10391068        }
    10401069
  • trunk/src/wp-includes/default-filters.php

    r57558 r57627  
    753753add_action( 'init', '_wp_register_default_font_collections' );
    754754
     755// It might be nice to use a filter instead of an action, but the `WP_REST_Templates_Controller` doesn't
     756// provide one (unlike e.g. `WP_REST_Posts_Controller`, which has `rest_pre_insert_{$this->post_type}`).
     757add_action( 'rest_after_insert_wp_template', 'inject_ignored_hooked_blocks_metadata_attributes', 10, 3 );
     758add_action( 'rest_after_insert_wp_template_part', 'inject_ignored_hooked_blocks_metadata_attributes', 10, 3 );
     759
    755760unset( $filter, $action );
  • trunk/tests/phpunit/tests/block-templates/base.php

    r57594 r57627  
    4040                'post_name'    => 'my_template',
    4141                'post_title'   => 'My Template',
    42                 'post_content' => '<!-- wp:heading {"level":1} --><h1>Template</h1><!-- /wp:heading -->',
     42                'post_content' => '<!-- wp:heading {"level":1,"metadata":{"ignoredHookedBlocks":["tests/ignored"]}} --><h1>Template</h1><!-- /wp:heading -->',
    4343                'post_excerpt' => 'Description of my template',
    4444                'tax_input'    => array(
     
    5858                'post_name'    => 'my_template_part',
    5959                'post_title'   => 'My Template Part',
    60                 'post_content' => '<!-- wp:heading {"level":2} --><h2>Template Part</h2><!-- /wp:heading -->',
     60                'post_content' => '<!-- wp:heading {"level":2,"metadata":{"ignoredHookedBlocks":["tests/ignored"]}} --><h2>Template Part</h2><!-- /wp:heading -->',
    6161                'post_excerpt' => 'Description of my template part',
    6262                'tax_input'    => array(
  • trunk/tests/phpunit/tests/block-templates/buildBlockTemplateResultFromPost.php

    r57594 r57627  
    1919        if ( $registry->is_registered( 'tests/my-block' ) ) {
    2020            $registry->unregister( 'tests/my-block' );
     21        }
     22
     23        if ( $registry->is_registered( 'tests/ignored' ) ) {
     24            $registry->unregister( 'tests/ignored' );
    2125        }
    2226
     
    6872    /**
    6973     * @ticket 59646
     74     * @ticket 60506
    7075     */
    7176    public function test_should_inject_hooked_block_into_template() {
     
    8489        );
    8590        $this->assertStringStartsWith( '<!-- wp:tests/my-block /-->', $template->content );
    86         $this->assertStringContainsString( '"metadata":{"ignoredHookedBlocks":["tests/my-block"]}', $template->content );
    8791    }
    8892
    8993    /**
    9094     * @ticket 59646
     95     * @ticket 60506
    9196     */
    9297    public function test_should_inject_hooked_block_into_template_part() {
     
    105110        );
    106111        $this->assertStringEndsWith( '<!-- wp:tests/my-block /-->', $template_part->content );
    107         $this->assertStringContainsString( '"metadata":{"ignoredHookedBlocks":["tests/my-block"]}', $template_part->content );
     112    }
     113
     114    /**
     115     * @ticket 59646
     116     * @ticket 60506
     117     */
     118    public function test_should_not_inject_ignored_hooked_block_into_template() {
     119        register_block_type(
     120            'tests/ignored',
     121            array(
     122                'block_hooks' => array(
     123                    'core/heading' => 'after',
     124                ),
     125            )
     126        );
     127
     128        $template = _build_block_template_result_from_post(
     129            self::$template_post,
     130            'wp_template'
     131        );
     132        $this->assertStringNotContainsString( '<!-- wp:tests/ignored /-->', $template->content );
     133    }
     134
     135    /**
     136     * @ticket 59646
     137     * @ticket 60506
     138     */
     139    public function test_should_not_inject_ignored_hooked_block_into_template_part() {
     140        register_block_type(
     141            'tests/ignored',
     142            array(
     143                'block_hooks' => array(
     144                    'core/heading' => 'after',
     145                ),
     146            )
     147        );
     148
     149        $template_part = _build_block_template_result_from_post(
     150            self::$template_part_post,
     151            'wp_template_part'
     152        );
     153        $this->assertStringNotContainsString( '<!-- wp:tests/ignored /-->', $template_part->content );
    108154    }
    109155}
  • trunk/tests/phpunit/tests/blocks/getHookedBlocks.php

    r57172 r57627  
    137137     * @ticket 59313
    138138     * @ticket 60008
     139     * @ticket 60506
    139140     *
    140141     * @covers ::get_hooked_blocks
     
    151152        );
    152153        $this->assertStringContainsString(
    153             '<!-- wp:post-content {"layout":{"type":"constrained"},"metadata":{"ignoredHookedBlocks":["tests/hooked-after"]}} /-->'
     154            '<!-- wp:post-content {"layout":{"type":"constrained"}} /-->'
    154155            . '<!-- wp:tests/hooked-after /-->',
    155156            $template->content
     
    168169     * @ticket 59313
    169170     * @ticket 60008
     171     * @ticket 60506
    170172     *
    171173     * @covers ::get_hooked_blocks
     
    179181        $this->assertStringContainsString(
    180182            '<!-- wp:tests/hooked-before /-->'
    181             . '<!-- wp:navigation {"layout":{"type":"flex","setCascadingProperties":true,"justifyContent":"right"},"metadata":{"ignoredHookedBlocks":["tests/hooked-before"]}} /-->',
     183            . '<!-- wp:navigation {"layout":{"type":"flex","setCascadingProperties":true,"justifyContent":"right"}} /-->',
    182184            $template->content
    183185        );
     
    199201     * @ticket 59313
    200202     * @ticket 60008
     203     * @ticket 60506
    201204     *
    202205     * @covers ::get_hooked_blocks
     
    219222        );
    220223        $this->assertStringContainsString(
    221             '<!-- wp:comments {"metadata":{"ignoredHookedBlocks":["tests/hooked-first-child"]}} -->'
     224            '<!-- wp:comments -->'
    222225            . '<div class="wp-block-comments">'
    223226            . '<!-- wp:tests/hooked-first-child /-->',
  • trunk/tests/phpunit/tests/blocks/insertHookedBlocks.php

    r57354 r57627  
    2626     * @ticket 59572
    2727     * @ticket 60126
     28     * @ticket 60506
    2829     *
    2930     * @covers ::insert_hooked_blocks
    3031     */
    31     public function test_insert_hooked_blocks_adds_metadata() {
     32    public function test_insert_hooked_blocks_returns_correct_markup() {
    3233        $anchor_block = array(
    3334            'blockName' => self::ANCHOR_BLOCK_TYPE,
     
    3536
    3637        $actual = insert_hooked_blocks( $anchor_block, 'after', self::HOOKED_BLOCKS, array() );
    37         $this->assertSame(
    38             array( self::HOOKED_BLOCK_TYPE ),
    39             $anchor_block['attrs']['metadata']['ignoredHookedBlocks'],
    40             "Hooked block type wasn't added to ignoredHookedBlocks metadata."
    41         );
    4238        $this->assertSame(
    4339            '<!-- wp:' . self::HOOKED_BLOCK_TYPE . ' /-->',
     
    5046     * @ticket 59572
    5147     * @ticket 60126
     48     * @ticket 60506
    5249     *
    5350     * @covers ::insert_hooked_blocks
    5451     */
    55     public function test_insert_hooked_blocks_if_block_is_already_hooked() {
     52    public function test_insert_hooked_blocks_if_block_is_ignored() {
    5653        $anchor_block = array(
    5754            'blockName' => 'tests/anchor-block',
     
    6562        $actual = insert_hooked_blocks( $anchor_block, 'after', self::HOOKED_BLOCKS, array() );
    6663        $this->assertSame(
    67             array( self::HOOKED_BLOCK_TYPE ),
    68             $anchor_block['attrs']['metadata']['ignoredHookedBlocks'],
    69             "ignoredHookedBlocks metadata shouldn't have been modified."
    70         );
    71         $this->assertSame(
    7264            '',
    7365            $actual,
     
    7971     * @ticket 59572
    8072     * @ticket 60126
     73     * @ticket 60506
    8174     *
    8275     * @covers ::insert_hooked_blocks
    8376     */
    84     public function test_insert_hooked_blocks_adds_to_ignored_hooked_blocks() {
     77    public function test_insert_hooked_blocks_if_other_block_is_ignored() {
    8578        $anchor_block = array(
    8679            'blockName' => 'tests/anchor-block',
     
    9487        $actual = insert_hooked_blocks( $anchor_block, 'before', self::HOOKED_BLOCKS, array() );
    9588        $this->assertSame(
    96             array( self::HOOKED_BLOCK_TYPE, self::OTHER_HOOKED_BLOCK_TYPE ),
    97             $anchor_block['attrs']['metadata']['ignoredHookedBlocks'],
    98             "Newly hooked block should've been added to ignoredHookedBlocks metadata while retaining previously ignored one."
    99         );
    100         $this->assertSame(
    10189            '<!-- wp:' . self::OTHER_HOOKED_BLOCK_TYPE . ' /-->',
    10290            $actual,
     
    10896     * @ticket 59572
    10997     * @ticket 60126
     98     * @ticket 60506
    11099     *
    111100     * @covers ::insert_hooked_blocks
     
    141130
    142131        $this->assertSame(
    143             array( self::HOOKED_BLOCK_TYPE ),
    144             $anchor_block['attrs']['metadata']['ignoredHookedBlocks'],
    145             "Hooked block type wasn't added to ignoredHookedBlocks metadata."
    146         );
    147         $this->assertSame(
    148132            '<!-- wp:' . self::HOOKED_BLOCK_TYPE . ' {"layout":{"type":"constrained"}} /-->',
    149133            $actual,
     
    155139     * @ticket 59572
    156140     * @ticket 60126
     141     * @ticket 60506
    157142     *
    158143     * @covers ::insert_hooked_blocks
     
    191176
    192177        $this->assertSame(
    193             array( self::HOOKED_BLOCK_TYPE ),
    194             $anchor_block['attrs']['metadata']['ignoredHookedBlocks'],
    195             "Hooked block type wasn't added to ignoredHookedBlocks metadata."
    196         );
    197         $this->assertSame(
    198178            '<!-- wp:group --><div class="wp-block-group"><!-- wp:' . self::HOOKED_BLOCK_TYPE . ' /--></div><!-- /wp:group -->',
    199179            $actual,
  • trunk/tests/phpunit/tests/blocks/wpBlockPatternsRegistry.php

    r57172 r57627  
    345345     * @ticket 59476
    346346     * @ticket 60008
     347     * @ticket 60506
    347348     *
    348349     * @covers WP_Block_Patterns_Registry::register
     
    386387        $this->assertCount( 3, $registered );
    387388        $this->assertStringEndsWith( '<!-- wp:tests/my-block /-->', $registered[1]['content'] );
    388         $this->assertStringContainsString( '"metadata":{"ignoredHookedBlocks":["tests/my-block"]}', $registered[1]['content'] );
    389389        $this->assertStringEndsWith( '<!-- wp:tests/my-block /-->', $registered[2]['content'] );
    390         $this->assertStringContainsString( '"metadata":{"ignoredHookedBlocks":["tests/my-block"]}', $registered[2]['content'] );
    391390    }
    392391
     
    419418     * @ticket 59476
    420419     * @ticket 60008
     420     * @ticket 60506
    421421     *
    422422     * @covers WP_Block_Patterns_Registry::register
     
    447447        $pattern = $this->registry->get_registered( 'test/one' );
    448448        $this->assertStringStartsWith( '<!-- wp:tests/my-block /-->', $pattern['content'] );
    449         $this->assertStringContainsString( '"metadata":{"ignoredHookedBlocks":["tests/my-block"]}', $pattern['content'] );
    450449    }
    451450
Note: See TracChangeset for help on using the changeset viewer.