[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/block-supports/ -> layout.php (source)

   1  <?php
   2  /**
   3   * Layout block support flag.
   4   *
   5   * @package WordPress
   6   * @since 5.8.0
   7   */
   8  
   9  /**
  10   * Gets the first style variation name from a className string that matches a registered style.
  11   *
  12   * @since 7.0.0
  13   *
  14   * @param string                              $class_name        CSS class string for a block.
  15   * @param array<string, array<string, mixed>> $registered_styles Currently registered block styles.
  16   * @return string|null The name of the first registered variation, or null if none found.
  17   */
  18  function wp_get_block_style_variation_name_from_registered_style( string $class_name, array $registered_styles = array() ): ?string {
  19      if ( ! $class_name ) {
  20          return null;
  21      }
  22  
  23      $registered_names = array_filter( array_column( $registered_styles, 'name' ) );
  24  
  25      $prefix = 'is-style-';
  26      $length = strlen( $prefix );
  27  
  28      foreach ( explode( ' ', $class_name ) as $class ) {
  29          if ( str_starts_with( $class, $prefix ) ) {
  30              $variation = substr( $class, $length );
  31              if ( 'default' !== $variation && in_array( $variation, $registered_names, true ) ) {
  32                  return $variation;
  33              }
  34          }
  35      }
  36  
  37      return null;
  38  }
  39  
  40  /**
  41   * Returns the child-layout-only subset of a layout object.
  42   *
  43   * @since 7.1.0
  44   *
  45   * @param mixed $layout Layout object.
  46   * @return array Child layout values, or an empty array.
  47   */
  48  function wp_get_layout_child_values( $layout ) {
  49      if ( ! is_array( $layout ) ) {
  50          return array();
  51      }
  52  
  53      return array_intersect_key(
  54          $layout,
  55          array_flip( array( 'selfStretch', 'flexSize', 'columnStart', 'columnSpan', 'rowStart', 'rowSpan' ) )
  56      );
  57  }
  58  
  59  /**
  60   * Returns the container-layout subset of a layout object.
  61   *
  62   * @since 7.1.0
  63   *
  64   * @param mixed $layout Layout object.
  65   * @return array Container layout values, or an empty array.
  66   */
  67  function wp_get_layout_container_values( $layout ) {
  68      if ( ! is_array( $layout ) ) {
  69          return array();
  70      }
  71  
  72      return array_diff_key(
  73          $layout,
  74          array_flip( array( 'selfStretch', 'flexSize', 'columnStart', 'columnSpan', 'rowStart', 'rowSpan' ) )
  75      );
  76  }
  77  
  78  /**
  79   * Sanitizes a block gap value before layout style generation.
  80   *
  81   * @since 7.1.0
  82   *
  83   * @param string|array|null $gap_value Block gap value.
  84   * @return string|array|null Sanitized block gap value.
  85   */
  86  function wp_sanitize_block_gap_value( $gap_value ) {
  87      if ( is_array( $gap_value ) ) {
  88          foreach ( $gap_value as $key => $value ) {
  89              $gap_value[ $key ] = ! is_scalar( $value ) || ( $value && preg_match( '%[\\\(&=}]|/\*%', (string) $value ) ) ? null : $value;
  90          }
  91  
  92          return $gap_value;
  93      }
  94  
  95      return $gap_value && preg_match( '%[\\\(&=}]|/\*%', $gap_value ) ? null : $gap_value;
  96  }
  97  
  98  /**
  99   * Returns child layout styles for a block affected by its parent's layout.
 100   *
 101   * @since 7.1.0
 102   *
 103   * @param string     $selector           CSS selector.
 104   * @param array      $child_layout       Child layout values.
 105   * @param array      $parent_layout      Parent layout values.
 106   * @param array|null $viewport_overrides Optional. Child viewport layout overrides to emit.
 107   * @return array Child layout style rules.
 108   */
 109  function wp_get_child_layout_style_rules( $selector, $child_layout, $parent_layout = array(), $viewport_overrides = null ) {
 110      $base_child_layout              = is_array( $child_layout ) ? $child_layout : array();
 111      $viewport_overrides             = is_array( $viewport_overrides ) ? $viewport_overrides : null;
 112      $child_layout                   = null === $viewport_overrides ? $base_child_layout : array_replace( $base_child_layout, $viewport_overrides );
 113      $child_layout_declarations      = array();
 114      $child_layout_styles            = array();
 115      $has_viewport_property_override = static function ( $property ) use ( $viewport_overrides ) {
 116          return array_key_exists( $property, $viewport_overrides );
 117      };
 118  
 119      $self_stretch      = $child_layout['selfStretch'] ?? null;
 120      $base_self_stretch = $base_child_layout['selfStretch'] ?? null;
 121  
 122      /*
 123       * These are the serialized `selfStretch` values. `max` used to be called
 124       * "Fixed" in the UI, but was renamed and replaced by `fixedNoShrink`.
 125       */
 126      $flex_child_layout_values = array(
 127          'fit'   => 'fit',
 128          'grow'  => 'fill',
 129          'max'   => 'fixed',
 130          'fixed' => 'fixedNoShrink',
 131      );
 132      $flex_size_values         = array(
 133          $flex_child_layout_values['max'],
 134          $flex_child_layout_values['fixed'],
 135      );
 136  
 137      if ( null === $viewport_overrides || $has_viewport_property_override( 'selfStretch' ) || $has_viewport_property_override( 'flexSize' ) ) {
 138          if (
 139              null !== $viewport_overrides &&
 140              ( $flex_child_layout_values['fit'] === $self_stretch || $flex_child_layout_values['grow'] === $self_stretch ) &&
 141              in_array( $base_self_stretch, $flex_size_values, true ) &&
 142              isset( $base_child_layout['flexSize'] )
 143          ) {
 144              $child_layout_declarations['flex-basis'] = 'unset';
 145              if ( $flex_child_layout_values['fixed'] === $base_self_stretch ) {
 146                  $child_layout_declarations['flex-shrink'] = 'unset';
 147              }
 148          }
 149          if ( in_array( $self_stretch, $flex_size_values, true ) && isset( $child_layout['flexSize'] ) ) {
 150              $child_layout_declarations['flex-basis'] = $child_layout['flexSize'];
 151              if ( $flex_child_layout_values['fixed'] === $self_stretch ) {
 152                  $child_layout_declarations['flex-shrink'] = '0';
 153              } elseif ( null !== $viewport_overrides && $flex_child_layout_values['fixed'] === $base_self_stretch ) {
 154                  $child_layout_declarations['flex-shrink'] = 'unset';
 155              }
 156              $child_layout_declarations['box-sizing'] = 'border-box';
 157          } elseif ( $flex_child_layout_values['grow'] === $self_stretch ) {
 158              $child_layout_declarations['flex-grow'] = '1';
 159          }
 160      }
 161  
 162      /*
 163       * Grid line numbers and spans are whole numbers. The editor stores them as numbers, but
 164       * content saved by WordPress 6.3 to 6.6 stored them as numeric strings, and that
 165       * migration only runs when a block is parsed in JavaScript, so the front end still sees
 166       * strings. Accept any numeric value and cast it, and treat anything else as absent
 167       * because it can't render as valid CSS.
 168       */
 169      $column_start_attr = $child_layout['columnStart'] ?? null;
 170      $column_start      = is_numeric( $column_start_attr ) ? (int) $column_start_attr : null;
 171      $column_span_attr  = $child_layout['columnSpan'] ?? null;
 172      $column_span       = is_numeric( $column_span_attr ) ? (int) $column_span_attr : null;
 173      if ( null === $viewport_overrides || $has_viewport_property_override( 'columnStart' ) || $has_viewport_property_override( 'columnSpan' ) ) {
 174          if ( $column_start && $column_span ) {
 175              $child_layout_declarations['grid-column'] = "$column_start / span $column_span";
 176          } elseif ( $column_start ) {
 177              $child_layout_declarations['grid-column'] = "$column_start";
 178          } elseif ( $column_span ) {
 179              $child_layout_declarations['grid-column'] = "span $column_span";
 180          }
 181      }
 182  
 183      $row_start_attr = $child_layout['rowStart'] ?? null;
 184      $row_start      = is_numeric( $row_start_attr ) ? (int) $row_start_attr : null;
 185      $row_span_attr  = $child_layout['rowSpan'] ?? null;
 186      $row_span       = is_numeric( $row_span_attr ) ? (int) $row_span_attr : null;
 187      if ( null === $viewport_overrides || $has_viewport_property_override( 'rowStart' ) || $has_viewport_property_override( 'rowSpan' ) ) {
 188          if ( $row_start && $row_span ) {
 189              $child_layout_declarations['grid-row'] = "$row_start / span $row_span";
 190          } elseif ( $row_start ) {
 191              $child_layout_declarations['grid-row'] = "$row_start";
 192          } elseif ( $row_span ) {
 193              $child_layout_declarations['grid-row'] = "span $row_span";
 194          }
 195      }
 196  
 197      if ( ! empty( $child_layout_declarations ) ) {
 198          $child_layout_styles[] = array(
 199              'selector'     => $selector,
 200              'declarations' => $child_layout_declarations,
 201          );
 202      }
 203  
 204      $minimum_column_width_attr = $parent_layout['minimumColumnWidth'] ?? null;
 205      $minimum_column_width      = is_string( $minimum_column_width_attr ) ? $minimum_column_width_attr : null;
 206      $column_count              = $parent_layout['columnCount'] ?? null;
 207  
 208      /*
 209       * If columnSpan or columnStart is set, and the parent grid is responsive, i.e. if it has a minimumColumnWidth set,
 210       * the columnSpan should be removed once the grid is smaller than the span, and columnStart should be removed
 211       * once the grid has less columns than the start.
 212       * If there's a minimumColumnWidth, the grid is responsive. But if the minimumColumnWidth value wasn't changed, it won't be set.
 213       * In that case, if columnCount doesn't exist, we can assume that the grid is responsive.
 214       */
 215      if ( null === $viewport_overrides && ( $column_span || $column_start ) && ( $minimum_column_width || ! $column_count ) ) {
 216          $column_span_number  = floatval( $column_span );
 217          $column_start_number = floatval( $column_start );
 218          $parent_column_width = $minimum_column_width ? $minimum_column_width : '12rem';
 219          $parent_column_value = floatval( $parent_column_width );
 220          $parent_column_unit  = explode( $parent_column_value, $parent_column_width );
 221  
 222          $num_cols_to_break_at = 2;
 223          if ( $column_span_number && $column_start_number ) {
 224              $num_cols_to_break_at = $column_start_number + $column_span_number - 1;
 225          } elseif ( $column_span_number ) {
 226              $num_cols_to_break_at = $column_span_number;
 227          } else {
 228              $num_cols_to_break_at = $column_start_number;
 229          }
 230  
 231          /*
 232           * If there is no unit, the width has somehow been mangled so we reset both unit and value
 233           * to defaults.
 234           * Additionally, the unit should be one of px, rem or em, so that also needs to be checked.
 235           */
 236          if ( count( $parent_column_unit ) <= 1 ) {
 237              $parent_column_unit  = 'rem';
 238              $parent_column_value = 12;
 239          } else {
 240              $parent_column_unit = $parent_column_unit[1];
 241  
 242              if ( ! in_array( $parent_column_unit, array( 'px', 'rem', 'em' ), true ) ) {
 243                  $parent_column_unit = 'rem';
 244              }
 245          }
 246  
 247          /*
 248           * A default gap value is used for this computation because custom gap values may not be
 249           * viable to use in the computation of the container query value.
 250           */
 251          $default_gap_value             = 'px' === $parent_column_unit ? 24 : 1.5;
 252          $container_query_value         = $num_cols_to_break_at * $parent_column_value + ( $num_cols_to_break_at - 1 ) * $default_gap_value;
 253          $minimum_container_query_value = $parent_column_value * 2 + $default_gap_value - 1;
 254          $container_query_value         = max( $container_query_value, $minimum_container_query_value ) . $parent_column_unit;
 255          // If a span is set we want to preserve it as long as possible, otherwise we just reset the value.
 256          $grid_column_value = $column_span && $column_span > 1 ? '1/-1' : 'auto';
 257  
 258          $child_layout_styles[] = array(
 259              'rules_group'  => "@container (max-width: $container_query_value )",
 260              'selector'     => $selector,
 261              'declarations' => array(
 262                  'grid-column' => $grid_column_value,
 263                  'grid-row'    => 'auto',
 264              ),
 265          );
 266      }
 267  
 268      return $child_layout_styles;
 269  }
 270  
 271  /**
 272   * Returns layout definitions, keyed by layout type.
 273   *
 274   * Provides a common definition of slugs, classnames, base styles, and spacing styles for each layout type.
 275   * When making changes or additions to layout definitions, the corresponding JavaScript definitions should
 276   * also be updated.
 277   *
 278   * @since 6.3.0
 279   * @since 6.6.0 Updated specificity for compatibility with 0-1-0 global styles specificity.
 280   * @access private
 281   *
 282   * @return array[] Layout definitions.
 283   */
 284  function wp_get_layout_definitions() {
 285      $layout_definitions = array(
 286          'default'     => array(
 287              'name'          => 'default',
 288              'slug'          => 'flow',
 289              'className'     => 'is-layout-flow',
 290              'baseStyles'    => array(
 291                  array(
 292                      'selector' => ' > .alignleft',
 293                      'rules'    => array(
 294                          'float'               => 'left',
 295                          'margin-inline-start' => '0',
 296                          'margin-inline-end'   => '2em',
 297                      ),
 298                  ),
 299                  array(
 300                      'selector' => ' > .alignright',
 301                      'rules'    => array(
 302                          'float'               => 'right',
 303                          'margin-inline-start' => '2em',
 304                          'margin-inline-end'   => '0',
 305                      ),
 306                  ),
 307                  array(
 308                      'selector' => ' > .aligncenter',
 309                      'rules'    => array(
 310                          'margin-left'  => 'auto !important',
 311                          'margin-right' => 'auto !important',
 312                      ),
 313                  ),
 314              ),
 315              'spacingStyles' => array(
 316                  array(
 317                      'selector' => ' > :first-child',
 318                      'rules'    => array(
 319                          'margin-block-start' => '0',
 320                      ),
 321                  ),
 322                  array(
 323                      'selector' => ' > :last-child',
 324                      'rules'    => array(
 325                          'margin-block-end' => '0',
 326                      ),
 327                  ),
 328                  array(
 329                      'selector' => ' > *',
 330                      'rules'    => array(
 331                          'margin-block-start' => null,
 332                          'margin-block-end'   => '0',
 333                      ),
 334                  ),
 335              ),
 336          ),
 337          'constrained' => array(
 338              'name'          => 'constrained',
 339              'slug'          => 'constrained',
 340              'className'     => 'is-layout-constrained',
 341              'baseStyles'    => array(
 342                  array(
 343                      'selector' => ' > .alignleft',
 344                      'rules'    => array(
 345                          'float'               => 'left',
 346                          'margin-inline-start' => '0',
 347                          'margin-inline-end'   => '2em',
 348                      ),
 349                  ),
 350                  array(
 351                      'selector' => ' > .alignright',
 352                      'rules'    => array(
 353                          'float'               => 'right',
 354                          'margin-inline-start' => '2em',
 355                          'margin-inline-end'   => '0',
 356                      ),
 357                  ),
 358                  array(
 359                      'selector' => ' > .aligncenter',
 360                      'rules'    => array(
 361                          'margin-left'  => 'auto !important',
 362                          'margin-right' => 'auto !important',
 363                      ),
 364                  ),
 365                  array(
 366                      'selector' => ' > :where(:not(.alignleft):not(.alignright):not(.alignfull))',
 367                      'rules'    => array(
 368                          'max-width'    => 'var(--wp--style--global--content-size)',
 369                          'margin-left'  => 'auto !important',
 370                          'margin-right' => 'auto !important',
 371                      ),
 372                  ),
 373                  array(
 374                      'selector' => ' > .alignwide',
 375                      'rules'    => array(
 376                          'max-width' => 'var(--wp--style--global--wide-size)',
 377                      ),
 378                  ),
 379              ),
 380              'spacingStyles' => array(
 381                  array(
 382                      'selector' => ' > :first-child',
 383                      'rules'    => array(
 384                          'margin-block-start' => '0',
 385                      ),
 386                  ),
 387                  array(
 388                      'selector' => ' > :last-child',
 389                      'rules'    => array(
 390                          'margin-block-end' => '0',
 391                      ),
 392                  ),
 393                  array(
 394                      'selector' => ' > *',
 395                      'rules'    => array(
 396                          'margin-block-start' => null,
 397                          'margin-block-end'   => '0',
 398                      ),
 399                  ),
 400              ),
 401          ),
 402          'flex'        => array(
 403              'name'          => 'flex',
 404              'slug'          => 'flex',
 405              'className'     => 'is-layout-flex',
 406              'displayMode'   => 'flex',
 407              'baseStyles'    => array(
 408                  array(
 409                      'selector' => '',
 410                      'rules'    => array(
 411                          'flex-wrap'   => 'wrap',
 412                          'align-items' => 'center',
 413                      ),
 414                  ),
 415                  array(
 416                      'selector' => ' > :is(*, div)', // :is(*, div) instead of just * increases the specificity by 001.
 417                      'rules'    => array(
 418                          'margin' => '0',
 419                      ),
 420                  ),
 421              ),
 422              'spacingStyles' => array(
 423                  array(
 424                      'selector' => '',
 425                      'rules'    => array(
 426                          'gap' => null,
 427                      ),
 428                  ),
 429              ),
 430          ),
 431          'grid'        => array(
 432              'name'          => 'grid',
 433              'slug'          => 'grid',
 434              'className'     => 'is-layout-grid',
 435              'displayMode'   => 'grid',
 436              'baseStyles'    => array(
 437                  array(
 438                      'selector' => ' > :is(*, div)', // :is(*, div) instead of just * increases the specificity by 001.
 439                      'rules'    => array(
 440                          'margin' => '0',
 441                      ),
 442                  ),
 443              ),
 444              'spacingStyles' => array(
 445                  array(
 446                      'selector' => '',
 447                      'rules'    => array(
 448                          'gap' => null,
 449                      ),
 450                  ),
 451              ),
 452          ),
 453      );
 454  
 455      return $layout_definitions;
 456  }
 457  
 458  /**
 459   * Registers the layout block attribute for block types that support it.
 460   *
 461   * @since 5.8.0
 462   * @since 6.3.0 Check for layout support via the `layout` key with fallback to `__experimentalLayout`.
 463   * @access private
 464   *
 465   * @param WP_Block_Type $block_type Block Type.
 466   */
 467  function wp_register_layout_support( $block_type ) {
 468      $support_layout = block_has_support( $block_type, 'layout', false ) || block_has_support( $block_type, '__experimentalLayout', false );
 469      if ( $support_layout ) {
 470          if ( ! $block_type->attributes ) {
 471              $block_type->attributes = array();
 472          }
 473  
 474          if ( ! array_key_exists( 'layout', $block_type->attributes ) ) {
 475              $block_type->attributes['layout'] = array(
 476                  'type' => 'object',
 477              );
 478          }
 479      }
 480  }
 481  
 482  /**
 483   * Generates the CSS corresponding to the provided layout.
 484   *
 485   * @since 5.9.0
 486   * @since 6.1.0 Added `$block_spacing` param, use style engine to enqueue styles.
 487   * @since 6.3.0 Added grid layout type.
 488   * @since 6.6.0 Removed duplicated selector from layout styles.
 489   *              Enabled negative margins for alignfull children of blocks with custom padding.
 490   * @since 7.1.0 Added options array with options to process responsive styles.
 491   * @access private
 492   *
 493   * @param string               $selector                      CSS selector.
 494   * @param array                $layout                        Layout object. The one that is passed has already checked
 495   *                                                            the existence of default block layout.
 496   * @param bool                 $has_block_gap_support         Optional. Whether the theme has support for the block gap. Default false.
 497   * @param string|string[]|null $gap_value                     Optional. The block gap value to apply. Default null.
 498   * @param bool                 $should_skip_gap_serialization Optional. Whether to skip applying the user-defined value set in the editor. Default false.
 499   * @param string|array         $fallback_gap_value            Optional. The block gap value to apply. If it's an array expected properties are "top" and/or "left". Default '0.5em'.
 500   * @param array|null           $block_spacing                 Optional. Custom spacing set on the block. Default null.
 501   * @param array                $options                       {
 502   *     Optional. Extra options for internal callers. Default empty array.
 503   *
 504   *     @type array       $viewport_overrides     An array of layout property overrides for the sake of style generation,
 505   *                                               keyed by property name.
 506   *     @type string|null $rules_group            Optional group name for the rules. Default null.
 507   *     @type bool        $has_block_gap_override Whether the block gap has been overridden. Default false.
 508   * }
 509   * @return string CSS styles on success. Else, empty string.
 510   */
 511  function wp_get_layout_style( $selector, $layout, $has_block_gap_support = false, $gap_value = null, $should_skip_gap_serialization = false, $fallback_gap_value = '0.5em', $block_spacing = null, $options = array() ) {
 512      $base_layout             = is_array( $layout ) ? $layout : array();
 513      $viewport_overrides      = $options['viewport_overrides'] ?? null;
 514      $layout_for_styles       = null === $viewport_overrides ? $base_layout : array_replace( $base_layout, $viewport_overrides );
 515      $layout_type             = $base_layout['type'] ?? 'default';
 516      $rules_group             = $options['rules_group'] ?? null;
 517      $has_block_gap_override  = ! empty( $options['has_block_gap_override'] );
 518      $should_output_block_gap = null === $viewport_overrides || $has_block_gap_override;
 519  
 520      /*
 521       * Viewport styles only store changed fields. If a field is present with null,
 522       * the user cleared a value inherited from the default viewport, so check
 523       * whether the key exists rather than whether the value is truthy.
 524       */
 525      $has_viewport_property_override = static function ( $property ) use ( $viewport_overrides ) {
 526          return array_key_exists( $property, $viewport_overrides );
 527      };
 528      $layout_styles                  = array();
 529  
 530      if ( 'default' === $layout_type ) {
 531          if ( $has_block_gap_support && $should_output_block_gap ) {
 532              if ( is_array( $gap_value ) ) {
 533                  $gap_value = $gap_value['top'] ?? null;
 534              }
 535              if ( null !== $gap_value && ! $should_skip_gap_serialization ) {
 536                  // Get spacing CSS variable from preset value if provided.
 537                  if ( is_string( $gap_value ) && str_contains( $gap_value, 'var:preset|spacing|' ) ) {
 538                      $index_to_splice = strrpos( $gap_value, '|' ) + 1;
 539                      $slug            = _wp_to_kebab_case( substr( $gap_value, $index_to_splice ) );
 540                      $gap_value       = "var(--wp--preset--spacing--$slug)";
 541                  }
 542  
 543                  array_push(
 544                      $layout_styles,
 545                      array(
 546                          'selector'     => "$selector > *",
 547                          'declarations' => array(
 548                              'margin-block-start' => '0',
 549                              'margin-block-end'   => '0',
 550                          ),
 551                      ),
 552                      array(
 553                          'selector'     => "$selector > * + *",
 554                          'declarations' => array(
 555                              'margin-block-start' => $gap_value,
 556                              'margin-block-end'   => '0',
 557                          ),
 558                      )
 559                  );
 560              }
 561          }
 562      } elseif ( 'constrained' === $layout_type ) {
 563          // The schemas and editor UI only produce strings here, so treat a non-string
 564          // value as absent rather than casting it — it couldn't render as valid CSS anyway.
 565          $content_size_attr    = $layout_for_styles['contentSize'] ?? null;
 566          $content_size         = is_string( $content_size_attr ) ? $content_size_attr : '';
 567          $wide_size_attr       = $layout_for_styles['wideSize'] ?? null;
 568          $wide_size            = is_string( $wide_size_attr ) ? $wide_size_attr : '';
 569          $justify_content_attr = $layout_for_styles['justifyContent'] ?? null;
 570          $justify_content      = is_string( $justify_content_attr ) ? $justify_content_attr : 'center';
 571  
 572          // Check if viewport-specific ("override") values exist. Null values are valid and mean the user cleared a value inherited from the default viewport.
 573          $has_justify_content_override = null !== $viewport_overrides && $has_viewport_property_override( 'justifyContent' );
 574          $has_content_size_override    = null !== $viewport_overrides && $has_viewport_property_override( 'contentSize' );
 575          $has_wide_size_override       = null !== $viewport_overrides && $has_viewport_property_override( 'wideSize' );
 576  
 577          /*
 578           * Styles should be output either if there are no viewport overrides (this is the default case), or if the user has set a new viewport-specific
 579           * value for contentSize or wideSize. If a viewport clears a custom constrained size, reset to the global layout variable.
 580           */
 581          $should_output_constrained_sizes = null === $viewport_overrides || $has_content_size_override || $has_wide_size_override;
 582          $is_resetting_constrained_sizes  = null !== $viewport_overrides &&
 583              (
 584                  ( $has_content_size_override && ! $content_size ) ||
 585                  ( $has_wide_size_override && ! $wide_size )
 586              );
 587  
 588          // If a viewport clears a custom constrained size, reset to the global layout variable.
 589          $all_max_width_value  = $content_size
 590              ? $content_size
 591              : ( $wide_size && ! $has_content_size_override ? $wide_size : 'var(--wp--style--global--content-size, none)' );
 592          $wide_max_width_value = $wide_size
 593              ? $wide_size
 594              : ( $content_size && ! $has_wide_size_override ? $content_size : 'var(--wp--style--global--wide-size, none)' );
 595  
 596          // Make sure there is a single CSS rule, and all tags are stripped for security.
 597          $all_max_width_value  = safecss_filter_attr( explode( ';', $all_max_width_value )[0] );
 598          $wide_max_width_value = safecss_filter_attr( explode( ';', $wide_max_width_value )[0] );
 599  
 600          $margin_left  = 'left' === $justify_content ? '0 !important' : 'auto !important';
 601          $margin_right = 'right' === $justify_content ? '0 !important' : 'auto !important';
 602  
 603          if ( $should_output_constrained_sizes && ( $content_size || $wide_size || $is_resetting_constrained_sizes ) ) {
 604              $content_size_declarations = array(
 605                  'max-width' => $all_max_width_value,
 606              );
 607  
 608              if ( null === $viewport_overrides || $has_justify_content_override ) {
 609                  $content_size_declarations['margin-left']  = $margin_left;
 610                  $content_size_declarations['margin-right'] = $margin_right;
 611              }
 612  
 613              array_push(
 614                  $layout_styles,
 615                  array(
 616                      'selector'     => "$selector > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
 617                      'declarations' => $content_size_declarations,
 618                  ),
 619                  array(
 620                      'selector'     => "$selector > .alignwide",
 621                      'declarations' => array( 'max-width' => $wide_max_width_value ),
 622                  ),
 623                  array(
 624                      'selector'     => "$selector .alignfull",
 625                      'declarations' => array( 'max-width' => 'none' ),
 626                  )
 627              );
 628          }
 629  
 630          if ( null === $viewport_overrides && isset( $block_spacing ) ) {
 631              $block_spacing_values = wp_style_engine_get_styles(
 632                  array(
 633                      'spacing' => $block_spacing,
 634                  )
 635              );
 636  
 637              /*
 638               * Handle negative margins for alignfull children of blocks with custom padding set.
 639               * They're added separately because padding might only be set on one side.
 640               */
 641              if ( isset( $block_spacing_values['declarations']['padding-right'] ) ) {
 642                  $padding_right = $block_spacing_values['declarations']['padding-right'];
 643                  // Add unit if 0.
 644                  if ( '0' === $padding_right ) {
 645                      $padding_right = '0px';
 646                  }
 647                  $layout_styles[] = array(
 648                      'selector'     => "$selector > .alignfull",
 649                      'declarations' => array( 'margin-right' => "calc($padding_right * -1)" ),
 650                  );
 651              }
 652              if ( isset( $block_spacing_values['declarations']['padding-left'] ) ) {
 653                  $padding_left = $block_spacing_values['declarations']['padding-left'];
 654                  // Add unit if 0.
 655                  if ( '0' === $padding_left ) {
 656                      $padding_left = '0px';
 657                  }
 658                  $layout_styles[] = array(
 659                      'selector'     => "$selector > .alignfull",
 660                      'declarations' => array( 'margin-left' => "calc($padding_left * -1)" ),
 661                  );
 662              }
 663          }
 664  
 665          if ( $has_justify_content_override && ! $should_output_constrained_sizes ) {
 666              $layout_styles[] = array(
 667                  'selector'     => "$selector > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
 668                  'declarations' => array(
 669                      'margin-left'  => $margin_left,
 670                      'margin-right' => $margin_right,
 671                  ),
 672              );
 673          } elseif ( null === $viewport_overrides ) {
 674              if ( 'left' === $justify_content ) {
 675                  $layout_styles[] = array(
 676                      'selector'     => "$selector > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
 677                      'declarations' => array( 'margin-left' => '0 !important' ),
 678                  );
 679              }
 680  
 681              if ( 'right' === $justify_content ) {
 682                  $layout_styles[] = array(
 683                      'selector'     => "$selector > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
 684                      'declarations' => array( 'margin-right' => '0 !important' ),
 685                  );
 686              }
 687          }
 688  
 689          if ( $has_block_gap_support && $should_output_block_gap ) {
 690              if ( is_array( $gap_value ) ) {
 691                  $gap_value = $gap_value['top'] ?? null;
 692              }
 693              if ( null !== $gap_value && ! $should_skip_gap_serialization ) {
 694                  // Get spacing CSS variable from preset value if provided.
 695                  if ( is_string( $gap_value ) && str_contains( $gap_value, 'var:preset|spacing|' ) ) {
 696                      $index_to_splice = strrpos( $gap_value, '|' ) + 1;
 697                      $slug            = _wp_to_kebab_case( substr( $gap_value, $index_to_splice ) );
 698                      $gap_value       = "var(--wp--preset--spacing--$slug)";
 699                  }
 700  
 701                  array_push(
 702                      $layout_styles,
 703                      array(
 704                          'selector'     => "$selector > *",
 705                          'declarations' => array(
 706                              'margin-block-start' => '0',
 707                              'margin-block-end'   => '0',
 708                          ),
 709                      ),
 710                      array(
 711                          'selector'     => "$selector > * + *",
 712                          'declarations' => array(
 713                              'margin-block-start' => $gap_value,
 714                              'margin-block-end'   => '0',
 715                          ),
 716                      )
 717                  );
 718              }
 719          }
 720      } elseif ( 'flex' === $layout_type ) {
 721          $layout_orientation = $layout_for_styles['orientation'] ?? 'horizontal';
 722  
 723          $justify_content_options = array(
 724              'left'   => 'flex-start',
 725              'right'  => 'flex-end',
 726              'center' => 'center',
 727          );
 728  
 729          $vertical_alignment_options = array(
 730              'top'    => 'flex-start',
 731              'center' => 'center',
 732              'bottom' => 'flex-end',
 733          );
 734  
 735          if ( 'horizontal' === $layout_orientation ) {
 736              $justify_content_options    += array( 'space-between' => 'space-between' );
 737              $vertical_alignment_options += array( 'stretch' => 'stretch' );
 738          } else {
 739              $justify_content_options    += array( 'stretch' => 'stretch' );
 740              $vertical_alignment_options += array( 'space-between' => 'space-between' );
 741          }
 742  
 743          /*
 744           * Styles should be output either if there are no viewport overrides (this is the default case), or if the user has set a new viewport-specific
 745           * value for any of the flex properties.
 746           */
 747          $should_output_flex_wrap          = null === $viewport_overrides || $has_viewport_property_override( 'flexWrap' );
 748          $should_output_flex_orientation   = null === $viewport_overrides || $has_viewport_property_override( 'orientation' );
 749          $should_output_flex_justification = null === $viewport_overrides || $has_viewport_property_override( 'justifyContent' ) || $has_viewport_property_override( 'orientation' );
 750          $should_output_flex_alignment     = null === $viewport_overrides || $has_viewport_property_override( 'verticalAlignment' ) || $has_viewport_property_override( 'orientation' );
 751  
 752          if ( $should_output_flex_wrap && ! empty( $layout_for_styles['flexWrap'] ) && 'nowrap' === $layout_for_styles['flexWrap'] ) {
 753              $layout_styles[] = array(
 754                  'selector'     => $selector,
 755                  'declarations' => array( 'flex-wrap' => 'nowrap' ),
 756              );
 757          }
 758  
 759          if ( $has_block_gap_support && $should_output_block_gap && isset( $gap_value ) ) {
 760              $combined_gap_value = '';
 761              $gap_sides          = is_array( $gap_value ) ? array( 'top', 'left' ) : array( 'top' );
 762  
 763              foreach ( $gap_sides as $gap_side ) {
 764                  $process_value = $gap_value;
 765                  if ( is_array( $gap_value ) ) {
 766                      if ( is_array( $fallback_gap_value ) ) {
 767                          $fallback_value = $fallback_gap_value[ $gap_side ] ?? reset( $fallback_gap_value );
 768                      } else {
 769                          $fallback_value = $fallback_gap_value;
 770                      }
 771                      $process_value = $gap_value[ $gap_side ] ?? $fallback_value;
 772                  }
 773                  // Get spacing CSS variable from preset value if provided.
 774                  if ( is_string( $process_value ) && str_contains( $process_value, 'var:preset|spacing|' ) ) {
 775                      $index_to_splice = strrpos( $process_value, '|' ) + 1;
 776                      $slug            = _wp_to_kebab_case( substr( $process_value, $index_to_splice ) );
 777                      $process_value   = "var(--wp--preset--spacing--$slug)";
 778                  }
 779                  $combined_gap_value .= "$process_value ";
 780              }
 781              $gap_value = trim( $combined_gap_value );
 782  
 783              if ( null !== $gap_value && ! $should_skip_gap_serialization ) {
 784                  $layout_styles[] = array(
 785                      'selector'     => $selector,
 786                      'declarations' => array( 'gap' => $gap_value ),
 787                  );
 788              }
 789          }
 790  
 791          $flex_justify_content    = $layout_for_styles['justifyContent'] ?? null;
 792          $flex_vertical_alignment = $layout_for_styles['verticalAlignment'] ?? null;
 793  
 794          if ( 'horizontal' === $layout_orientation ) {
 795              /*
 796               * Add this style only if is not empty for backwards compatibility,
 797               * since we intend to convert blocks that had flex layout implemented
 798               * by custom css.
 799               */
 800              if ( $should_output_flex_justification && ! empty( $flex_justify_content ) && is_string( $flex_justify_content ) && array_key_exists( $flex_justify_content, $justify_content_options ) ) {
 801                  $layout_styles[] = array(
 802                      'selector'     => $selector,
 803                      'declarations' => array( 'justify-content' => $justify_content_options[ $flex_justify_content ] ),
 804                  );
 805              }
 806  
 807              if ( $should_output_flex_alignment && ! empty( $flex_vertical_alignment ) && is_string( $flex_vertical_alignment ) && array_key_exists( $flex_vertical_alignment, $vertical_alignment_options ) ) {
 808                  $layout_styles[] = array(
 809                      'selector'     => $selector,
 810                      'declarations' => array( 'align-items' => $vertical_alignment_options[ $flex_vertical_alignment ] ),
 811                  );
 812              }
 813          } else {
 814              if ( $should_output_flex_orientation ) {
 815                  $layout_styles[] = array(
 816                      'selector'     => $selector,
 817                      'declarations' => array( 'flex-direction' => 'column' ),
 818                  );
 819              }
 820              if ( $should_output_flex_justification && ! empty( $flex_justify_content ) && is_string( $flex_justify_content ) && array_key_exists( $flex_justify_content, $justify_content_options ) ) {
 821                  $layout_styles[] = array(
 822                      'selector'     => $selector,
 823                      'declarations' => array( 'align-items' => $justify_content_options[ $flex_justify_content ] ),
 824                  );
 825              } elseif ( $should_output_flex_justification ) {
 826                  $layout_styles[] = array(
 827                      'selector'     => $selector,
 828                      'declarations' => array( 'align-items' => 'flex-start' ),
 829                  );
 830              }
 831              if ( $should_output_flex_alignment && ! empty( $flex_vertical_alignment ) && is_string( $flex_vertical_alignment ) && array_key_exists( $flex_vertical_alignment, $vertical_alignment_options ) ) {
 832                  $layout_styles[] = array(
 833                      'selector'     => $selector,
 834                      'declarations' => array( 'justify-content' => $vertical_alignment_options[ $flex_vertical_alignment ] ),
 835                  );
 836              }
 837          }
 838      } elseif ( 'grid' === $layout_type ) {
 839          /*
 840           * Column and row counts are whole numbers, for the same reason as the grid line
 841           * numbers in wp_get_child_layout_style_rules().
 842           */
 843          $column_count_attr = $layout_for_styles['columnCount'] ?? null;
 844          $column_count      = is_numeric( $column_count_attr ) ? (int) $column_count_attr : null;
 845          $row_count_attr    = $layout_for_styles['rowCount'] ?? null;
 846          $row_count         = is_numeric( $row_count_attr ) ? (int) $row_count_attr : null;
 847  
 848          /*
 849           * If the gap value is an array, we use the "left" value because it represents the vertical gap, which
 850           * is the relevant one for computation of responsive grid columns.
 851           */
 852          if ( is_array( $fallback_gap_value ) ) {
 853              $responsive_gap_value = $fallback_gap_value['left'] ?? reset( $fallback_gap_value );
 854          } else {
 855              $responsive_gap_value = $fallback_gap_value;
 856          }
 857  
 858          if ( $has_block_gap_support && isset( $gap_value ) ) {
 859              $combined_gap_value = '';
 860              $gap_sides          = is_array( $gap_value ) ? array( 'top', 'left' ) : array( 'top' );
 861  
 862              foreach ( $gap_sides as $gap_side ) {
 863                  $process_value = $gap_value;
 864                  if ( is_array( $gap_value ) ) {
 865                      if ( is_array( $fallback_gap_value ) ) {
 866                          $fallback_value = $fallback_gap_value[ $gap_side ] ?? reset( $fallback_gap_value );
 867                      } else {
 868                          $fallback_value = $fallback_gap_value;
 869                      }
 870                      $process_value = $gap_value[ $gap_side ] ?? $fallback_value;
 871                  }
 872                  // Get spacing CSS variable from preset value if provided.
 873                  if ( is_string( $process_value ) && str_contains( $process_value, 'var:preset|spacing|' ) ) {
 874                      $index_to_splice = strrpos( $process_value, '|' ) + 1;
 875                      $slug            = _wp_to_kebab_case( substr( $process_value, $index_to_splice ) );
 876                      $process_value   = "var(--wp--preset--spacing--$slug)";
 877                  }
 878                  $combined_gap_value .= "$process_value ";
 879              }
 880              $gap_value            = trim( $combined_gap_value );
 881              $responsive_gap_value = $gap_value;
 882          }
 883  
 884          // Ensure 0 values have a unit so they work in calc().
 885          if ( '0' === $responsive_gap_value || 0 === $responsive_gap_value ) {
 886              $responsive_gap_value = '0px';
 887          }
 888  
 889          /*
 890           * Styles should be output either if there are no viewport overrides (this is the default case), or if the user has set a new viewport-specific
 891           * value for any of the grid properties.
 892           */
 893          $should_output_grid_columns = null === $viewport_overrides || $has_viewport_property_override( 'minimumColumnWidth' ) || $has_viewport_property_override( 'columnCount' ) || $has_viewport_property_override( 'autoFit' );
 894          $uses_gap_in_grid_columns   = ! empty( $column_count ) && ! empty( $layout_for_styles['minimumColumnWidth'] );
 895          if ( $has_block_gap_override && $uses_gap_in_grid_columns ) {
 896              $should_output_grid_columns = true;
 897          }
 898  
 899          $should_output_grid_rows = ( null === $viewport_overrides || $has_viewport_property_override( 'rowCount' ) ) && ! empty( $column_count ) && ! empty( $row_count );
 900          $grid_declarations       = array();
 901  
 902          /*
 903           * When enabled, columns stretch to fill the available space using
 904           * `auto-fit`; otherwise empty tracks are preserved with `auto-fill`.
 905           */
 906          $auto_placement = ! empty( $layout_for_styles['autoFit'] ) ? 'auto-fit' : 'auto-fill';
 907  
 908          if ( $should_output_grid_columns && ! empty( $column_count ) && ! empty( $layout_for_styles['minimumColumnWidth'] ) ) {
 909              $max_value                                  = 'max(min(' . $layout_for_styles['minimumColumnWidth'] . ', 100%), (100% - (' . $responsive_gap_value . ' * (' . $column_count . ' - 1))) /' . $column_count . ')';
 910              $grid_declarations['grid-template-columns'] = 'repeat(' . $auto_placement . ', minmax(' . $max_value . ', 1fr))';
 911          } elseif ( $should_output_grid_columns && ! empty( $column_count ) ) {
 912              $grid_declarations['grid-template-columns'] = 'repeat(' . $column_count . ', minmax(0, 1fr))';
 913          } elseif ( $should_output_grid_columns ) {
 914              $minimum_column_width                       = ! empty( $layout_for_styles['minimumColumnWidth'] ) ? $layout_for_styles['minimumColumnWidth'] : '12rem';
 915              $grid_declarations['grid-template-columns'] = 'repeat(' . $auto_placement . ', minmax(min(' . $minimum_column_width . ', 100%), 1fr))';
 916          }
 917  
 918          if ( ! empty( $grid_declarations ) ) {
 919              $base_has_container_type = empty( $base_layout['columnCount'] ) || ( ! empty( $base_layout['columnCount'] ) && ! empty( $base_layout['minimumColumnWidth'] ) );
 920              if ( empty( $column_count ) || ! empty( $layout_for_styles['minimumColumnWidth'] ) ) {
 921                  if ( null === $viewport_overrides || ! $base_has_container_type ) {
 922                      $grid_declarations['container-type'] = 'inline-size';
 923                  }
 924              }
 925              $layout_styles[] = array(
 926                  'selector'     => $selector,
 927                  'declarations' => $grid_declarations,
 928              );
 929          }
 930  
 931          if ( $should_output_grid_rows ) {
 932              $layout_styles[] = array(
 933                  'selector'     => $selector,
 934                  'declarations' => array( 'grid-template-rows' => 'repeat(' . $row_count . ', minmax(1rem, auto))' ),
 935              );
 936          }
 937  
 938          if ( $has_block_gap_support && $should_output_block_gap && null !== $gap_value && ! $should_skip_gap_serialization ) {
 939              $layout_styles[] = array(
 940                  'selector'     => $selector,
 941                  'declarations' => array( 'gap' => $gap_value ),
 942              );
 943          }
 944      }
 945  
 946      if ( ! empty( $layout_styles ) ) {
 947          if ( ! empty( $rules_group ) ) {
 948              foreach ( $layout_styles as $index => $layout_style ) {
 949                  $layout_styles[ $index ]['rules_group'] = $rules_group;
 950              }
 951          }
 952  
 953          /*
 954           * Add to the style engine store to enqueue and render layout styles.
 955           * Return compiled layout styles to retain backwards compatibility.
 956           * Since https://github.com/WordPress/gutenberg/pull/42452,
 957           * wp_enqueue_block_support_styles is no longer called in this block supports file.
 958           */
 959          return wp_style_engine_get_stylesheet_from_css_rules(
 960              $layout_styles,
 961              array(
 962                  'context'  => 'block-supports',
 963                  'prettify' => false,
 964              )
 965          );
 966      }
 967  
 968      return '';
 969  }
 970  
 971  /**
 972   * Renders the layout config to the block wrapper.
 973   *
 974   * @since 5.8.0
 975   * @since 6.3.0 Adds compound class to layout wrapper for global spacing styles.
 976   * @since 6.3.0 Check for layout support via the `layout` key with fallback to `__experimentalLayout`.
 977   * @since 6.6.0 Removed duplicate container class from layout styles.
 978   * @access private
 979   *
 980   * @param string $block_content Rendered block content.
 981   * @param array  $block         Block object.
 982   * @return string Filtered block content.
 983   */
 984  function wp_render_layout_support_flag( $block_content, $block ) {
 985      static $global_styles = null;
 986  
 987      $block_type            = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] );
 988      $block_supports_layout = block_has_support( $block_type, 'layout', false ) || block_has_support( $block_type, '__experimentalLayout', false );
 989      $style_attr            = $block['attrs']['style'] ?? array();
 990      /*
 991       * A block with no layout support and no style attribute at all cannot
 992       * produce layout output, so return before resolving global settings.
 993       *
 994       * Resolving settings is not read-only: on a cold cache it queries the
 995       * user's `wp_global_styles` post, which fires `the_posts`. A callback on
 996       * that hook that renders blocks re-enters this filter, and the content it
 997       * renders at that point is the global styles post itself, which parses to a
 998       * single block with no name and no attributes. Without this return that
 999       * block resolves settings again and the recursion has no base case.
1000       */
1001      if ( ! $block_supports_layout && empty( $style_attr ) ) {
1002          return $block_content;
1003      }
1004  
1005      $global_settings          = wp_get_global_settings();
1006      $viewport_settings        = $global_settings['viewport'] ?? null;
1007      $responsive_media_queries = WP_Theme_JSON::get_viewport_media_queries( $viewport_settings );
1008      $child_layout             = $style_attr['layout'] ?? null;
1009  
1010      /*
1011       * Collect responsive viewport child layout overrides so that a block with
1012       * only responsive child layout (no base child layout) is still processed.
1013       */
1014      $viewport_child_layouts = array();
1015      foreach ( $responsive_media_queries as $breakpoint => $media_query ) {
1016          $viewport_child = wp_get_layout_child_values( $style_attr[ $breakpoint ]['layout'] ?? null );
1017  
1018          if ( ! empty( $viewport_child ) ) {
1019              $viewport_child_layouts[ $breakpoint ] = array(
1020                  'media_query'  => $media_query,
1021                  'child_layout' => $viewport_child,
1022              );
1023          }
1024      }
1025  
1026      if ( ! $block_supports_layout && ! $child_layout && empty( $viewport_child_layouts ) ) {
1027          return $block_content;
1028      }
1029  
1030      $outer_class_names = array();
1031  
1032      // Child layout specific logic.
1033      if ( $child_layout || ! empty( $viewport_child_layouts ) ) {
1034          $base_child_layout = wp_get_layout_child_values( $child_layout );
1035          $parent_layout     = $block['parentLayout'] ?? array();
1036          /*
1037           * Generates a unique class for child block layout styles.
1038           *
1039           * To ensure consistent class generation across different page renders,
1040           * only properties that affect layout styling are used. These properties
1041           * come from `$block['attrs']['style']['layout']`, viewport overrides in
1042           * `$block['attrs']['style'][$breakpoint]['layout']`, and `$block['parentLayout']`.
1043           *
1044           * As long as these properties coincide, the generated class will be the same.
1045           */
1046          $container_content_hash_input = array(
1047              'layout'       => $base_child_layout,
1048              'parentLayout' => array_intersect_key(
1049                  $parent_layout,
1050                  array_flip( array( 'minimumColumnWidth', 'columnCount' ) )
1051              ),
1052          );
1053  
1054          foreach ( $viewport_child_layouts as $breakpoint => $viewport_data ) {
1055              $container_content_hash_input[ $breakpoint ] = $viewport_data['child_layout'];
1056          }
1057  
1058          $container_content_class = wp_unique_id_from_values(
1059              $container_content_hash_input,
1060              'wp-container-content-'
1061          );
1062  
1063          $child_layout_styles = wp_get_child_layout_style_rules( ".$container_content_class", $base_child_layout, $parent_layout );
1064  
1065          /*
1066           * Emit responsive child layout CSS using the same container-content class
1067           * so that base and responsive child layout share the exact same selector.
1068           */
1069          foreach ( $viewport_child_layouts as $viewport_data ) {
1070              $viewport_child_styles = wp_get_child_layout_style_rules(
1071                  ".$container_content_class",
1072                  $base_child_layout,
1073                  $parent_layout,
1074                  $viewport_data['child_layout']
1075              );
1076  
1077              foreach ( $viewport_child_styles as $index => $rule ) {
1078                  $viewport_child_styles[ $index ]['rules_group'] = $viewport_data['media_query'];
1079              }
1080  
1081              $child_layout_styles = array_merge( $child_layout_styles, $viewport_child_styles );
1082          }
1083  
1084          /*
1085           * Add to the style engine store to enqueue and render layout styles.
1086           * Return styles here just to check if any exist.
1087           */
1088          $child_css = wp_style_engine_get_stylesheet_from_css_rules(
1089              $child_layout_styles,
1090              array(
1091                  'context'  => 'block-supports',
1092                  'prettify' => false,
1093              )
1094          );
1095  
1096          if ( $child_css ) {
1097              $outer_class_names[] = $container_content_class;
1098          }
1099      }
1100  
1101      // Prep the processor for modifying the block output.
1102      $processor = new WP_HTML_Tag_Processor( $block_content );
1103  
1104      // Having no tags implies there are no tags onto which to add class names.
1105      if ( ! $processor->next_tag() ) {
1106          return $block_content;
1107      }
1108  
1109      /*
1110       * A block may not support layout but still be affected by a parent block's layout.
1111       *
1112       * In these cases add the appropriate class names and then return early; there's
1113       * no need to investigate on this block whether additional layout constraints apply.
1114       */
1115      if ( ! $block_supports_layout && ! empty( $outer_class_names ) ) {
1116          foreach ( $outer_class_names as $class_name ) {
1117              $processor->add_class( $class_name );
1118          }
1119          return $processor->get_updated_html();
1120      } elseif ( ! $block_supports_layout ) {
1121          // Ensure layout classnames are not injected if there is no layout support.
1122          return $block_content;
1123      }
1124  
1125      $fallback_layout = $block_type->supports['layout']['default'] ?? array();
1126      if ( empty( $fallback_layout ) ) {
1127          $fallback_layout = $block_type->supports['__experimentalLayout']['default'] ?? array();
1128      }
1129      $used_layout = $block['attrs']['layout'] ?? $fallback_layout;
1130  
1131      $class_names        = array();
1132      $layout_definitions = wp_get_layout_definitions();
1133  
1134      // Set the correct layout type for blocks using legacy content width.
1135      if ( isset( $used_layout['inherit'] ) && $used_layout['inherit'] || isset( $used_layout['contentSize'] ) && $used_layout['contentSize'] ) {
1136          $used_layout['type'] = 'constrained';
1137      }
1138  
1139      $root_padding_aware_alignments = $global_settings['useRootPaddingAwareAlignments'] ?? false;
1140  
1141      if (
1142          $root_padding_aware_alignments &&
1143          isset( $used_layout['type'] ) &&
1144          'constrained' === $used_layout['type']
1145      ) {
1146          $class_names[] = 'has-global-padding';
1147      }
1148  
1149      /*
1150       * The following section was added to reintroduce a small set of layout classnames that were
1151       * removed in the 5.9 release (https://github.com/WordPress/gutenberg/issues/38719). It is
1152       * not intended to provide an extended set of classes to match all block layout attributes
1153       * here.
1154       */
1155      $orientation = $block['attrs']['layout']['orientation'] ?? null;
1156      if ( ! empty( $orientation ) && is_string( $orientation ) ) {
1157          $class_names[] = 'is-' . sanitize_title( $orientation );
1158      }
1159  
1160      $justify_content = $block['attrs']['layout']['justifyContent'] ?? null;
1161      if ( ! empty( $justify_content ) && is_string( $justify_content ) ) {
1162          $class_names[] = 'is-content-justification-' . sanitize_title( $justify_content );
1163      }
1164  
1165      $flex_wrap = $block['attrs']['layout']['flexWrap'] ?? null;
1166      if ( ! empty( $flex_wrap ) && 'nowrap' === $flex_wrap ) {
1167          $class_names[] = 'is-nowrap';
1168      }
1169  
1170      // Get classname for layout type.
1171      if ( isset( $used_layout['type'] ) && is_string( $used_layout['type'] ) ) {
1172          $layout_classname = $layout_definitions[ $used_layout['type'] ]['className'] ?? '';
1173      } else {
1174          $layout_classname = $layout_definitions['default']['className'] ?? '';
1175      }
1176  
1177      if ( $layout_classname && is_string( $layout_classname ) ) {
1178          $class_names[] = sanitize_title( $layout_classname );
1179      }
1180  
1181      /*
1182       * Only generate Layout styles if the theme has not opted-out.
1183       * Attribute-based Layout classnames are output in all cases.
1184       */
1185      if ( ! current_theme_supports( 'disable-layout-styles' ) ) {
1186  
1187          $gap_value          = wp_sanitize_block_gap_value( $style_attr['spacing']['blockGap'] ?? null );
1188          $fallback_gap_value = $block_type->supports['spacing']['blockGap']['__experimentalDefault'] ?? '0.5em';
1189          $block_spacing      = $style_attr['spacing'] ?? null;
1190  
1191          /*
1192           * If a block's block.json skips serialization for spacing or spacing.blockGap,
1193           * don't apply the user-defined value to the styles.
1194           */
1195          $should_skip_gap_serialization = wp_should_skip_block_supports_serialization( $block_type, 'spacing', 'blockGap' );
1196  
1197          $block_gap             = $global_settings['spacing']['blockGap'] ?? null;
1198          $has_block_gap_support = isset( $block_gap );
1199  
1200          // Get default blockGap value from global styles for use in layouts like grid.
1201          // Check style variation first, then block-specific styles, then fall back to root styles.
1202          $block_name = $block['blockName'] ?? '';
1203          if ( null === $global_styles ) {
1204              $global_styles = wp_get_global_styles();
1205          }
1206  
1207          // Check if the block has an active style variation with a blockGap value.
1208          // Only check the registry if the className contains a variation class to avoid unnecessary lookups.
1209          $variation_block_gap_value = null;
1210          $block_class_name          = is_string( $block['attrs']['className'] ?? null )
1211              ? $block['attrs']['className']
1212              : '';
1213          if ( $block_class_name && str_contains( $block_class_name, 'is-style-' ) && $block_name ) {
1214              $styles_registry   = WP_Block_Styles_Registry::get_instance();
1215              $registered_styles = $styles_registry->get_registered_styles_for_block( $block_name );
1216              $variation_name    = wp_get_block_style_variation_name_from_registered_style( $block_class_name, $registered_styles );
1217              if ( $variation_name ) {
1218                  $variation_block_gap_value = $global_styles['blocks'][ $block_name ]['variations'][ $variation_name ]['spacing']['blockGap'] ?? null;
1219              }
1220          }
1221  
1222          $global_block_gap_value = $variation_block_gap_value ?? $global_styles['blocks'][ $block_name ]['spacing']['blockGap'] ?? $global_styles['spacing']['blockGap'] ?? null;
1223  
1224          if ( null !== $global_block_gap_value ) {
1225              $fallback_gap_value = $global_block_gap_value;
1226          }
1227  
1228          $container_class_hash_input = array(
1229              $used_layout,
1230              $has_block_gap_support,
1231              $gap_value,
1232              $should_skip_gap_serialization,
1233              $fallback_gap_value,
1234              $block_spacing,
1235          );
1236  
1237          foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
1238              $viewport_style = $style_attr[ $breakpoint ] ?? null;
1239              if ( ! is_array( $viewport_style ) ) {
1240                  continue;
1241              }
1242  
1243              $viewport_container_layout = wp_get_layout_container_values( $viewport_style['layout'] ?? null );
1244              if ( ! empty( $viewport_container_layout ) ) {
1245                  $container_class_hash_input[] = array(
1246                      'breakpoint' => $breakpoint,
1247                      'layout'     => $viewport_container_layout,
1248                  );
1249              }
1250  
1251              if ( isset( $viewport_style['spacing']['blockGap'] ) ) {
1252                  $container_class_hash_input[] = array(
1253                      'breakpoint' => $breakpoint,
1254                      'blockGap'   => wp_sanitize_block_gap_value( $viewport_style['spacing']['blockGap'] ),
1255                  );
1256              }
1257          }
1258  
1259          /*
1260           * Generates a unique ID based on all the data required to obtain the
1261           * corresponding layout style. Keeps the CSS class names the same
1262           * even for different blocks on different places, as long as they have
1263           * the same layout definition. Makes the CSS class names stable across
1264           * paginations for features like the enhanced pagination of the Query block.
1265           */
1266          $container_class = wp_unique_id_from_values(
1267              $container_class_hash_input,
1268              'wp-container-' . sanitize_title( $block['blockName'] ) . '-is-layout-'
1269          );
1270  
1271          $style = wp_get_layout_style(
1272              ".$container_class",
1273              $used_layout,
1274              $has_block_gap_support,
1275              $gap_value,
1276              $should_skip_gap_serialization,
1277              $fallback_gap_value,
1278              $block_spacing
1279          );
1280  
1281          /*
1282           * Emit responsive container layout styles using the same $container_class
1283           * selector as the base layout so they target the inner block wrapper.
1284           */
1285          foreach ( $responsive_media_queries as $breakpoint => $media_query ) {
1286              $viewport_style = $style_attr[ $breakpoint ] ?? null;
1287              if ( ! is_array( $viewport_style ) ) {
1288                  continue;
1289              }
1290  
1291              $viewport_container_layout = wp_get_layout_container_values( $viewport_style['layout'] ?? null );
1292              $has_viewport_layout       = ! empty( $viewport_container_layout );
1293              $has_viewport_block_gap    = isset( $viewport_style['spacing']['blockGap'] );
1294  
1295              if ( ! $has_viewport_layout && ! $has_viewport_block_gap ) {
1296                  continue;
1297              }
1298  
1299              $viewport_gap_value = $has_viewport_block_gap
1300                  ? wp_sanitize_block_gap_value( $viewport_style['spacing']['blockGap'] )
1301                  : $gap_value;
1302  
1303              $viewport_block_spacing = is_array( $viewport_style['spacing'] ?? null )
1304                  ? array_replace( is_array( $block_spacing ) ? $block_spacing : array(), $viewport_style['spacing'] )
1305                  : $block_spacing;
1306  
1307              $viewport_styles = wp_get_layout_style(
1308                  ".$container_class",
1309                  $used_layout,
1310                  $has_block_gap_support,
1311                  $viewport_gap_value,
1312                  $should_skip_gap_serialization,
1313                  $fallback_gap_value,
1314                  $viewport_block_spacing,
1315                  array(
1316                      'rules_group'            => $media_query,
1317                      'viewport_overrides'     => $viewport_container_layout,
1318                      'has_block_gap_override' => $has_viewport_block_gap,
1319                  )
1320              );
1321  
1322              if ( ! empty( $viewport_styles ) && ! in_array( $container_class, $class_names, true ) ) {
1323                  $class_names[] = $container_class;
1324              }
1325          }
1326  
1327          // Only add container class and enqueue block support styles if unique styles were generated.
1328          if ( ! empty( $style ) ) {
1329              $class_names[] = $container_class;
1330          }
1331      }
1332  
1333      // Add combined layout and block classname for global styles to hook onto.
1334      $split_block_name = explode( '/', $block['blockName'] );
1335      $full_block_name  = 'core' === $split_block_name[0] ? end( $split_block_name ) : implode( '-', $split_block_name );
1336      $class_names[]    = 'wp-block-' . $full_block_name . '-' . $layout_classname;
1337  
1338      // Add classes to the outermost HTML tag if necessary.
1339      if ( ! empty( $outer_class_names ) ) {
1340          foreach ( $outer_class_names as $outer_class_name ) {
1341              $processor->add_class( $outer_class_name );
1342          }
1343      }
1344  
1345      /**
1346       * Attempts to refer to the inner-block wrapping element by its class attribute.
1347       *
1348       * When examining a block's inner content, if a block has inner blocks, then
1349       * the first content item will likely be a text (HTML) chunk immediately
1350       * preceding the inner blocks. The last HTML tag in that chunk would then be
1351       * an opening tag for an element that wraps the inner blocks.
1352       *
1353       * There's no reliable way to associate this wrapper in $block_content because
1354       * it may have changed during the rendering pipeline (as inner contents is
1355       * provided before rendering) and through previous filters. In many cases,
1356       * however, the `class` attribute will be a good-enough identifier, so this
1357       * code finds the last tag in that chunk and stores the `class` attribute
1358       * so that it can be used later when working through the rendered block output
1359       * to identify the wrapping element and add the remaining class names to it.
1360       *
1361       * It's also possible that no inner block wrapper even exists. If that's the
1362       * case this code could apply the class names to an invalid element.
1363       *
1364       * Example:
1365       *
1366       *     $block['innerBlocks']  = array( $list_item );
1367       *     $block['innerContent'] = array( '<ul class="list-wrapper is-unordered">', null, '</ul>' );
1368       *
1369       *     // After rendering, the initial contents may have been modified by other renderers or filters.
1370       *     $block_content = <<<HTML
1371       *         <figure>
1372       *             <ul class="annotated-list list-wrapper is-unordered">
1373       *                 <li>Code</li>
1374       *             </ul><figcaption>It's a list!</figcaption>
1375       *         </figure>
1376       *     HTML;
1377       *
1378       * Although it is possible that the original block-wrapper classes are changed in $block_content
1379       * from how they appear in $block['innerContent'], it's likely that the original class attributes
1380       * are still present in the wrapper as they are in this example. Frequently, additional classes
1381       * will also be present; rarely should classes be removed.
1382       *
1383       * @todo Find a better way to match the first inner block. If it's possible to identify where the
1384       *       first inner block starts, then it will be possible to find the last tag before it starts
1385       *       and then that tag, if an opening tag, can be solidly identified as a wrapping element.
1386       *       Can some unique value or class or ID be added to the inner blocks when they process
1387       *       so that they can be extracted here safely without guessing? Can the block rendering function
1388       *       return information about where the rendered inner blocks start?
1389       *
1390       * @var string|null
1391       */
1392      $inner_block_wrapper_classes = null;
1393      $first_chunk                 = $block['innerContent'][0] ?? null;
1394      if ( is_string( $first_chunk ) && count( $block['innerContent'] ) > 1 ) {
1395          $first_chunk_processor = new WP_HTML_Tag_Processor( $first_chunk );
1396          /*
1397           * Use a stack to track open elements as tags are visited. Void elements
1398           * (those without a matching closing tag) are excluded so they don't
1399           * accumulate on the stack. At the end of the chunk, every element still
1400           * on the stack is unclosed — meaning its closing tag lives in a later
1401           * innerContent entry alongside the inner blocks, which makes it the
1402           * inner-block container. Elements that open and close within this chunk
1403           * are siblings that precede the inner blocks and should be ignored.
1404           * The last unclosed element with a class attribute is the best candidate
1405           * for the inner-block wrapper.
1406           */
1407          $tag_stack = array();
1408          while ( $first_chunk_processor->next_tag( array( 'tag_closers' => 'visit' ) ) ) {
1409              if ( $first_chunk_processor->is_tag_closer() ) {
1410                  array_pop( $tag_stack );
1411              } elseif ( ! WP_HTML_Processor::is_void( $first_chunk_processor->get_tag() ) ) {
1412                  $tag_stack[] = $first_chunk_processor->get_attribute( 'class' );
1413              }
1414          }
1415          foreach ( array_reverse( $tag_stack ) as $class_attribute ) {
1416              if ( is_string( $class_attribute ) && ! empty( $class_attribute ) ) {
1417                  $inner_block_wrapper_classes = $class_attribute;
1418                  break;
1419              }
1420          }
1421      }
1422  
1423      /*
1424       * If necessary, advance to what is likely to be an inner block wrapper tag.
1425       *
1426       * This advances until it finds the first tag containing the original class
1427       * attribute from above. If none is found it will scan to the end of the block
1428       * and fail to add any class names.
1429       *
1430       * If there is no block wrapper it won't advance at all, in which case the
1431       * class names will be added to the first and outermost tag of the block.
1432       * For cases where this outermost tag is the only tag surrounding inner
1433       * blocks then the outer wrapper and inner wrapper are the same.
1434       */
1435      do {
1436          if ( ! $inner_block_wrapper_classes ) {
1437              break;
1438          }
1439  
1440          $class_attribute = $processor->get_attribute( 'class' );
1441          if ( is_string( $class_attribute ) && str_contains( $class_attribute, $inner_block_wrapper_classes ) ) {
1442              break;
1443          }
1444      } while ( $processor->next_tag() );
1445  
1446      // Add the remaining class names.
1447      foreach ( $class_names as $class_name ) {
1448          $processor->add_class( $class_name );
1449      }
1450  
1451      return $processor->get_updated_html();
1452  }
1453  
1454  /**
1455   * Check if the parent block exists and if it has a layout attribute.
1456   * If it does, add the parent layout to the parsed block
1457   *
1458   * @since 6.6.0
1459   * @access private
1460   *
1461   * @param array    $parsed_block The parsed block.
1462   * @param array    $source_block The source block.
1463   * @param WP_Block $parent_block The parent block.
1464   * @return array The parsed block with parent layout attribute if it exists.
1465   */
1466  function wp_add_parent_layout_to_parsed_block( $parsed_block, $source_block, $parent_block ) {
1467      if ( $parent_block && isset( $parent_block->parsed_block['attrs']['layout'] ) ) {
1468          $parsed_block['parentLayout'] = $parent_block->parsed_block['attrs']['layout'];
1469      }
1470      return $parsed_block;
1471  }
1472  
1473  add_filter( 'render_block_data', 'wp_add_parent_layout_to_parsed_block', 10, 3 );
1474  
1475  // Register the block support.
1476  WP_Block_Supports::get_instance()->register(
1477      'layout',
1478      array(
1479          'register_attribute' => 'wp_register_layout_support',
1480      )
1481  );
1482  add_filter( 'render_block', 'wp_render_layout_support_flag', 10, 2 );
1483  
1484  /**
1485   * For themes without theme.json file, make sure
1486   * to restore the inner div for the group block
1487   * to avoid breaking styles relying on that div.
1488   *
1489   * @since 5.8.0
1490   * @since 6.6.1 Removed inner container from Grid variations.
1491   * @access private
1492   *
1493   * @param string $block_content Rendered block content.
1494   * @param array  $block         Block object.
1495   * @return string Filtered block content.
1496   */
1497  function wp_restore_group_inner_container( $block_content, $block ) {
1498      $tag_name_attr                    = $block['attrs']['tagName'] ?? null;
1499      $tag_name                         = is_string( $tag_name_attr ) ? $tag_name_attr : 'div';
1500      $group_with_inner_container_regex = sprintf(
1501          '/(^\s*<%1$s\b[^>]*wp-block-group(\s|")[^>]*>)(\s*<div\b[^>]*wp-block-group__inner-container(\s|")[^>]*>)((.|\S|\s)*)/U',
1502          preg_quote( $tag_name, '/' )
1503      );
1504  
1505      if (
1506          wp_theme_has_theme_json() ||
1507          1 === preg_match( $group_with_inner_container_regex, $block_content ) ||
1508          ( isset( $block['attrs']['layout']['type'] ) && ( 'flex' === $block['attrs']['layout']['type'] || 'grid' === $block['attrs']['layout']['type'] ) )
1509      ) {
1510          return $block_content;
1511      }
1512  
1513      /*
1514       * This filter runs after the layout classnames have been added to the block, so they
1515       * have to be removed from the outer wrapper and then added to the inner.
1516       */
1517      $layout_classes = array();
1518      $processor      = new WP_HTML_Tag_Processor( $block_content );
1519  
1520      if ( $processor->next_tag( array( 'class_name' => 'wp-block-group' ) ) ) {
1521          foreach ( $processor->class_list() as $class_name ) {
1522              if ( str_contains( $class_name, 'is-layout-' ) ) {
1523                  $layout_classes[] = $class_name;
1524                  $processor->remove_class( $class_name );
1525              }
1526          }
1527      }
1528  
1529      $content_without_layout_classes = $processor->get_updated_html();
1530      $replace_regex                  = sprintf(
1531          '/(^\s*<%1$s\b[^>]*wp-block-group[^>]*>)(.*)(<\/%1$s>\s*$)/ms',
1532          preg_quote( $tag_name, '/' )
1533      );
1534      $updated_content                = preg_replace_callback(
1535          $replace_regex,
1536          static function ( $matches ) {
1537              return $matches[1] . '<div class="wp-block-group__inner-container">' . $matches[2] . '</div>' . $matches[3];
1538          },
1539          $content_without_layout_classes
1540      );
1541  
1542      // Add layout classes to inner wrapper.
1543      if ( ! empty( $layout_classes ) ) {
1544          $processor = new WP_HTML_Tag_Processor( $updated_content );
1545          if ( $processor->next_tag( array( 'class_name' => 'wp-block-group__inner-container' ) ) ) {
1546              foreach ( $layout_classes as $class_name ) {
1547                  $processor->add_class( $class_name );
1548              }
1549          }
1550          $updated_content = $processor->get_updated_html();
1551      }
1552      return $updated_content;
1553  }
1554  
1555  add_filter( 'render_block_core/group', 'wp_restore_group_inner_container', 10, 2 );
1556  
1557  /**
1558   * For themes without theme.json file, make sure
1559   * to restore the outer div for the aligned image block
1560   * to avoid breaking styles relying on that div.
1561   *
1562   * @since 6.0.0
1563   * @access private
1564   *
1565   * @param string $block_content Rendered block content.
1566   * @param  array  $block        Block object.
1567   * @return string Filtered block content.
1568   */
1569  function wp_restore_image_outer_container( $block_content, $block ) {
1570      if ( wp_theme_has_theme_json() ) {
1571          return $block_content;
1572      }
1573  
1574      $figure_processor = new WP_HTML_Tag_Processor( $block_content );
1575      if (
1576          ! $figure_processor->next_tag( 'FIGURE' ) ||
1577          ! $figure_processor->has_class( 'wp-block-image' ) ||
1578          ! (
1579              $figure_processor->has_class( 'alignleft' ) ||
1580              $figure_processor->has_class( 'aligncenter' ) ||
1581              $figure_processor->has_class( 'alignright' )
1582          )
1583      ) {
1584          return $block_content;
1585      }
1586  
1587      /*
1588       * The next section of code wraps the existing figure in a new DIV element.
1589       * While doing it, it needs to transfer the layout and the additional CSS
1590       * class names from the original figure upward to the wrapper.
1591       *
1592       * Example:
1593       *
1594       *     // From this…
1595       *     <!-- wp:image {"className":"hires"} -->
1596       *     <figure class="wp-block-image wide hires">…
1597       *
1598       *     // To this…
1599       *     <div class="wp-block-image hires"><figure class="wide">…
1600       */
1601      $wrapper_processor = new WP_HTML_Tag_Processor( '<div>' );
1602      $wrapper_processor->next_token();
1603      $wrapper_processor->set_attribute(
1604          'class',
1605          is_string( $block['attrs']['className'] ?? null )
1606              ? "wp-block-image {$block['attrs']['className']}"
1607              : 'wp-block-image'
1608      );
1609  
1610      // And remove them from the existing content; it has been transferred upward.
1611      $figure_processor->remove_class( 'wp-block-image' );
1612      foreach ( $wrapper_processor->class_list() as $class_name ) {
1613          $figure_processor->remove_class( $class_name );
1614      }
1615  
1616      return "{$wrapper_processor->get_updated_html()}{$figure_processor->get_updated_html()}</div>";
1617  }
1618  
1619  add_filter( 'render_block_core/image', 'wp_restore_image_outer_container', 10, 2 );


Generated : Mon Aug 24 08:20:24 2026 Cross-referenced by PHPXref