<!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>[56995] branches/6.4: Blocks: Fix layout support to be compatible with enhanced pagination.</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/56995">56995</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/56995","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>2023-10-24 09:02:02 +0000 (Tue, 24 Oct 2023)</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'>Blocks: Fix layout support to be compatible with enhanced pagination.

Make layout support compatible with enhanced pagination by ensuring that generated class names are stable across pagination, even when the number of rendered posts is different.

With the previous implementation of enhanced pagination, the CSS corresponding to each block was not detected. Therefore, for enhanced pagination to work correctly, the CSS of the blocks present in the Post Template must be stable on all pages.

The number of posts rendered by the Query block is always the same, except in the last page, where it can be only a fraction. If any of the blocks rendered by the Post Template used the `wp_unique_id` function, the ID (which is incremental) would have been different than in the previous pages and the class names would have varied.

This is remediated by this changeset by replacing the usage of `wp_unique_id` in the layout support (which is used by the Query block) with an implementation that uses IDs that are incremental only for that block. That way, the generated class names are never affected by the number of times `wp_unique_id` runs.

Props luisherranz, andrewserong, isabel_brison, costdev, mukesh27, cbravobernal, hellofromTonya, jorbin.
Merges <a href="https://core.trac.wordpress.org/changeset/56994">[56994]</a> to the 6.4 branch.
Fixes <a href="https://core.trac.wordpress.org/ticket/59681">#59681</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#branches64srcwpincludesblocksupportslayoutphp">branches/6.4/src/wp-includes/block-supports/layout.php</a></li>
<li><a href="#branches64srcwpincludesfunctionsphp">branches/6.4/src/wp-includes/functions.php</a></li>
<li><a href="#branches64testsphpunittestsblocksrenderphp">branches/6.4/tests/phpunit/tests/blocks/render.php</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#branches64testsphpunittestsfunctionswpUniquePrefixedIdphp">branches/6.4/tests/phpunit/tests/functions/wpUniquePrefixedId.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="branches64srcwpincludesblocksupportslayoutphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: branches/6.4/src/wp-includes/block-supports/layout.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- branches/6.4/src/wp-includes/block-supports/layout.php    2023-10-24 08:49:38 UTC (rev 56994)
+++ branches/6.4/src/wp-includes/block-supports/layout.php      2023-10-24 09:02:02 UTC (rev 56995)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -630,8 +630,17 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        $class_names        = array();
</span><span class="cx" style="display: block; padding: 0 10px">        $layout_definitions = wp_get_layout_definitions();
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        $container_class    = wp_unique_id( 'wp-container-' );
</del><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        /*
+        * Uses an incremental ID that is independent per prefix to make sure that
+        * rendering different numbers of blocks doesn't affect the IDs of other
+        * blocks. Makes the CSS class names stable across paginations
+        * for features like the enhanced pagination of the Query block.
+        */
+       $container_class = wp_unique_prefixed_id(
+               'wp-container-' . sanitize_title( $block['blockName'] ) . '-layout-'
+       );
+
</ins><span class="cx" style="display: block; padding: 0 10px">         // Set the correct layout type for blocks using legacy content width.
</span><span class="cx" style="display: block; padding: 0 10px">        if ( isset( $used_layout['inherit'] ) && $used_layout['inherit'] || isset( $used_layout['contentSize'] ) && $used_layout['contentSize'] ) {
</span><span class="cx" style="display: block; padding: 0 10px">                $used_layout['type'] = 'constrained';
</span></span></pre></div>
<a id="branches64srcwpincludesfunctionsphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: branches/6.4/src/wp-includes/functions.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- branches/6.4/src/wp-includes/functions.php        2023-10-24 08:49:38 UTC (rev 56994)
+++ branches/6.4/src/wp-includes/functions.php  2023-10-24 09:02:02 UTC (rev 56995)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -7831,6 +7831,40 @@
</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">+ * Generates an incremental ID that is independent per each different prefix.
+ *
+ * It is similar to `wp_unique_id`, but each prefix has its own internal ID
+ * counter to make each prefix independent from each other. The ID starts at 1
+ * and increments on each call. The returned value is not universally unique,
+ * but it is unique across the life of the PHP process and it's stable per
+ * prefix.
+ *
+ * @since 6.4.0
+ *
+ * @param string $prefix Optional. Prefix for the returned ID. Default empty string.
+ * @return string Incremental ID per prefix.
+ */
+function wp_unique_prefixed_id( $prefix = '' ) {
+       static $id_counters = array();
+
+       if ( ! is_string( $prefix ) ) {
+               wp_trigger_error(
+                       __FUNCTION__,
+                       sprintf( 'The prefix must be a string. "%s" data type given.', gettype( $prefix ) )
+               );
+               $prefix = '';
+       }
+
+       if ( ! isset( $id_counters[ $prefix ] ) ) {
+               $id_counters[ $prefix ] = 0;
+       }
+
+       $id = ++$id_counters[ $prefix ];
+
+       return $prefix . (string) $id;
+}
+
+/**
</ins><span class="cx" style="display: block; padding: 0 10px">  * Gets last changed date for the specified cache group.
</span><span class="cx" style="display: block; padding: 0 10px">  *
</span><span class="cx" style="display: block; padding: 0 10px">  * @since 4.7.0
</span></span></pre></div>
<a id="branches64testsphpunittestsblocksrenderphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: branches/6.4/tests/phpunit/tests/blocks/render.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- branches/6.4/tests/phpunit/tests/blocks/render.php        2023-10-24 08:49:38 UTC (rev 56994)
+++ branches/6.4/tests/phpunit/tests/blocks/render.php  2023-10-24 09:02:02 UTC (rev 56995)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -218,9 +218,9 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $html = do_blocks( self::strip_r( file_get_contents( $html_path ) ) );
</span><span class="cx" style="display: block; padding: 0 10px">                // If blocks opt into Gutenberg's layout implementation
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                // the container will receive an added classname of `wp_unique_id( 'wp-container-' )`
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         // the container will receive an additional, unique classname based on "wp-container-[blockname]-layout"
</ins><span class="cx" style="display: block; padding: 0 10px">                 // so we need to normalize the random id.
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $normalized_html = preg_replace( '/wp-container-\d+/', 'wp-container-1', $html );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $normalized_html = preg_replace( '/wp-container-[a-z-]+\d+/', 'wp-container-1', $html );
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                // The gallery block uses a unique class name of `wp_unique_id( 'wp-block-gallery-' )`
</span><span class="cx" style="display: block; padding: 0 10px">                // so we need to normalize the random id.
</span></span></pre></div>
<a id="branches64testsphpunittestsfunctionswpUniquePrefixedIdphp"></a>
<div class="addfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Added: branches/6.4/tests/phpunit/tests/functions/wpUniquePrefixedId.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- branches/6.4/tests/phpunit/tests/functions/wpUniquePrefixedId.php                         (rev 0)
+++ branches/6.4/tests/phpunit/tests/functions/wpUniquePrefixedId.php   2023-10-24 09:02:02 UTC (rev 56995)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -0,0 +1,196 @@
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+<?php
+
+/**
+ * Test cases for the `wp_unique_prefixed_id()` function.
+ *
+ * @package WordPress\UnitTests
+ *
+ * @since 6.4.0
+ *
+ * @group functions.php
+ * @covers ::wp_unique_prefixed_id
+ */
+class Tests_Functions_WpUniquePrefixedId extends WP_UnitTestCase {
+
+       /**
+        * Tests that the expected unique prefixed IDs are created.
+        *
+        * @ticket 59681
+        *
+        * @dataProvider data_should_create_unique_prefixed_ids
+        *
+        * @runInSeparateProcess
+        * @preserveGlobalState disabled
+        *
+        * @param mixed $prefix   The prefix.
+        * @param array $expected The next two expected IDs.
+        */
+       public function test_should_create_unique_prefixed_ids( $prefix, $expected ) {
+               $id1 = wp_unique_prefixed_id( $prefix );
+               $id2 = wp_unique_prefixed_id( $prefix );
+
+               $this->assertNotSame( $id1, $id2, 'The IDs are not unique.' );
+               $this->assertSame( $expected, array( $id1, $id2 ), 'The IDs did not match the expected values.' );
+       }
+
+       /**
+        * Data provider.
+        *
+        * @return array[]
+        */
+       public function data_should_create_unique_prefixed_ids() {
+               return array(
+                       'prefix as empty string'       => array(
+                               'prefix'   => '',
+                               'expected' => array( '1', '2' ),
+                       ),
+                       'prefix as (string) "0"'       => array(
+                               'prefix'   => '0',
+                               'expected' => array( '01', '02' ),
+                       ),
+                       'prefix as string'             => array(
+                               'prefix'   => 'test',
+                               'expected' => array( 'test1', 'test2' ),
+                       ),
+                       'prefix as string with spaces' => array(
+                               'prefix'   => '   ',
+                               'expected' => array( '   1', '   2' ),
+                       ),
+                       'prefix as (string) "1"'       => array(
+                               'prefix'   => '1',
+                               'expected' => array( '11', '12' ),
+                       ),
+                       'prefix as a (string) "."'     => array(
+                               'prefix'   => '.',
+                               'expected' => array( '.1', '.2' ),
+                       ),
+                       'prefix as a block name'       => array(
+                               'prefix'   => 'core/list-item',
+                               'expected' => array( 'core/list-item1', 'core/list-item2' ),
+                       ),
+               );
+       }
+
+       /**
+        * @ticket 59681
+        *
+        * @dataProvider data_should_raise_notice_and_use_empty_string_prefix_when_nonstring_given
+        *
+        * @runInSeparateProcess
+        * @preserveGlobalState disabled
+        *
+        * @param mixed  $non_string_prefix         Non-string prefix.
+        * @param int    $number_of_ids_to_generate Number of IDs to generate.
+        *                                          As the prefix will default to an empty string, changing the number of IDs generated within each dataset further tests ID uniqueness.
+        * @param string $expected_message          Expected notice message.
+        * @param array  $expected_ids              Expected unique IDs.
+        */
+       public function test_should_raise_notice_and_use_empty_string_prefix_when_nonstring_given( $non_string_prefix, $number_of_ids_to_generate, $expected_message, $expected_ids ) {
+               $this->expectNotice();
+               $this->expectNoticeMessage( $expected_message );
+
+               $ids = array();
+               for ( $i = 0; $i < $number_of_ids_to_generate; $i++ ) {
+                       $ids[] = wp_unique_prefixed_id( $non_string_prefix );
+               }
+
+               $this->assertSameSets( $ids, array_unique( $ids ), 'IDs are not unique.' );
+               $this->assertSameSets( $expected_ids, $ids, 'The IDs did not match the expected values.' );
+       }
+
+       /**
+        * Data provider.
+        *
+        * @return array[]
+        */
+       public function data_should_raise_notice_and_use_empty_string_prefix_when_nonstring_given() {
+               $message = 'wp_unique_prefixed_id(): The prefix must be a string. "%s" data type given.';
+               return array(
+                       'prefix as null'          => array(
+                               'non_string_prefix'         => null,
+                               'number_of_ids_to_generate' => 2,
+                               'expected_message'          => sprintf( $message, 'NULL' ),
+                               'expected_ids'              => array( '1', '2' ),
+                       ),
+                       'prefix as (int) 0'       => array(
+                               'non_string_prefix'         => 0,
+                               'number_of_ids_to_generate' => 3,
+                               'expected_message'          => sprintf( $message, 'integer' ),
+                               'expected_ids'              => array( '1', '2', '3' ),
+                       ),
+                       'prefix as (int) 1'       => array(
+                               'non_string_prefix'         => 1,
+                               'number_of_ids_to_generate' => 4,
+                               'expected_data_type'        => sprintf( $message, 'integer' ),
+                               'expected_ids'              => array( '1', '2', '3', '4' ),
+                       ),
+                       'prefix as (bool) false'  => array(
+                               'non_string_prefix'         => false,
+                               'number_of_ids_to_generate' => 5,
+                               'expected_data_type'        => sprintf( $message, 'boolean' ),
+                               'expected_ids'              => array( '1', '2', '3', '4', '5' ),
+                       ),
+                       'prefix as (double) 98.7' => array(
+                               'non_string_prefix'         => 98.7,
+                               'number_of_ids_to_generate' => 6,
+                               'expected_data_type'        => sprintf( $message, 'double' ),
+                               'expected_ids'              => array( '1', '2', '3', '4', '5', '6' ),
+                       ),
+               );
+       }
+
+       /**
+        * Prefixes that are or will become the same should generate unique IDs.
+        *
+        * This test is added to avoid future regressions if the function's prefix data type check is
+        * modified to type juggle or check for scalar data types.
+        *
+        * @ticket 59681
+        *
+        * @dataProvider data_same_prefixes_should_generate_unique_ids
+        *
+        * @runInSeparateProcess
+        * @preserveGlobalState disabled
+        *
+        * @param array $prefixes The prefixes to check.
+        * @param array $expected The expected unique IDs.
+        */
+       public function test_same_prefixes_should_generate_unique_ids( array $prefixes, array $expected ) {
+               // Suppress E_USER_NOTICE, which will be raised when a prefix is non-string.
+               $original_error_reporting = error_reporting();
+               error_reporting( $original_error_reporting & ~E_USER_NOTICE );
+
+               $ids = array();
+               foreach ( $prefixes as $prefix ) {
+                       $ids[] = wp_unique_prefixed_id( $prefix );
+               }
+
+               // Reset error reporting.
+               error_reporting( $original_error_reporting );
+
+               $this->assertSameSets( $ids, array_unique( $ids ), 'IDs are not unique.' );
+               $this->assertSameSets( $expected, $ids, 'The IDs did not match the expected values.' );
+       }
+
+       /**
+        * Data provider.
+        *
+        * @return array[]
+        */
+       public function data_same_prefixes_should_generate_unique_ids() {
+               return array(
+                       'prefixes = empty string' => array(
+                               'prefixes' => array( null, true, '' ),
+                               'expected' => array( '1', '2', '3' ),
+                       ),
+                       'prefixes = 0'            => array(
+                               'prefixes' => array( '0', 0, 0.0, false ),
+                               'expected' => array( '01', '1', '2', '3' ),
+                       ),
+                       'prefixes = 1'            => array(
+                               'prefixes' => array( '1', 1, 1.0, true ),
+                               'expected' => array( '11', '1', '2', '3' ),
+                       ),
+               );
+       }
+}
</ins></span></pre>
</div>
</div>

</body>
</html>