[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-theme-json.php (source)

   1  <?php
   2  /**
   3   * WP_Theme_JSON class
   4   *
   5   * @package WordPress
   6   * @subpackage Theme
   7   * @since 5.8.0
   8   */
   9  
  10  /**
  11   * Class that encapsulates the processing of structures that adhere to the theme.json spec.
  12   *
  13   * This class is for internal core usage and is not supposed to be used by extenders (plugins and/or themes).
  14   * This is a low-level API that may need to do breaking changes. Please,
  15   * use get_global_settings, get_global_styles, and get_global_stylesheet instead.
  16   *
  17   * @access private
  18   */
  19  #[AllowDynamicProperties]
  20  class WP_Theme_JSON {
  21  
  22      /**
  23       * Container of data in theme.json format.
  24       *
  25       * @since 5.8.0
  26       * @var array
  27       */
  28      protected $theme_json = null;
  29  
  30      /**
  31       * Holds block metadata extracted from block.json
  32       * to be shared among all instances so we don't
  33       * process it twice.
  34       *
  35       * @since 5.8.0
  36       * @since 6.1.0 Initialize as an empty array.
  37       * @var array
  38       */
  39      protected static $blocks_metadata = array();
  40  
  41      /**
  42       * The CSS selector for the top-level preset settings.
  43       *
  44       * @since 6.6.0
  45       * @var string
  46       */
  47      const ROOT_CSS_PROPERTIES_SELECTOR = ':root';
  48  
  49      /**
  50       * The CSS selector for the top-level styles.
  51       *
  52       * @since 5.8.0
  53       * @var string
  54       */
  55      const ROOT_BLOCK_SELECTOR = 'body';
  56  
  57      /**
  58       * The sources of data this object can represent.
  59       *
  60       * @since 5.8.0
  61       * @since 6.1.0 Added 'blocks'.
  62       * @var string[]
  63       */
  64      const VALID_ORIGINS = array(
  65          'default',
  66          'blocks',
  67          'theme',
  68          'custom',
  69      );
  70  
  71      /**
  72       * Presets are a set of values that serve
  73       * to bootstrap some styles: colors, font sizes, etc.
  74       *
  75       * They are a unkeyed array of values such as:
  76       *
  77       *     array(
  78       *       array(
  79       *         'slug'      => 'unique-name-within-the-set',
  80       *         'name'      => 'Name for the UI',
  81       *         <value_key> => 'value'
  82       *       ),
  83       *     )
  84       *
  85       * This contains the necessary metadata to process them:
  86       *
  87       * - path             => Where to find the preset within the settings section.
  88       * - prevent_override => Disables override of default presets by theme presets.
  89       *                       The relationship between whether to override the defaults
  90       *                       and whether the defaults are enabled is inverse:
  91       *                         - If defaults are enabled  => theme presets should not be overridden
  92       *                         - If defaults are disabled => theme presets should be overridden
  93       *                       For example, a theme sets defaultPalette to false,
  94       *                       making the default palette hidden from the user.
  95       *                       In that case, we want all the theme presets to be present,
  96       *                       so they should override the defaults by setting this false.
  97       * - use_default_names => whether to use the default names
  98       * - value_key        => the key that represents the value
  99       * - value_func       => optionally, instead of value_key, a function to generate
 100       *                       the value that takes a preset as an argument
 101       *                       (either value_key or value_func should be present)
 102       * - css_vars         => template string to use in generating the CSS Custom Property.
 103       *                       Example output: "--wp--preset--duotone--blue: <value>" will generate as many CSS Custom Properties as presets defined
 104       *                       substituting the $slug for the slug's value for each preset value.
 105       * - classes          => array containing a structure with the classes to
 106       *                       generate for the presets, where for each array item
 107       *                       the key is the class name and the value the property name.
 108       *                       The "$slug" substring will be replaced by the slug of each preset.
 109       *                       For example:
 110       *                       'classes' => array(
 111       *                         '.has-$slug-color'            => 'color',
 112       *                         '.has-$slug-background-color' => 'background-color',
 113       *                         '.has-$slug-border-color'     => 'border-color',
 114       *                       )
 115       * - properties       => array of CSS properties to be used by kses to
 116       *                       validate the content of each preset
 117       *                       by means of the remove_insecure_properties method.
 118       *
 119       * @since 5.8.0
 120       * @since 5.9.0 Added the `color.duotone` and `typography.fontFamilies` presets,
 121       *              `use_default_names` preset key, and simplified the metadata structure.
 122       * @since 6.0.0 Replaced `override` with `prevent_override` and updated the
 123       *              `prevent_override` value for `color.duotone` to use `color.defaultDuotone`.
 124       * @since 6.2.0 Added 'shadow' presets.
 125       * @since 6.3.0 Replaced value_func for duotone with `null`. Custom properties are handled by class-wp-duotone.php.
 126       * @since 6.6.0 Added the `dimensions.aspectRatios` and `dimensions.defaultAspectRatios` presets.
 127       *              Updated the 'prevent_override' value for font size presets to use 'typography.defaultFontSizes'
 128       *              and spacing size presets to use `spacing.defaultSpacingSizes`.
 129       * @since 6.9.0 Added `border.radiusSizes`.
 130       * @var array
 131       */
 132      const PRESETS_METADATA = array(
 133          array(
 134              'path'              => array( 'dimensions', 'aspectRatios' ),
 135              'prevent_override'  => array( 'dimensions', 'defaultAspectRatios' ),
 136              'use_default_names' => false,
 137              'value_key'         => 'ratio',
 138              'css_vars'          => '--wp--preset--aspect-ratio--$slug',
 139              'classes'           => array(),
 140              'properties'        => array( 'aspect-ratio' ),
 141          ),
 142          array(
 143              'path'              => array( 'color', 'palette' ),
 144              'prevent_override'  => array( 'color', 'defaultPalette' ),
 145              'use_default_names' => false,
 146              'value_key'         => 'color',
 147              'css_vars'          => '--wp--preset--color--$slug',
 148              'classes'           => array(
 149                  '.has-$slug-color'            => 'color',
 150                  '.has-$slug-background-color' => 'background-color',
 151                  '.has-$slug-border-color'     => 'border-color',
 152              ),
 153              'properties'        => array( 'color', 'background-color', 'border-color' ),
 154          ),
 155          array(
 156              'path'              => array( 'color', 'gradients' ),
 157              'prevent_override'  => array( 'color', 'defaultGradients' ),
 158              'use_default_names' => false,
 159              'value_key'         => 'gradient',
 160              'css_vars'          => '--wp--preset--gradient--$slug',
 161              'classes'           => array( '.has-$slug-gradient-background' => 'background' ),
 162              'properties'        => array( 'background' ),
 163          ),
 164          array(
 165              'path'              => array( 'color', 'duotone' ),
 166              'prevent_override'  => array( 'color', 'defaultDuotone' ),
 167              'use_default_names' => false,
 168              'value_func'        => null, // CSS Custom Properties for duotone are handled by block supports in class-wp-duotone.php.
 169              'css_vars'          => null,
 170              'classes'           => array(),
 171              'properties'        => array( 'filter' ),
 172          ),
 173          array(
 174              'path'              => array( 'typography', 'fontSizes' ),
 175              'prevent_override'  => array( 'typography', 'defaultFontSizes' ),
 176              'use_default_names' => true,
 177              'value_func'        => 'wp_get_typography_font_size_value',
 178              'css_vars'          => '--wp--preset--font-size--$slug',
 179              'classes'           => array( '.has-$slug-font-size' => 'font-size' ),
 180              'properties'        => array( 'font-size' ),
 181          ),
 182          array(
 183              'path'              => array( 'typography', 'fontFamilies' ),
 184              'prevent_override'  => false,
 185              'use_default_names' => false,
 186              'value_key'         => 'fontFamily',
 187              'css_vars'          => '--wp--preset--font-family--$slug',
 188              'classes'           => array( '.has-$slug-font-family' => 'font-family' ),
 189              'properties'        => array( 'font-family' ),
 190          ),
 191          array(
 192              'path'              => array( 'spacing', 'spacingSizes' ),
 193              'prevent_override'  => array( 'spacing', 'defaultSpacingSizes' ),
 194              'use_default_names' => true,
 195              'value_key'         => 'size',
 196              'css_vars'          => '--wp--preset--spacing--$slug',
 197              'classes'           => array(),
 198              'properties'        => array( 'padding', 'margin' ),
 199          ),
 200          array(
 201              'path'              => array( 'shadow', 'presets' ),
 202              'prevent_override'  => array( 'shadow', 'defaultPresets' ),
 203              'use_default_names' => false,
 204              'value_key'         => 'shadow',
 205              'css_vars'          => '--wp--preset--shadow--$slug',
 206              'classes'           => array(),
 207              'properties'        => array( 'box-shadow' ),
 208          ),
 209          array(
 210              'path'              => array( 'border', 'radiusSizes' ),
 211              'prevent_override'  => false,
 212              'use_default_names' => false,
 213              'value_key'         => 'size',
 214              'css_vars'          => '--wp--preset--border-radius--$slug',
 215              'classes'           => array(),
 216              'properties'        => array( 'border-radius' ),
 217          ),
 218          array(
 219              'path'              => array( 'dimensions', 'dimensionSizes' ),
 220              'prevent_override'  => false,
 221              'use_default_names' => false,
 222              'value_key'         => 'size',
 223              'css_vars'          => '--wp--preset--dimension--$slug',
 224              'classes'           => array(),
 225              'properties'        => array( 'width', 'height', 'min-height' ),
 226          ),
 227      );
 228  
 229      /**
 230       * Metadata for style properties.
 231       *
 232       * Each element is a direct mapping from the CSS property name to the
 233       * path to the value in theme.json & block attributes.
 234       *
 235       * @since 5.8.0
 236       * @since 5.9.0 Added the `border-*`, `font-family`, `font-style`, `font-weight`,
 237       *              `letter-spacing`, `margin-*`, `padding-*`, `--wp--style--block-gap`,
 238       *              `text-decoration`, `text-transform`, and `filter` properties,
 239       *              simplified the metadata structure.
 240       * @since 6.1.0 Added the `border-*-color`, `border-*-width`, `border-*-style`,
 241       *              `--wp--style--root--padding-*`, and `box-shadow` properties,
 242       *              removed the `--wp--style--block-gap` property.
 243       * @since 6.2.0 Added `outline-*`, and `min-height` properties.
 244       * @since 6.3.0 Added `column-count` property.
 245       * @since 6.4.0 Added `writing-mode` property.
 246       * @since 6.5.0 Added `aspect-ratio` property.
 247       * @since 6.6.0 Added `background-[image|position|repeat|size]` properties.
 248       * @since 6.7.0 Added `background-attachment` property.
 249       * @since 7.0.0 Added `dimensions.width` and `dimensions.height`.
 250       *              Added `text-indent` property.
 251       * @since 7.1.0 Added `min-width` and `text-shadow`.
 252       * @var array
 253       */
 254      const PROPERTIES_METADATA = array(
 255          'aspect-ratio'                      => array( 'dimensions', 'aspectRatio' ),
 256          'background'                        => array( 'color', 'gradient' ),
 257          'background-color'                  => array( 'color', 'background' ),
 258          'background-image'                  => array( 'background', 'backgroundImage' ),
 259          'background-position'               => array( 'background', 'backgroundPosition' ),
 260          'background-repeat'                 => array( 'background', 'backgroundRepeat' ),
 261          'background-size'                   => array( 'background', 'backgroundSize' ),
 262          'background-attachment'             => array( 'background', 'backgroundAttachment' ),
 263          'border-radius'                     => array( 'border', 'radius' ),
 264          'border-top-left-radius'            => array( 'border', 'radius', 'topLeft' ),
 265          'border-top-right-radius'           => array( 'border', 'radius', 'topRight' ),
 266          'border-bottom-left-radius'         => array( 'border', 'radius', 'bottomLeft' ),
 267          'border-bottom-right-radius'        => array( 'border', 'radius', 'bottomRight' ),
 268          'border-color'                      => array( 'border', 'color' ),
 269          'border-width'                      => array( 'border', 'width' ),
 270          'border-style'                      => array( 'border', 'style' ),
 271          'border-top-color'                  => array( 'border', 'top', 'color' ),
 272          'border-top-width'                  => array( 'border', 'top', 'width' ),
 273          'border-top-style'                  => array( 'border', 'top', 'style' ),
 274          'border-right-color'                => array( 'border', 'right', 'color' ),
 275          'border-right-width'                => array( 'border', 'right', 'width' ),
 276          'border-right-style'                => array( 'border', 'right', 'style' ),
 277          'border-bottom-color'               => array( 'border', 'bottom', 'color' ),
 278          'border-bottom-width'               => array( 'border', 'bottom', 'width' ),
 279          'border-bottom-style'               => array( 'border', 'bottom', 'style' ),
 280          'border-left-color'                 => array( 'border', 'left', 'color' ),
 281          'border-left-width'                 => array( 'border', 'left', 'width' ),
 282          'border-left-style'                 => array( 'border', 'left', 'style' ),
 283          'color'                             => array( 'color', 'text' ),
 284          'text-align'                        => array( 'typography', 'textAlign' ),
 285          'column-count'                      => array( 'typography', 'textColumns' ),
 286          'font-family'                       => array( 'typography', 'fontFamily' ),
 287          'font-size'                         => array( 'typography', 'fontSize' ),
 288          'font-style'                        => array( 'typography', 'fontStyle' ),
 289          'font-weight'                       => array( 'typography', 'fontWeight' ),
 290          'letter-spacing'                    => array( 'typography', 'letterSpacing' ),
 291          'line-height'                       => array( 'typography', 'lineHeight' ),
 292          'margin'                            => array( 'spacing', 'margin' ),
 293          'margin-top'                        => array( 'spacing', 'margin', 'top' ),
 294          'margin-right'                      => array( 'spacing', 'margin', 'right' ),
 295          'margin-bottom'                     => array( 'spacing', 'margin', 'bottom' ),
 296          'margin-left'                       => array( 'spacing', 'margin', 'left' ),
 297          'min-height'                        => array( 'dimensions', 'minHeight' ),
 298          'min-width'                         => array( 'dimensions', 'minWidth' ),
 299          'outline-color'                     => array( 'outline', 'color' ),
 300          'outline-offset'                    => array( 'outline', 'offset' ),
 301          'outline-style'                     => array( 'outline', 'style' ),
 302          'outline-width'                     => array( 'outline', 'width' ),
 303          'padding'                           => array( 'spacing', 'padding' ),
 304          'padding-top'                       => array( 'spacing', 'padding', 'top' ),
 305          'padding-right'                     => array( 'spacing', 'padding', 'right' ),
 306          'padding-bottom'                    => array( 'spacing', 'padding', 'bottom' ),
 307          'padding-left'                      => array( 'spacing', 'padding', 'left' ),
 308          '--wp--style--root--padding'        => array( 'spacing', 'padding' ),
 309          '--wp--style--root--padding-top'    => array( 'spacing', 'padding', 'top' ),
 310          '--wp--style--root--padding-right'  => array( 'spacing', 'padding', 'right' ),
 311          '--wp--style--root--padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
 312          '--wp--style--root--padding-left'   => array( 'spacing', 'padding', 'left' ),
 313          'text-decoration'                   => array( 'typography', 'textDecoration' ),
 314          'text-shadow'                       => array( 'typography', 'textShadow' ),
 315          'text-transform'                    => array( 'typography', 'textTransform' ),
 316          'text-indent'                       => array( 'typography', 'textIndent' ),
 317          'filter'                            => array( 'filter', 'duotone' ),
 318          'box-shadow'                        => array( 'shadow' ),
 319          'height'                            => array( 'dimensions', 'height' ),
 320          'width'                             => array( 'dimensions', 'width' ),
 321          'writing-mode'                      => array( 'typography', 'writingMode' ),
 322      );
 323  
 324      /**
 325       * Indirect metadata for style properties that are not directly output.
 326       *
 327       * Each element maps from a CSS property name to an array of
 328       * paths to the value in theme.json & block attributes.
 329       *
 330       * Indirect properties are not output directly by `compute_style_properties`,
 331       * but are used elsewhere in the processing of global styles. The indirect
 332       * property is used to validate whether a style value is allowed.
 333       *
 334       * @since 6.2.0
 335       * @since 6.6.0 Added background-image properties.
 336       * @since 7.1.0 Added `background.gradient` to `background-image` paths.
 337       * @var array
 338       */
 339      const INDIRECT_PROPERTIES_METADATA = array(
 340          'gap'              => array(
 341              array( 'spacing', 'blockGap' ),
 342          ),
 343          'column-gap'       => array(
 344              array( 'spacing', 'blockGap', 'left' ),
 345          ),
 346          'row-gap'          => array(
 347              array( 'spacing', 'blockGap', 'top' ),
 348          ),
 349          'max-width'        => array(
 350              array( 'layout', 'contentSize' ),
 351              array( 'layout', 'wideSize' ),
 352          ),
 353          'background-image' => array(
 354              array( 'background', 'backgroundImage', 'url' ),
 355              array( 'background', 'gradient' ),
 356          ),
 357      );
 358  
 359      /**
 360       * Protected style properties.
 361       *
 362       * These style properties are only rendered if a setting enables it
 363       * via a value other than `null`.
 364       *
 365       * Each element maps the style property to the corresponding theme.json
 366       * setting key.
 367       *
 368       * @since 5.9.0
 369       * @var array
 370       */
 371      const PROTECTED_PROPERTIES = array(
 372          'spacing.blockGap' => array( 'spacing', 'blockGap' ),
 373      );
 374  
 375      /**
 376       * The top-level keys a theme.json can have.
 377       *
 378       * @since 5.8.0 As `ALLOWED_TOP_LEVEL_KEYS`.
 379       * @since 5.9.0 Renamed from `ALLOWED_TOP_LEVEL_KEYS` to `VALID_TOP_LEVEL_KEYS`,
 380       *              added the `customTemplates` and `templateParts` values.
 381       * @since 6.3.0 Added the `description` value.
 382       * @since 6.6.0 Added `blockTypes` to support block style variation theme.json partials.
 383       * @var string[]
 384       */
 385      const VALID_TOP_LEVEL_KEYS = array(
 386          'blockTypes',
 387          'customTemplates',
 388          'description',
 389          'patterns',
 390          'settings',
 391          'slug',
 392          'styles',
 393          'templateParts',
 394          'title',
 395          'version',
 396      );
 397  
 398      /**
 399       * The valid properties under the settings key.
 400       *
 401       * @since 5.8.0 As `ALLOWED_SETTINGS`.
 402       * @since 5.9.0 Renamed from `ALLOWED_SETTINGS` to `VALID_SETTINGS`,
 403       *              added new properties for `border`, `color`, `spacing`,
 404       *              and `typography`, and renamed others according to the new schema.
 405       * @since 6.0.0 Added `color.defaultDuotone`.
 406       * @since 6.1.0 Added `layout.definitions` and `useRootPaddingAwareAlignments`.
 407       * @since 6.2.0 Added `dimensions.minHeight`, 'shadow.presets', 'shadow.defaultPresets',
 408       *              `position.fixed` and `position.sticky`.
 409       * @since 6.3.0 Added support for `typography.textColumns`, removed `layout.definitions`.
 410       * @since 6.4.0 Added support for `layout.allowEditing`, `background.backgroundImage`,
 411       *              `typography.writingMode`, `lightbox.enabled` and `lightbox.allowEditing`.
 412       * @since 6.5.0 Added support for `layout.allowCustomContentAndWideSize`,
 413       *              `background.backgroundSize` and `dimensions.aspectRatio`.
 414       * @since 6.6.0 Added support for 'dimensions.aspectRatios', 'dimensions.defaultAspectRatios',
 415       *              'typography.defaultFontSizes', and 'spacing.defaultSpacingSizes'.
 416       * @since 6.9.0 Added support for `border.radiusSizes`.
 417       * @since 7.0.0 Added type markers to the schema for boolean values.
 418       *              Added support for `dimensions.width` and `dimensions.height`.
 419       *              Added support for `typography.textIndent`.
 420       * @since 7.1.0 Added `viewport` property.
 421       *              Added support for `background.gradient`, `dimensions.minWidth` and `blockVisibility.allowEditing`.
 422       * @var array
 423       */
 424      const VALID_SETTINGS = array(
 425          'appearanceTools'               => null,
 426          'useRootPaddingAwareAlignments' => null,
 427          'background'                    => array(
 428              'backgroundImage' => null,
 429              'backgroundSize'  => null,
 430              'gradient'        => null,
 431          ),
 432          'border'                        => array(
 433              'color'       => null,
 434              'radius'      => null,
 435              'radiusSizes' => null,
 436              'style'       => null,
 437              'width'       => null,
 438          ),
 439          'color'                         => array(
 440              'background'       => null,
 441              'custom'           => null,
 442              'customDuotone'    => null,
 443              'customGradient'   => null,
 444              'defaultDuotone'   => null,
 445              'defaultGradients' => null,
 446              'defaultPalette'   => null,
 447              'duotone'          => null,
 448              'gradients'        => null,
 449              'link'             => null,
 450              'heading'          => null,
 451              'button'           => null,
 452              'caption'          => null,
 453              'palette'          => null,
 454              'text'             => null,
 455          ),
 456          'custom'                        => null,
 457          'dimensions'                    => array(
 458              'aspectRatio'         => null,
 459              'aspectRatios'        => null,
 460              'defaultAspectRatios' => null,
 461              'dimensionSizes'      => null,
 462              'height'              => null,
 463              'minHeight'           => null,
 464              'minWidth'            => null,
 465              'width'               => null,
 466          ),
 467          'layout'                        => array(
 468              'contentSize'                   => null,
 469              'wideSize'                      => null,
 470              'allowEditing'                  => null,
 471              'allowCustomContentAndWideSize' => null,
 472          ),
 473          'lightbox'                      => array(
 474              'enabled'      => true,
 475              'allowEditing' => true,
 476          ),
 477          'position'                      => array(
 478              'fixed'  => null,
 479              'sticky' => null,
 480          ),
 481          'blockVisibility'               => array(
 482              'allowEditing' => true,
 483          ),
 484          'spacing'                       => array(
 485              'customSpacingSize'   => null,
 486              'defaultSpacingSizes' => null,
 487              'spacingSizes'        => null,
 488              'spacingScale'        => null,
 489              'blockGap'            => null,
 490              'margin'              => null,
 491              'padding'             => null,
 492              'units'               => null,
 493          ),
 494          'shadow'                        => array(
 495              'presets'        => null,
 496              'defaultPresets' => null,
 497          ),
 498          'typography'                    => array(
 499              'fluid'            => null,
 500              'customFontSize'   => null,
 501              'defaultFontSizes' => null,
 502              'dropCap'          => null,
 503              'fontFamilies'     => null,
 504              'fontSizes'        => null,
 505              'fontStyle'        => null,
 506              'fontWeight'       => null,
 507              'letterSpacing'    => null,
 508              'lineHeight'       => null,
 509              'textAlign'        => null,
 510              'textColumns'      => null,
 511              'textDecoration'   => null,
 512              'textIndent'       => null,
 513              'textTransform'    => null,
 514              'writingMode'      => null,
 515          ),
 516          'viewport'                      => array(
 517              'mobile' => null,
 518              'tablet' => null,
 519          ),
 520      );
 521  
 522      /**
 523       * The valid properties for fontFamilies under settings key.
 524       *
 525       * @since 6.5.0
 526       * @var array
 527       */
 528      const FONT_FAMILY_SCHEMA = array(
 529          array(
 530              'fontFamily' => null,
 531              'name'       => null,
 532              'slug'       => null,
 533              'fontFace'   => array(
 534                  array(
 535                      'ascentOverride'        => null,
 536                      'descentOverride'       => null,
 537                      'fontDisplay'           => null,
 538                      'fontFamily'            => null,
 539                      'fontFeatureSettings'   => null,
 540                      'fontStyle'             => null,
 541                      'fontStretch'           => null,
 542                      'fontVariationSettings' => null,
 543                      'fontWeight'            => null,
 544                      'lineGapOverride'       => null,
 545                      'sizeAdjust'            => null,
 546                      'src'                   => null,
 547                      'unicodeRange'          => null,
 548                  ),
 549              ),
 550          ),
 551      );
 552  
 553      /**
 554       * The valid properties under the styles key.
 555       *
 556       * @since 5.8.0 As `ALLOWED_STYLES`.
 557       * @since 5.9.0 Renamed from `ALLOWED_STYLES` to `VALID_STYLES`,
 558       *              added new properties for `border`, `filter`, `spacing`,
 559       *              and `typography`.
 560       * @since 6.1.0 Added new side properties for `border`,
 561       *              added new property `shadow`,
 562       *              updated `blockGap` to be allowed at any level.
 563       * @since 6.2.0 Added `outline`, and `minHeight` properties.
 564       * @since 6.3.0 Added support for `typography.textColumns`.
 565       * @since 6.5.0 Added support for `dimensions.aspectRatio`.
 566       * @since 6.6.0 Added `background` sub properties to top-level only.
 567       * @since 7.0.0 Added support for `dimensions.width` and `dimensions.height`.
 568       * @since 7.1.0 Added support for `background.gradient`,`dimensions.minWidth`,
 569       *              and `typography.textShadow`.
 570       * @var array
 571       */
 572      const VALID_STYLES = array(
 573          'background' => array(
 574              'backgroundImage'      => null,
 575              'backgroundPosition'   => null,
 576              'backgroundRepeat'     => null,
 577              'backgroundSize'       => null,
 578              'backgroundAttachment' => null,
 579              'gradient'             => null,
 580          ),
 581          'border'     => array(
 582              'color'  => null,
 583              'radius' => null,
 584              'style'  => null,
 585              'width'  => null,
 586              'top'    => null,
 587              'right'  => null,
 588              'bottom' => null,
 589              'left'   => null,
 590          ),
 591          'color'      => array(
 592              'background' => null,
 593              'gradient'   => null,
 594              'text'       => null,
 595          ),
 596          'dimensions' => array(
 597              'aspectRatio' => null,
 598              'height'      => null,
 599              'minHeight'   => null,
 600              'minWidth'    => null,
 601              'width'       => null,
 602          ),
 603          'filter'     => array(
 604              'duotone' => null,
 605          ),
 606          'outline'    => array(
 607              'color'  => null,
 608              'offset' => null,
 609              'style'  => null,
 610              'width'  => null,
 611          ),
 612          'shadow'     => null,
 613          'spacing'    => array(
 614              'margin'   => null,
 615              'padding'  => null,
 616              'blockGap' => null,
 617          ),
 618          'typography' => array(
 619              'fontFamily'     => null,
 620              'fontSize'       => null,
 621              'fontStyle'      => null,
 622              'fontWeight'     => null,
 623              'letterSpacing'  => null,
 624              'lineHeight'     => null,
 625              'textAlign'      => null,
 626              'textColumns'    => null,
 627              'textDecoration' => null,
 628              'textIndent'     => null,
 629              'textShadow'     => null,
 630              'textTransform'  => null,
 631              'writingMode'    => null,
 632          ),
 633          'css'        => null,
 634      );
 635  
 636      /**
 637       * Defines which pseudo selectors are enabled for which elements.
 638       *
 639       * The order of the selectors should be: link, any-link, visited, hover, focus, focus-visible, active.
 640       * This is to ensure the user action (hover, focus and active) styles have a higher
 641       * specificity than the visited styles, which in turn have a higher specificity than
 642       * the unvisited styles.
 643       *
 644       * See https://core.trac.wordpress.org/ticket/56928.
 645       * Note: this will affect both top-level and block-level elements.
 646       *
 647       * @since 6.1.0
 648       * @since 6.2.0 Added support for ':link' and ':any-link'.
 649       * @since 6.8.0 Added support for ':focus-visible'.
 650       * @since 6.9.0 Added `textInput` and `select` elements.
 651       * @var array
 652       */
 653      const VALID_ELEMENT_PSEUDO_SELECTORS = array(
 654          'link'   => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':focus-visible', ':active' ),
 655          'button' => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':focus-visible', ':active' ),
 656      );
 657  
 658      /**
 659       * The valid pseudo-selectors that can be used for blocks.
 660       *
 661       * @since 7.0
 662       * @var array
 663       */
 664      const VALID_BLOCK_PSEUDO_SELECTORS = array(
 665          'core/button'          => array( ':hover', ':focus', ':focus-visible', ':active' ),
 666          'core/navigation-link' => array( ':hover', ':focus', ':focus-visible', ':active' ),
 667      );
 668  
 669      /**
 670       * Custom states for blocks that map to CSS class selectors rather than
 671       * CSS pseudo-selectors. Values use the '-' prefix (e.g. '-current') to
 672       * distinguish them from real CSS pseudo-selectors and breakpoint states.
 673       *
 674       * The CSS selector for each state is defined in the block's block.json
 675       * under `selectors.states`, e.g.:
 676       *
 677       *   "selectors": { "states": { "-current": ".some-css-selector" } }
 678       *
 679       * This constant controls which states are valid in theme.json for a given
 680       * block. Blocks listed here also inherit their VALID_BLOCK_PSEUDO_SELECTORS
 681       * as valid sub-states, producing compound selectors such as
 682       * `.wp-block-navigation-item.current-menu-item:hover`.
 683       *
 684       * @since 7.1.0
 685       * @var array
 686       */
 687      const VALID_BLOCK_CUSTOM_STATES = array(
 688          'core/navigation-link' => array( '-current' ),
 689      );
 690  
 691      /**
 692       * Default viewport breakpoint sizes.
 693       *
 694       * @since 7.1.0
 695       * @var array
 696       */
 697      const DEFAULT_VIEWPORT_BREAKPOINTS = array(
 698          'mobile' => '480px',
 699          'tablet' => '782px',
 700      );
 701  
 702      /**
 703       * Returns CSS media queries for responsive viewport style states.
 704       *
 705       * Breakpoint values are read from `settings.viewport`, sanitized, and
 706       * normalized before the media query strings are generated. By default, the
 707       * returned keys are the theme.json style-state names (`@mobile`, `@tablet`).
 708       * When `$options['include_desktop']` is truthy, `@desktop` is included.
 709       *
 710       * @since 7.1.0
 711       *
 712       * @param mixed $viewport_settings Viewport settings from theme.json.
 713       * @param array $options           {
 714       *     Optional. Options for generating media queries.
 715       *
 716       *     @type bool $include_desktop Whether to include the desktop media query. Default false.
 717       * }
 718       * @return array Responsive media queries.
 719       */
 720  	public static function get_viewport_media_queries( $viewport_settings = null, $options = array() ) {
 721          $breakpoints = static::sanitize_viewport_settings( $viewport_settings );
 722  
 723          $responsive_media_queries = array();
 724  
 725          if ( isset( $breakpoints['mobile'] ) ) {
 726              $responsive_media_queries['@mobile'] = "@media (width <= {$breakpoints['mobile']})";
 727          }
 728  
 729          if ( isset( $breakpoints['tablet'] ) ) {
 730              $responsive_media_queries['@tablet'] = isset( $breakpoints['mobile'] )
 731                  ? sprintf(
 732                      '@media (%s < width <= %s)',
 733                      $breakpoints['mobile'],
 734                      $breakpoints['tablet']
 735                  )
 736                  : "@media (width <= {$breakpoints['tablet']})";
 737          }
 738  
 739          if ( ! empty( $options['include_desktop'] ) ) {
 740              if ( isset( $breakpoints['tablet'] ) ) {
 741                  $desktop_breakpoint = $breakpoints['tablet'];
 742              } else {
 743                  $desktop_breakpoint = $breakpoints['mobile'];
 744              }
 745  
 746              $responsive_media_queries['@desktop'] =
 747                  "@media (width > {$desktop_breakpoint})";
 748          }
 749  
 750          return $responsive_media_queries;
 751      }
 752  
 753      /**
 754       * Checks whether a viewport breakpoint value is a safe CSS length.
 755       *
 756       * Viewport breakpoints are limited to numeric `px`, `em`, and `rem` lengths.
 757       * CSS functions, percentages, and other units are rejected because breakpoint
 758       * values are interpolated into generated media queries.
 759       *
 760       * @since 7.1.0
 761       *
 762       * @param mixed $value Value to check.
 763       * @return bool Whether the value is valid.
 764       */
 765  	private static function is_valid_viewport_breakpoint_size( $value ) {
 766          if ( ! is_string( $value ) ) {
 767              return false;
 768          }
 769  
 770          $value = trim( $value );
 771          if ( '' === $value ) {
 772              return false;
 773          }
 774  
 775          return 1 === preg_match( '/^(?:\d+|\d*\.\d+)(?:px|em|rem)$/', $value );
 776      }
 777  
 778      /**
 779       * Converts a valid viewport breakpoint size to pixels for ordering checks.
 780       *
 781       * Generated media queries keep the original units. This method only
 782       * normalizes values so `mobile` and `tablet` can be compared safely. `em`
 783       * and `rem` lengths use a 16px base for comparison.
 784       *
 785       * @since 7.1.0
 786       *
 787       * @param mixed $value Viewport breakpoint size.
 788       * @return float|null Viewport breakpoint size in pixels, or null when invalid.
 789       */
 790  	private static function get_viewport_breakpoint_value_in_pixels( $value ) {
 791          if ( ! static::is_valid_viewport_breakpoint_size( $value ) ) {
 792              return null;
 793          }
 794  
 795          $value = trim( $value );
 796          $unit  = substr( $value, -3 );
 797          if ( 'rem' === $unit ) {
 798              $number = (float) substr( $value, 0, -3 );
 799          } else {
 800              $unit   = substr( $value, -2 );
 801              $number = (float) substr( $value, 0, -2 );
 802          }
 803  
 804          /*
 805           * Use the most common browser default font size as the base for em/rem
 806           * media query conversions. This pixel value is only used to compare
 807           * breakpoint order; generated media queries keep the original units.
 808           */
 809          return 'px' === $unit ? $number : $number * 16;
 810      }
 811  
 812      /**
 813       * Sanitizes and normalizes viewport breakpoint settings.
 814       *
 815       * Keeps only supported breakpoint keys, trims valid CSS lengths, and returns
 816       * the default breakpoints when no valid custom breakpoint is provided. When
 817       * only one breakpoint is valid, it remains keyed by its configured state and
 818       * uses a single max-width media query. When `tablet` is not larger than
 819       * `mobile`, it is removed.
 820       *
 821       * @since 7.1.0
 822       *
 823       * @param mixed $viewport_settings Viewport settings from theme.json.
 824       * @return array Sanitized viewport breakpoint settings.
 825       */
 826  	private static function sanitize_viewport_settings( $viewport_settings ) {
 827          if ( ! is_array( $viewport_settings ) ) {
 828              return static::DEFAULT_VIEWPORT_BREAKPOINTS;
 829          }
 830  
 831          $breakpoints = array();
 832          foreach ( array_keys( static::DEFAULT_VIEWPORT_BREAKPOINTS ) as $breakpoint ) {
 833              $value = $viewport_settings[ $breakpoint ] ?? null;
 834              $px    = static::get_viewport_breakpoint_value_in_pixels( $value );
 835              if ( null !== $px ) {
 836                  $breakpoints[ $breakpoint ] = array(
 837                      'value' => trim( $value ),
 838                      'px'    => $px,
 839                  );
 840              }
 841          }
 842  
 843          if ( empty( $breakpoints ) ) {
 844              return static::DEFAULT_VIEWPORT_BREAKPOINTS;
 845          }
 846  
 847          if ( 1 === count( $breakpoints ) ) {
 848              $breakpoint = key( $breakpoints );
 849              return array( $breakpoint => $breakpoints[ $breakpoint ]['value'] );
 850          }
 851  
 852          $sanitized = array( 'mobile' => $breakpoints['mobile']['value'] );
 853  
 854          if ( isset( $breakpoints['tablet'] ) && $breakpoints['mobile']['px'] < $breakpoints['tablet']['px'] ) {
 855              $sanitized['tablet'] = $breakpoints['tablet']['value'];
 856          }
 857  
 858          return $sanitized;
 859      }
 860  
 861      /**
 862       * The valid elements that can be found under styles.
 863       *
 864       * @since 5.8.0
 865       * @since 6.1.0 Added `heading`, `button`, and `caption` elements.
 866       * @var string[]
 867       */
 868      const ELEMENTS = array(
 869          'link'      => 'a:where(:not(.wp-element-button))', // The `where` is needed to lower the specificity.
 870          'heading'   => 'h1, h2, h3, h4, h5, h6',
 871          'h1'        => 'h1',
 872          'h2'        => 'h2',
 873          'h3'        => 'h3',
 874          'h4'        => 'h4',
 875          'h5'        => 'h5',
 876          'h6'        => 'h6',
 877          // We have the .wp-block-button__link class so that this will target older buttons that have been serialized.
 878          'button'    => '.wp-element-button, .wp-block-button__link',
 879          // The block classes are necessary to target older content that won't use the new class names.
 880          'caption'   => '.wp-element-caption, .wp-block-audio figcaption, .wp-block-embed figcaption, .wp-block-gallery figcaption, .wp-block-image figcaption, .wp-block-table figcaption, .wp-block-video figcaption',
 881          'cite'      => 'cite',
 882          'textInput' => 'textarea, input:where([type=email],[type=number],[type=password],[type=search],[type=text],[type=tel],[type=url])',
 883          'select'    => 'select',
 884      );
 885  
 886      const __EXPERIMENTAL_ELEMENT_CLASS_NAMES = array(
 887          'button'  => 'wp-element-button',
 888          'caption' => 'wp-element-caption',
 889      );
 890  
 891      /**
 892       * List of block support features that can have their related styles
 893       * generated under their own feature level selector rather than the block's.
 894       *
 895       * @since 6.1.0
 896       * @since 7.0.0 Added support for `dimensions`.
 897       * @var string[]
 898       */
 899      const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = array(
 900          '__experimentalBorder' => 'border',
 901          'color'                => 'color',
 902          'dimensions'           => 'dimensions',
 903          'spacing'              => 'spacing',
 904          'typography'           => 'typography',
 905      );
 906  
 907      /**
 908       * Return the input schema at the root and per origin.
 909       *
 910       * @since 6.5.0
 911       *
 912       * @param array $schema The base schema.
 913       * @return array The schema at the root and per origin.
 914       *
 915       * Example:
 916       * schema_in_root_and_per_origin(
 917       *   array(
 918       *    'fontFamily' => null,
 919       *    'slug' => null,
 920       *   )
 921       * )
 922       *
 923       * Returns:
 924       * array(
 925       *  'fontFamily' => null,
 926       *  'slug' => null,
 927       *  'default' => array(
 928       *    'fontFamily' => null,
 929       *    'slug' => null,
 930       *  ),
 931       *  'blocks' => array(
 932       *    'fontFamily' => null,
 933       *    'slug' => null,
 934       *  ),
 935       *  'theme' => array(
 936       *     'fontFamily' => null,
 937       *     'slug' => null,
 938       *  ),
 939       *  'custom' => array(
 940       *     'fontFamily' => null,
 941       *     'slug' => null,
 942       *  ),
 943       * )
 944       */
 945  	protected static function schema_in_root_and_per_origin( $schema ) {
 946          $schema_in_root_and_per_origin = $schema;
 947          foreach ( static::VALID_ORIGINS as $origin ) {
 948              $schema_in_root_and_per_origin[ $origin ] = $schema;
 949          }
 950          return $schema_in_root_and_per_origin;
 951      }
 952  
 953  
 954      /**
 955       * Processes pseudo-selectors for any node (block or variation).
 956       *
 957       * @param array  $node The node data (block or variation).
 958       * @param string $base_selector The base selector.
 959       * @param array  $settings The theme settings.
 960       * @param string $block_name The block name.
 961       * @param array|null $block_metadata Metadata about the block to get styles for.
 962       * @param array|null $style_variation Style variation metadata.
 963       * @return array Array of pseudo-selector declarations.
 964       */
 965  	private function process_pseudo_selectors( $node, $base_selector, $settings, $block_name, $block_metadata = null, $style_variation = null ) {
 966          $pseudo_declarations = array();
 967          $add_declarations    = static function ( $selector, $declarations ) use ( &$pseudo_declarations ) {
 968              if ( empty( $declarations ) ) {
 969                  return;
 970              }
 971  
 972              if ( isset( $pseudo_declarations[ $selector ] ) ) {
 973                  $pseudo_declarations[ $selector ] = array_merge(
 974                      $pseudo_declarations[ $selector ],
 975                      $declarations
 976                  );
 977              } else {
 978                  $pseudo_declarations[ $selector ] = $declarations;
 979              }
 980          };
 981  
 982          if ( ! isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
 983              return $pseudo_declarations;
 984          }
 985  
 986          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
 987              if ( isset( $node[ $pseudo_selector ] ) ) {
 988                  $pseudo_node = $node[ $pseudo_selector ];
 989  
 990                  if ( is_array( $block_metadata ) ) {
 991                      $feature_declarations = $this->get_feature_declarations_for_node( $block_metadata, $pseudo_node );
 992                      $feature_declarations = static::update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name );
 993                      $feature_declarations = static::update_button_width_declarations( $feature_declarations, $settings );
 994  
 995                      foreach ( $feature_declarations as $feature_selector => $declarations ) {
 996                          $target_selector   = is_array( $style_variation )
 997                              ? static::get_block_style_variation_feature_selector( $style_variation, $feature_selector )
 998                              : $feature_selector;
 999                          $combined_selector = static::append_to_selector( $target_selector, $pseudo_selector );
1000  
1001                          $add_declarations( $combined_selector, $declarations );
1002                      }
1003                  }
1004  
1005                  $combined_selector = static::append_to_selector( $base_selector, $pseudo_selector );
1006                  $declarations      = static::compute_style_properties( $pseudo_node, $settings, null, null );
1007                  $add_declarations( $combined_selector, $declarations );
1008              }
1009          }
1010  
1011          return $pseudo_declarations;
1012      }
1013  
1014  
1015      /**
1016       * Returns a class name by an element name.
1017       *
1018       * @since 6.1.0
1019       *
1020       * @param string $element The name of the element.
1021       * @return string The name of the class.
1022       */
1023  	public static function get_element_class_name( $element ) {
1024          $class_name = '';
1025  
1026          if ( isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ] ) ) {
1027              $class_name = static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ];
1028          }
1029  
1030          return $class_name;
1031      }
1032  
1033      /**
1034       * Options that settings.appearanceTools enables.
1035       *
1036       * @since 6.0.0
1037       * @since 6.2.0 Added `dimensions.minHeight` and `position.sticky`.
1038       * @since 6.4.0 Added `background.backgroundImage`.
1039       * @since 6.5.0 Added `background.backgroundSize` and `dimensions.aspectRatio`.
1040       * @since 7.0.0 Added `dimensions.width` and `dimensions.height`.
1041       * @since 7.1.0 Added `background.gradient`.
1042       *              Added `dimensions.minWidth`.
1043       * @var array
1044       */
1045      const APPEARANCE_TOOLS_OPT_INS = array(
1046          array( 'background', 'backgroundImage' ),
1047          array( 'background', 'backgroundSize' ),
1048          array( 'background', 'gradient' ),
1049          array( 'border', 'color' ),
1050          array( 'border', 'radius' ),
1051          array( 'border', 'style' ),
1052          array( 'border', 'width' ),
1053          array( 'color', 'link' ),
1054          array( 'color', 'heading' ),
1055          array( 'color', 'button' ),
1056          array( 'color', 'caption' ),
1057          array( 'dimensions', 'aspectRatio' ),
1058          array( 'dimensions', 'height' ),
1059          array( 'dimensions', 'minHeight' ),
1060          array( 'dimensions', 'minWidth' ),
1061          array( 'dimensions', 'width' ),
1062          array( 'position', 'sticky' ),
1063          array( 'spacing', 'blockGap' ),
1064          array( 'spacing', 'margin' ),
1065          array( 'spacing', 'padding' ),
1066          array( 'typography', 'lineHeight' ),
1067          array( 'typography', 'textColumns' ),
1068      );
1069  
1070      /**
1071       * The latest version of the schema in use.
1072       *
1073       * @since 5.8.0
1074       * @since 5.9.0 Changed value from 1 to 2.
1075       * @since 6.6.0 Changed value from 2 to 3.
1076       * @var int
1077       */
1078      const LATEST_SCHEMA = 3;
1079  
1080      /**
1081       * Constructor.
1082       *
1083       * @since 5.8.0
1084       * @since 6.6.0 Key spacingScale by origin, and Pre-generate the spacingSizes from spacingScale.
1085       *              Added unwrapping of shared block style variations into block type variations if registered.
1086       *
1087       * @param array  $theme_json A structure that follows the theme.json schema.
1088       * @param string $origin     Optional. What source of data this object represents.
1089       *                           One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'.
1090       */
1091  	public function __construct( $theme_json = array( 'version' => self::LATEST_SCHEMA ), $origin = 'theme' ) {
1092          if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
1093              $origin = 'theme';
1094          }
1095  
1096          $this->theme_json    = WP_Theme_JSON_Schema::migrate( $theme_json, $origin );
1097          $blocks_metadata     = static::get_blocks_metadata();
1098          $valid_block_names   = array_keys( $blocks_metadata );
1099          $valid_element_names = array_keys( static::ELEMENTS );
1100          $valid_variations    = static::get_valid_block_style_variations( $blocks_metadata );
1101          $this->theme_json    = static::unwrap_shared_block_style_variations( $this->theme_json, $valid_variations );
1102          $this->theme_json    = static::sanitize( $this->theme_json, $valid_block_names, $valid_element_names, $valid_variations );
1103          $this->theme_json    = static::maybe_opt_in_into_settings( $this->theme_json );
1104  
1105          // Internally, presets are keyed by origin.
1106          $nodes = static::get_setting_nodes( $this->theme_json );
1107          foreach ( $nodes as $node ) {
1108              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
1109                  $path = $node['path'];
1110                  foreach ( $preset_metadata['path'] as $subpath ) {
1111                      $path[] = $subpath;
1112                  }
1113                  $preset = _wp_array_get( $this->theme_json, $path, null );
1114                  if ( null !== $preset ) {
1115                      // If the preset is not already keyed by origin.
1116                      if ( isset( $preset[0] ) || empty( $preset ) ) {
1117                          _wp_array_set( $this->theme_json, $path, array( $origin => $preset ) );
1118                      }
1119                  }
1120              }
1121          }
1122  
1123          // In addition to presets, spacingScale (which generates presets) is also keyed by origin.
1124          $scale_path    = array( 'settings', 'spacing', 'spacingScale' );
1125          $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null );
1126          if ( null !== $spacing_scale ) {
1127              // If the spacingScale is not already keyed by origin.
1128              if ( empty( array_intersect( array_keys( $spacing_scale ), static::VALID_ORIGINS ) ) ) {
1129                  _wp_array_set( $this->theme_json, $scale_path, array( $origin => $spacing_scale ) );
1130              }
1131          }
1132  
1133          // Pre-generate the spacingSizes from spacingScale.
1134          $scale_path    = array( 'settings', 'spacing', 'spacingScale', $origin );
1135          $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null );
1136          if ( isset( $spacing_scale ) ) {
1137              $sizes_path           = array( 'settings', 'spacing', 'spacingSizes', $origin );
1138              $spacing_sizes        = _wp_array_get( $this->theme_json, $sizes_path, array() );
1139              $spacing_scale_sizes  = static::compute_spacing_sizes( $spacing_scale );
1140              $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes );
1141              _wp_array_set( $this->theme_json, $sizes_path, $merged_spacing_sizes );
1142          }
1143      }
1144  
1145      /**
1146       * Unwraps shared block style variations.
1147       *
1148       * It takes the shared variations (styles.variations.variationName) and
1149       * applies them to all the blocks that have the given variation registered
1150       * (styles.blocks.blockType.variations.variationName).
1151       *
1152       * For example, given the `core/paragraph` and `core/group` blocks have
1153       * registered the `section-a` style variation, and given the following input:
1154       *
1155       * {
1156       *   "styles": {
1157       *     "variations": {
1158       *       "section-a": { "color": { "background": "backgroundColor" } }
1159       *     }
1160       *   }
1161       * }
1162       *
1163       * It returns the following output:
1164       *
1165       * {
1166       *   "styles": {
1167       *     "blocks": {
1168       *       "core/paragraph": {
1169       *         "variations": {
1170       *             "section-a": { "color": { "background": "backgroundColor" } }
1171       *         },
1172       *       },
1173       *       "core/group": {
1174       *         "variations": {
1175       *           "section-a": { "color": { "background": "backgroundColor" } }
1176       *         }
1177       *       }
1178       *     }
1179       *   }
1180       * }
1181       *
1182       * @since 6.6.0
1183       *
1184       * @param array $theme_json       A structure that follows the theme.json schema.
1185       * @param array $valid_variations Valid block style variations.
1186       * @return array Theme json data with shared variation definitions unwrapped under appropriate block types.
1187       */
1188  	private static function unwrap_shared_block_style_variations( $theme_json, $valid_variations ) {
1189          if ( empty( $theme_json['styles']['variations'] ) || empty( $valid_variations ) ) {
1190              return $theme_json;
1191          }
1192  
1193          $new_theme_json = $theme_json;
1194          $variations     = $new_theme_json['styles']['variations'];
1195  
1196          foreach ( $valid_variations as $block_type => $registered_variations ) {
1197              foreach ( $registered_variations as $variation_name ) {
1198                  $block_level_data = $new_theme_json['styles']['blocks'][ $block_type ]['variations'][ $variation_name ] ?? array();
1199                  $top_level_data   = $variations[ $variation_name ] ?? array();
1200                  $merged_data      = array_replace_recursive( $top_level_data, $block_level_data );
1201                  if ( ! empty( $merged_data ) ) {
1202                      _wp_array_set( $new_theme_json, array( 'styles', 'blocks', $block_type, 'variations', $variation_name ), $merged_data );
1203                  }
1204              }
1205          }
1206  
1207          unset( $new_theme_json['styles']['variations'] );
1208  
1209          return $new_theme_json;
1210      }
1211  
1212      /**
1213       * Enables some opt-in settings if theme declared support.
1214       *
1215       * @since 5.9.0
1216       *
1217       * @param array $theme_json A theme.json structure to modify.
1218       * @return array The modified theme.json structure.
1219       */
1220  	protected static function maybe_opt_in_into_settings( $theme_json ) {
1221          $new_theme_json = $theme_json;
1222  
1223          if (
1224              isset( $new_theme_json['settings']['appearanceTools'] ) &&
1225              true === $new_theme_json['settings']['appearanceTools']
1226          ) {
1227              static::do_opt_in_into_settings( $new_theme_json['settings'] );
1228          }
1229  
1230          if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) {
1231              foreach ( $new_theme_json['settings']['blocks'] as &$block ) {
1232                  if ( isset( $block['appearanceTools'] ) && ( true === $block['appearanceTools'] ) ) {
1233                      static::do_opt_in_into_settings( $block );
1234                  }
1235              }
1236          }
1237  
1238          return $new_theme_json;
1239      }
1240  
1241      /**
1242       * Enables some settings.
1243       *
1244       * @since 5.9.0
1245       *
1246       * @param array $context The context to which the settings belong.
1247       */
1248  	protected static function do_opt_in_into_settings( &$context ) {
1249          foreach ( static::APPEARANCE_TOOLS_OPT_INS as $path ) {
1250              /*
1251               * Use "unset prop" as a marker instead of "null" because
1252               * "null" can be a valid value for some props (e.g. blockGap).
1253               */
1254              if ( 'unset prop' === _wp_array_get( $context, $path, 'unset prop' ) ) {
1255                  _wp_array_set( $context, $path, true );
1256              }
1257          }
1258  
1259          unset( $context['appearanceTools'] );
1260      }
1261  
1262      /**
1263       * Sanitizes the input according to the schemas.
1264       *
1265       * @since 5.8.0
1266       * @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters.
1267       * @since 6.3.0 Added the `$valid_variations` parameter.
1268       * @since 6.6.0 Updated schema to allow extended block style variations.
1269       *
1270       * @param array $input               Structure to sanitize.
1271       * @param array $valid_block_names   List of valid block names.
1272       * @param array $valid_element_names List of valid element names.
1273       * @param array $valid_variations    List of valid variations per block.
1274       * @return array The sanitized output.
1275       */
1276  	protected static function sanitize( $input, $valid_block_names, $valid_element_names, $valid_variations ) {
1277          $output = array();
1278  
1279          if ( ! is_array( $input ) ) {
1280              return $output;
1281          }
1282  
1283          // Preserve only the top most level keys.
1284          $output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) );
1285  
1286          /*
1287           * Remove any rules that are annotated as "top" in VALID_STYLES constant.
1288           * Some styles are only meant to be available at the top-level (e.g.: blockGap),
1289           * hence, the schema for blocks & elements should not have them.
1290           */
1291          $styles_non_top_level = static::VALID_STYLES;
1292          foreach ( array_keys( $styles_non_top_level ) as $section ) {
1293              // array_key_exists() needs to be used instead of isset() because the value can be null.
1294              if ( array_key_exists( $section, $styles_non_top_level ) && is_array( $styles_non_top_level[ $section ] ) ) {
1295                  foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) {
1296                      if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) {
1297                          unset( $styles_non_top_level[ $section ][ $prop ] );
1298                      }
1299                  }
1300              }
1301          }
1302  
1303          // Build the schema based on valid block & element names.
1304          $schema                   = array();
1305          $schema_styles_elements   = array();
1306          $responsive_media_queries = static::get_viewport_media_queries( $input['settings']['viewport'] ?? null );
1307  
1308          /*
1309           * Set allowed element pseudo selectors and responsive breakpoint states.
1310           * Target data structure in schema:
1311           * e.g.
1312           * - top level elements: `$schema['styles']['elements']['link'][':hover']`.
1313           * - block level elements: `$schema['styles']['blocks']['core/button']['elements']['link'][':hover']`.
1314           * - block responsive elements: `$schema['styles']['blocks']['core/button']['@tablet']['elements']['link'][':hover']`.
1315           */
1316          foreach ( $valid_element_names as $element ) {
1317              $schema_styles_elements[ $element ] = $styles_non_top_level;
1318  
1319              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
1320                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
1321                      $schema_styles_elements[ $element ][ $pseudo_selector ] = $styles_non_top_level;
1322                  }
1323              }
1324  
1325              // Add responsive breakpoint states for elements.
1326              foreach ( array_keys( $responsive_media_queries ) as $breakpoint_state ) {
1327                  $schema_styles_elements[ $element ][ $breakpoint_state ] = $styles_non_top_level;
1328              }
1329          }
1330  
1331          $schema_styles_blocks   = array();
1332          $schema_settings_blocks = array();
1333  
1334          /*
1335           * Generate a schema for blocks.
1336           * - Block styles can contain `elements`, `variations`, and responsive breakpoint state definitions.
1337           * - Variations definitions cannot be nested.
1338           * - Variations can contain styles for inner `blocks`, `elements`, and responsive breakpoint states.
1339           * - Variation inner `blocks` styles can contain `elements` and responsive breakpoint states.
1340           *
1341           * As each variation needs both a `blocks` schema and responsive `blocks` schemas
1342           * for further nested inner `blocks`, the overall schema is generated in multiple passes.
1343           */
1344          foreach ( $valid_block_names as $block ) {
1345              $schema_settings_blocks[ $block ] = static::VALID_SETTINGS;
1346              // `viewport` and `blockVisibility` are global-only settings and cannot be set per block for now.
1347              unset( $schema_settings_blocks[ $block ]['viewport'] );
1348              unset( $schema_settings_blocks[ $block ]['blockVisibility'] );
1349              $schema_styles_blocks[ $block ]             = $styles_non_top_level;
1350              $schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
1351  
1352              // Add responsive breakpoint states for all blocks.
1353              foreach ( array_keys( $responsive_media_queries ) as $breakpoint_state ) {
1354                  $schema_styles_blocks[ $block ][ $breakpoint_state ]             = $styles_non_top_level;
1355                  $schema_styles_blocks[ $block ][ $breakpoint_state ]['elements'] = $schema_styles_elements;
1356  
1357                  if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1358                      foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1359                          $schema_styles_blocks[ $block ][ $breakpoint_state ][ $pseudo_selector ] = $styles_non_top_level;
1360                      }
1361                  }
1362              }
1363  
1364              // Add pseudo-selectors for blocks that support them
1365              if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1366                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1367                      $schema_styles_blocks[ $block ][ $pseudo_selector ] = $styles_non_top_level;
1368                  }
1369              }
1370  
1371              // Add custom states for blocks that support them (e.g. '-current' for navigation).
1372              if ( isset( static::VALID_BLOCK_CUSTOM_STATES[ $block ] ) ) {
1373                  foreach ( static::VALID_BLOCK_CUSTOM_STATES[ $block ] as $custom_state ) {
1374                      $custom_state_schema = $styles_non_top_level;
1375                      /*
1376                       * The same pseudo-selectors valid for the block at the top level
1377                       * are also valid within each custom state.
1378                       */
1379                      if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1380                          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo ) {
1381                              $custom_state_schema[ $pseudo ] = $styles_non_top_level;
1382                          }
1383                      }
1384                      $schema_styles_blocks[ $block ][ $custom_state ] = $custom_state_schema;
1385                  }
1386              }
1387          }
1388  
1389          $block_style_variation_styles             = static::VALID_STYLES;
1390          $block_style_variation_styles['blocks']   = $schema_styles_blocks;
1391          $block_style_variation_styles['elements'] = $schema_styles_elements;
1392  
1393          foreach ( $valid_block_names as $block ) {
1394              // Build the schema for each block style variation.
1395              $style_variation_names = array();
1396              if (
1397                  ! empty( $input['styles']['blocks'][ $block ]['variations'] ) &&
1398                  is_array( $input['styles']['blocks'][ $block ]['variations'] ) &&
1399                  isset( $valid_variations[ $block ] )
1400              ) {
1401                  $style_variation_names = array_intersect(
1402                      array_keys( $input['styles']['blocks'][ $block ]['variations'] ),
1403                      $valid_variations[ $block ]
1404                  );
1405              }
1406  
1407              $schema_styles_variations = array();
1408              if ( ! empty( $style_variation_names ) ) {
1409                  foreach ( $style_variation_names as $variation_name ) {
1410                      $variation_schema = $block_style_variation_styles;
1411  
1412                      // Add responsive breakpoint states to block style variations.
1413                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint_state ) {
1414                          $variation_schema[ $breakpoint_state ]             = $styles_non_top_level;
1415                          $variation_schema[ $breakpoint_state ]['elements'] = $schema_styles_elements;
1416                          $variation_schema[ $breakpoint_state ]['blocks']   = $schema_styles_blocks;
1417  
1418                          if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1419                              foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1420                                  $variation_schema[ $breakpoint_state ][ $pseudo_selector ] = $styles_non_top_level;
1421                              }
1422                          }
1423                      }
1424  
1425                      // Add pseudo-selectors to variations for blocks that support them
1426                      if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1427                          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1428                              $variation_schema[ $pseudo_selector ] = $styles_non_top_level;
1429                          }
1430                      }
1431  
1432                      $schema_styles_variations[ $variation_name ] = $variation_schema;
1433                  }
1434              }
1435  
1436              $schema_styles_blocks[ $block ]['variations'] = $schema_styles_variations;
1437          }
1438  
1439          $schema['styles']                                 = static::VALID_STYLES;
1440          $schema['styles']['blocks']                       = $schema_styles_blocks;
1441          $schema['styles']['elements']                     = $schema_styles_elements;
1442          $schema['settings']                               = static::VALID_SETTINGS;
1443          $schema['settings']['blocks']                     = $schema_settings_blocks;
1444          $schema['settings']['typography']['fontFamilies'] = static::schema_in_root_and_per_origin( static::FONT_FAMILY_SCHEMA );
1445  
1446          // Remove anything that's not present in the schema.
1447          foreach ( array( 'styles', 'settings' ) as $subtree ) {
1448              if ( ! isset( $input[ $subtree ] ) ) {
1449                  continue;
1450              }
1451  
1452              if ( ! is_array( $input[ $subtree ] ) ) {
1453                  unset( $output[ $subtree ] );
1454                  continue;
1455              }
1456  
1457              $result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
1458  
1459              if ( 'settings' === $subtree && array_key_exists( 'viewport', $input[ $subtree ] ) ) {
1460                  $result['viewport'] = static::sanitize_viewport_settings( $input[ $subtree ]['viewport'] );
1461              }
1462  
1463              if ( empty( $result ) ) {
1464                  unset( $output[ $subtree ] );
1465              } else {
1466                  $output[ $subtree ] = static::resolve_custom_css_format( $result );
1467              }
1468          }
1469  
1470          return $output;
1471      }
1472  
1473      /**
1474       * Appends a sub-selector to an existing one.
1475       *
1476       * Given the compounded $selector "h1, h2, h3"
1477       * and the $to_append selector ".some-class" the result will be
1478       * "h1.some-class, h2.some-class, h3.some-class".
1479       *
1480       * @since 5.8.0
1481       * @since 6.1.0 Added append position.
1482       * @since 6.3.0 Removed append position parameter.
1483       *
1484       * @param string $selector  Original selector.
1485       * @param string $to_append Selector to append.
1486       * @return string The new selector.
1487       */
1488  	protected static function append_to_selector( $selector, $to_append ) {
1489          if ( ! str_contains( $selector, ',' ) ) {
1490              return trim( $selector, " \t\n" ) . $to_append;
1491          }
1492  
1493          /**
1494           * Check for an opportunity to skip the more-costly selector splitting.
1495           * This should be possible if there are no comments, strings, functions,
1496           * URLs, escapes, or comment declaration openers (CDOs).
1497           *
1498           * Note that this means the fast-path will not apply for selectors like
1499           * the following incomplete list:
1500           *
1501           *  - `[class ~= "wide"]`
1502           *  - `.wp-block:is(.is-style-a, .is-style-b)`
1503           *  - `:nth-child(1)`
1504           *
1505           * These syntax forms all present opportunities where a comma may not
1506           * separate selectors. If none of the start characters are present,
1507           * there should be no way for a comma to mean anything other than a
1508           * comma token. The exception are syntax errors, which are not handled here.
1509           *
1510           * @see https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
1511           */
1512          if ( strlen( $selector ) === strcspn( $selector, '/\'"(<\\' ) ) {
1513              return preg_replace( '~[ \t\n]*,[ \t\n]*~', "{$to_append}, ", trim( $selector, " \t\n" ) ) . $to_append;
1514          }
1515  
1516          $new_selectors = array();
1517          $selectors     = static::split_selector_list( $selector );
1518          foreach ( $selectors as $sel ) {
1519              $new_selectors[] = $sel . $to_append;
1520          }
1521          return implode( ', ', $new_selectors );
1522      }
1523  
1524      /**
1525       * Prepends a sub-selector to an existing one.
1526       *
1527       * Given the compounded $selector "h1, h2, h3"
1528       * and the $to_prepend selector ".some-class " the result will be
1529       * ".some-class h1, .some-class  h2, .some-class  h3".
1530       *
1531       * @since 6.3.0
1532       *
1533       * @param string $selector   Original selector.
1534       * @param string $to_prepend Selector to prepend.
1535       * @return string The new selector.
1536       */
1537  	protected static function prepend_to_selector( $selector, $to_prepend ) {
1538          if ( ! str_contains( $selector, ',' ) ) {
1539              return $to_prepend . trim( $selector, " \t\n" );
1540          }
1541  
1542          /**
1543           * Check for an opportunity to skip the more-costly selector splitting.
1544           * This should be possible if there are no comments, strings, functions,
1545           * URLs, escapes, or comment declaration openers (CDOs).
1546           *
1547           * Note that this means the fast-path will not apply for selectors like
1548           * the following incomplete list:
1549           *
1550           *  - `[class ~= "wide"]`
1551           *  - `.wp-block:is(.is-style-a, .is-style-b)`
1552           *  - `:nth-child(1)`
1553           *
1554           * These syntax forms all present opportunities where a comma may not
1555           * separate selectors. If none of the start characters are present,
1556           * there should be no way for a comma to mean anything other than a
1557           * comma token. The exception are syntax errors, which are not handled here.
1558           *
1559           * @see https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
1560           */
1561          if ( strlen( $selector ) === strcspn( $selector, '/\'"(<\\' ) ) {
1562              return $to_prepend . preg_replace( '~[ \t\n]*,[ \t\n]*~', ", {$to_prepend}", trim( $selector, " \t\n" ) );
1563          }
1564  
1565          $new_selectors = array();
1566          $selectors     = static::split_selector_list( $selector );
1567          foreach ( $selectors as $sel ) {
1568              $new_selectors[] = $to_prepend . $sel;
1569          }
1570          return implode( ', ', $new_selectors );
1571      }
1572  
1573      /**
1574       * Splits a selector list into separate selectors.
1575       *
1576       * While selectors are joined by commas, not all commas separate top-level selectors.
1577       * This method only separates top-level selectors, so some commas may appear inside
1578       * strings, nested selectors, and comments. Leading and trailing CSS whitespace is
1579       * trimmed from the returned list items.
1580       *
1581       * Non-selector content, such as comments, are retained in the list in the same item
1582       * as the selector content they follow.
1583       *
1584       * Example:
1585       *
1586       *     array( '.wp-block' )    === self::split_selector_list( '.wp-block' );
1587       *     array( '.one', '.two' ) === self::split_selector_list( '.one, .two' );
1588       *
1589       *     // Nested selector lists are retained within their containing selector.
1590       *     array( ':is(.a, .b)', 'c' ) === self::split_selector_list( ':is(.a, .b), .c' );
1591       *
1592       *     // Commas within strings do not separate selectors.
1593       *     $selectors   = self::split_selector_list( '[data-label="Save, continue"],.fallback' );
1594       *     $selectors === array( '[data-label="Save, continue"]', '.fallback' )
1595       *
1596       *     array( 'lang(zh, "*-hant")', '.foo' ) === self::split_selector_list( 'lang(zh, "*-hant"), .foo' );
1597       *
1598       *     // Identifiers may contain escaped commas.
1599       *     array( '.foo\,bar', '.baz' ) === self::split_selector_list( '.foo\,bar,.baz' );
1600       *
1601       *     // Comments stay with the selector they follow.
1602       *     array( '.a /* a, the first *\/', '.b' ) === self::split_selector_list( '.a /* a, the first *\/,.b' );
1603       *
1604       * @see https://www.w3.org/TR/selectors/#parse-selector
1605       * @see https://www.w3.org/TR/css-syntax-3/
1606       *
1607       * @since 7.1.0
1608       *
1609       * @param string $selector CSS selector list as a string, e.g. '.wp-block .wp-block-paragraph'.
1610       * @return string[] List of trimmed selectors parsed from input list.
1611       */
1612  	protected static function split_selector_list( $selector ): array {
1613          if ( ! str_contains( $selector, ',' ) ) {
1614              // See note on trimming CSS whitespace in main loop.
1615              return array( trim( $selector, " \t\n" ) );
1616          }
1617  
1618          $selectors         = array();
1619          $selector_length   = strlen( $selector );
1620          $parentheses_depth = 0;
1621          $at                = 0;
1622          $was_at            = 0;
1623  
1624          while ( $at < $selector_length ) {
1625              $next_at = $at + strcspn( $selector, '/,\'"()<-\\', $at );
1626              if ( $next_at >= $selector_length ) {
1627                  break;
1628              }
1629  
1630              $next_cp = $selector[ $next_at ];
1631  
1632              // Escaped syntax characters do not act as delimiters.
1633              if ( '\\' === $next_cp ) {
1634                  $at = min( $next_at + 2, $selector_length );
1635                  continue;
1636              }
1637  
1638              /*
1639               * Start of a parenthesized expression, which maintains a stack of parentheses.
1640               * For the sake of this function, no selector list will be split inside parentheses.
1641               * Therefore it’s possible to jump ahead until this list completes.
1642               */
1643              if ( '(' === $next_cp || ')' === $next_cp ) {
1644                  $parentheses_depth += '(' === $next_cp ? 1 : -1;
1645                  $at                 = $next_at + 1;
1646                  continue;
1647              }
1648  
1649              // Start of a string, which will be incorporated into the selector in which it’s found.
1650              if ( "'" === $next_cp || '"' === $next_cp ) {
1651                  $end_of_string = $next_at + 1;
1652                  while ( $end_of_string < $selector_length ) {
1653                      $end_of_string += strcspn( $selector, "{$next_cp}\\", $end_of_string );
1654                      if ( $end_of_string >= $selector_length ) {
1655                          break;
1656                      }
1657  
1658                      $end_cp = $selector[ $end_of_string ];
1659  
1660                      // Skip escaped characters.
1661                      if ( '\\' === $end_cp ) {
1662                          $end_of_string = $end_of_string + 2;
1663                          continue;
1664                      }
1665  
1666                      if ( $next_cp === $end_cp ) {
1667                          ++$end_of_string;
1668                          break;
1669                      }
1670  
1671                      ++$end_of_string;
1672                  }
1673  
1674                  $at = $end_of_string;
1675                  continue;
1676              }
1677  
1678              // Start of a comment, which will be incorporated into the selector in which it’s found.
1679              if ( '/' === $next_cp && ( $next_at + 1 ) < $selector_length && '*' === $selector[ $next_at + 1 ] ) {
1680                  $comment_end_at = strpos( $selector, '*/', $next_at + 1 );
1681                  $is_terminated  = false !== $comment_end_at;
1682                  $after_comment  = $is_terminated ? $comment_end_at + 2 : strlen( $selector );
1683                  $at             = $after_comment;
1684                  continue;
1685              }
1686  
1687              // Start of a CDO or CDC, which will be incorporated into the selector in which it’s found.
1688              if (
1689                  ( '<' === $next_cp && 0 === substr_compare( $selector, '<!--', $next_at, 4 ) ) ||
1690                  ( '-' === $next_cp && 0 === substr_compare( $selector, '-->', $next_at, 3 ) )
1691              ) {
1692                  $at = $next_at + ( '<' === $next_cp ? 4 : 3 );
1693                  continue;
1694              }
1695  
1696              // Everything else is either a comma token or part of a selector.
1697              if ( ',' === $next_cp && 0 === $parentheses_depth ) {
1698                  /**
1699                   * Trim each selector so that downstream code doesn’t see whitespace
1700                   * as the first character in a selector and get confused.
1701                   *
1702                   * There is inconsistency in this because comments and other syntax
1703                   * are included which are also not part of the selector itself, but
1704                   * a tradeoff is made between removing common syntax which carries
1705                   * no meaning and rarer syntax which leaves auxiliary information.
1706                   *
1707                   * > A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE.
1708                   * > Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are
1709                   * > not included in this definition, as they are converted
1710                   * > to U+000A LINE FEED during preprocessing.
1711                   *
1712                   * @see https://www.w3.org/TR/css-syntax/#whitespace
1713                   * @see https://www.w3.org/TR/css-syntax/#newline
1714                   */
1715                  $selectors[] = trim( substr( $selector, $was_at, $next_at - $was_at ), " \t\n" );
1716                  $at          = $next_at + 1;
1717                  $was_at      = $at;
1718                  continue;
1719              }
1720  
1721              $at = $next_at + 1;
1722          }
1723  
1724          if ( $was_at < $selector_length ) {
1725              // See note on trimming CSS whitespace in main loop.
1726              $selectors[] = trim( substr( $selector, $was_at ), " \t\n" );
1727          }
1728  
1729          return $selectors;
1730      }
1731  
1732      /**
1733       * Returns the metadata for each block.
1734       *
1735       * Example:
1736       *
1737       *     {
1738       *       'core/paragraph': {
1739       *         'selector': 'p',
1740       *         'elements': {
1741       *           'link' => 'link selector',
1742       *           'etc'  => 'element selector'
1743       *         }
1744       *       },
1745       *       'core/heading': {
1746       *         'selector': 'h1',
1747       *         'elements': {}
1748       *       },
1749       *       'core/image': {
1750       *         'selector': '.wp-block-image',
1751       *         'duotone': 'img',
1752       *         'elements': {}
1753       *       }
1754       *     }
1755       *
1756       * @since 5.8.0
1757       * @since 5.9.0 Added `duotone` key with CSS selector.
1758       * @since 6.1.0 Added `features` key with block support feature level selectors.
1759       * @since 6.3.0 Refactored and stabilized selectors API.
1760       * @since 6.6.0 Updated to include block style variations from the block styles registry.
1761       *
1762       * @return array Block metadata.
1763       */
1764  	protected static function get_blocks_metadata() {
1765          $registry       = WP_Block_Type_Registry::get_instance();
1766          $blocks         = $registry->get_all_registered();
1767          $style_registry = WP_Block_Styles_Registry::get_instance();
1768  
1769          // Is there metadata for all currently registered blocks?
1770          $blocks = array_diff_key( $blocks, static::$blocks_metadata );
1771          if ( empty( $blocks ) ) {
1772              /*
1773               * New block styles may have been registered within WP_Block_Styles_Registry.
1774               * Update block metadata for any new block style variations.
1775               */
1776              $registered_styles = $style_registry->get_all_registered();
1777              foreach ( static::$blocks_metadata as $block_name => $block_metadata ) {
1778                  if ( ! empty( $registered_styles[ $block_name ] ) ) {
1779                      $style_selectors = $block_metadata['styleVariations'] ?? array();
1780  
1781                      foreach ( $registered_styles[ $block_name ] as $block_style ) {
1782                          if ( ! isset( $style_selectors[ $block_style['name'] ] ) ) {
1783                              $style_selectors[ $block_style['name'] ] = static::get_block_style_variation_selector( $block_style['name'], $block_metadata['selector'] );
1784                          }
1785                      }
1786  
1787                      static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors;
1788                  }
1789              }
1790              return static::$blocks_metadata;
1791          }
1792  
1793          foreach ( $blocks as $block_name => $block_type ) {
1794              $root_selector = wp_get_block_css_selector( $block_type );
1795  
1796              static::$blocks_metadata[ $block_name ]['selector']  = $root_selector;
1797              static::$blocks_metadata[ $block_name ]['selectors'] = static::get_block_selectors( $block_type, $root_selector );
1798  
1799              $elements = static::get_block_element_selectors( $root_selector );
1800              if ( ! empty( $elements ) ) {
1801                  static::$blocks_metadata[ $block_name ]['elements'] = $elements;
1802              }
1803  
1804              // The block may or may not have a duotone selector.
1805              $duotone_selector = wp_get_block_css_selector( $block_type, 'filter.duotone' );
1806  
1807              // Keep backwards compatibility for support.color.__experimentalDuotone.
1808              if ( null === $duotone_selector ) {
1809                  $duotone_support = $block_type->supports['color']['__experimentalDuotone'] ?? null;
1810  
1811                  if ( $duotone_support ) {
1812                      $root_selector    = wp_get_block_css_selector( $block_type );
1813                      $duotone_selector = static::scope_selector( $root_selector, $duotone_support );
1814                  }
1815              }
1816  
1817              if ( null !== $duotone_selector ) {
1818                  static::$blocks_metadata[ $block_name ]['duotone'] = $duotone_selector;
1819              }
1820  
1821              // If the block has style variations, append their selectors to the block metadata.
1822              $style_selectors = array();
1823              if ( ! empty( $block_type->styles ) ) {
1824                  foreach ( $block_type->styles as $style ) {
1825                      $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] );
1826                  }
1827              }
1828  
1829              // Block style variations can be registered through the WP_Block_Styles_Registry as well as block.json.
1830              $registered_styles = $style_registry->get_registered_styles_for_block( $block_name );
1831              foreach ( $registered_styles as $style ) {
1832                  $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] );
1833              }
1834  
1835              if ( ! empty( $style_selectors ) ) {
1836                  static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors;
1837              }
1838  
1839              // If the block has custom states defined in block.json, store their selectors.
1840              if ( ! empty( $block_type->selectors['states'] ) && is_array( $block_type->selectors['states'] ) ) {
1841                  static::$blocks_metadata[ $block_name ]['states'] = $block_type->selectors['states'];
1842              }
1843          }
1844  
1845          return static::$blocks_metadata;
1846      }
1847  
1848      /**
1849       * Given a tree, removes the keys that are not present in the schema.
1850       *
1851       * It is recursive and modifies the input in-place.
1852       *
1853       * @since 5.8.0
1854       * @since 7.0.0 Added type validation for boolean values.
1855       *
1856       * @param array $tree   Input to process.
1857       * @param array $schema Schema to adhere to.
1858       * @return array The modified $tree.
1859       */
1860  	protected static function remove_keys_not_in_schema( $tree, $schema ) {
1861          if ( ! is_array( $tree ) ) {
1862              return $tree;
1863          }
1864  
1865          foreach ( $tree as $key => $value ) {
1866              // Remove keys not in the schema or with null/empty values.
1867              if ( ! array_key_exists( $key, $schema ) ) {
1868                  unset( $tree[ $key ] );
1869                  continue;
1870              }
1871  
1872              // Validate type if schema specifies a boolean marker.
1873              if ( is_bool( $schema[ $key ] ) ) {
1874                  // Schema expects a boolean value - validate the input matches.
1875                  if ( ! is_bool( $value ) ) {
1876                      unset( $tree[ $key ] );
1877                      continue;
1878                  }
1879                  // Type matches, keep the value and continue to next key.
1880                  continue;
1881              }
1882  
1883              if ( is_array( $schema[ $key ] ) ) {
1884                  if ( ! is_array( $value ) ) {
1885                      unset( $tree[ $key ] );
1886                  } elseif ( wp_is_numeric_array( $value ) ) {
1887                      // If indexed, process each item in the array.
1888                      foreach ( $value as $item_key => $item_value ) {
1889                          if ( isset( $schema[ $key ][0] ) && is_array( $schema[ $key ][0] ) ) {
1890                              $tree[ $key ][ $item_key ] = self::remove_keys_not_in_schema( $item_value, $schema[ $key ][0] );
1891                          } else {
1892                              // If the schema does not define a further structure, keep the value as is.
1893                              $tree[ $key ][ $item_key ] = $item_value;
1894                          }
1895                      }
1896                  } else {
1897                      // If associative, process as a single object.
1898                      $tree[ $key ] = self::remove_keys_not_in_schema( $value, $schema[ $key ] );
1899  
1900                      if ( empty( $tree[ $key ] ) ) {
1901                          unset( $tree[ $key ] );
1902                      }
1903                  }
1904              }
1905          }
1906          return $tree;
1907      }
1908  
1909      /**
1910       * Returns the existing settings for each block.
1911       *
1912       * Example:
1913       *
1914       *     {
1915       *       'root': {
1916       *         'color': {
1917       *           'custom': true
1918       *         }
1919       *       },
1920       *       'core/paragraph': {
1921       *         'spacing': {
1922       *           'customPadding': true
1923       *         }
1924       *       }
1925       *     }
1926       *
1927       * @since 5.8.0
1928       *
1929       * @return array Settings per block.
1930       */
1931  	public function get_settings() {
1932          if ( ! isset( $this->theme_json['settings'] ) ) {
1933              return array();
1934          } else {
1935              return $this->theme_json['settings'];
1936          }
1937      }
1938  
1939      /**
1940       * Returns the stylesheet that results of processing
1941       * the theme.json structure this object represents.
1942       *
1943       * @since 5.8.0
1944       * @since 5.9.0 Removed the `$type` parameter, added the `$types` and `$origins` parameters.
1945       * @since 6.3.0 Add fallback layout styles for Post Template when block gap support isn't available.
1946       * @since 6.6.0 Added boolean `skip_root_layout_styles` and `include_block_style_variations` options
1947       *              to control styles output as desired.
1948       * @since 7.0.0 Deprecated 'base-layout-styles' type; added `base_layout_styles` option for classic themes.
1949       *
1950       * @param string[] $types   Types of styles to load. Will load all by default. It accepts:
1951       *                          - `variables`: only the CSS Custom Properties for presets & custom ones.
1952       *                          - `styles`: only the styles section in theme.json.
1953       *                          - `presets`: only the classes for the presets.
1954       *                          - `base-layout-styles`: only the base layout styles. Deprecated in 7.0.0.
1955       *                          - `custom-css`: only the custom CSS.
1956       * @param string[] $origins A list of origins to include. By default it includes VALID_ORIGINS.
1957       * @param array    $options {
1958       *     Optional. An array of options for now used for internal purposes only (may change without notice).
1959       *
1960       *     @type string $scope                           Makes sure all style are scoped to a given selector
1961       *     @type string $root_selector                   Overwrites and forces a given selector to be used on the root node
1962       *     @type bool   $skip_root_layout_styles         Omits root layout styles from the generated stylesheet. Default false.
1963       *     @type bool   $base_layout_styles              When true generates only base layout styles without alignment rules. Default false.
1964       *     @type bool   $include_block_style_variations  Includes styles for block style variations in the generated stylesheet. Default false.
1965       * }
1966       * @return string The resulting stylesheet.
1967       */
1968  	public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null, $options = array() ) {
1969          if ( null === $origins ) {
1970              $origins = static::VALID_ORIGINS;
1971          }
1972  
1973          if ( is_string( $types ) ) {
1974              // Dispatch error and map old arguments to new ones.
1975              _deprecated_argument( __FUNCTION__, '5.9.0' );
1976              if ( 'block_styles' === $types ) {
1977                  $types = array( 'styles', 'presets' );
1978              } elseif ( 'css_variables' === $types ) {
1979                  $types = array( 'variables' );
1980              } else {
1981                  $types = array( 'variables', 'styles', 'presets' );
1982              }
1983          }
1984  
1985          $blocks_metadata = static::get_blocks_metadata();
1986          $style_nodes     = static::get_style_nodes( $this->theme_json, $blocks_metadata, $options );
1987          $setting_nodes   = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
1988  
1989          $root_style_key    = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $style_nodes, 'selector' ), true );
1990          $root_settings_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $setting_nodes, 'selector' ), true );
1991  
1992          if ( ! empty( $options['scope'] ) ) {
1993              foreach ( $setting_nodes as &$node ) {
1994                  $node['selector'] = static::scope_selector( $options['scope'], $node['selector'] );
1995              }
1996              foreach ( $style_nodes as &$node ) {
1997                  $node = static::scope_style_node_selectors( $options['scope'], $node );
1998              }
1999              unset( $node );
2000          }
2001  
2002          if ( ! empty( $options['root_selector'] ) ) {
2003              if ( false !== $root_settings_key ) {
2004                  $setting_nodes[ $root_settings_key ]['selector'] = $options['root_selector'];
2005              }
2006              if ( false !== $root_style_key ) {
2007                  $style_nodes[ $root_style_key ]['selector'] = $options['root_selector'];
2008              }
2009          }
2010  
2011          $stylesheet = '';
2012  
2013          if ( in_array( 'variables', $types, true ) ) {
2014              $stylesheet .= $this->get_css_variables( $setting_nodes, $origins );
2015          }
2016  
2017          if ( in_array( 'styles', $types, true ) ) {
2018              if ( false !== $root_style_key && empty( $options['skip_root_layout_styles'] ) ) {
2019                  $stylesheet .= $this->get_root_layout_rules( $style_nodes[ $root_style_key ]['selector'], $style_nodes[ $root_style_key ], $options );
2020              }
2021              $stylesheet .= $this->get_block_classes( $style_nodes );
2022          }
2023  
2024          if ( in_array( 'presets', $types, true ) ) {
2025              $stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
2026          }
2027  
2028          // Load the custom CSS last so it has the highest specificity.
2029          if ( in_array( 'custom-css', $types, true ) ) {
2030              // Add the global styles root CSS.
2031              $stylesheet .= _wp_array_get( $this->theme_json, array( 'styles', 'css' ) );
2032          }
2033  
2034          return $stylesheet;
2035      }
2036  
2037      /**
2038       * Processes the CSS, to apply nesting.
2039       *
2040       * @since 6.2.0
2041       * @since 6.6.0 Enforced 0-1-0 specificity for block custom CSS selectors.
2042       * @since 7.0.0 Made public for use in custom-css block support.
2043       *
2044       * @param string $css      The CSS to process.
2045       * @param string $selector The selector to nest.
2046       * @return string The processed CSS.
2047       */
2048  	public static function process_blocks_custom_css( $css, $selector ) {
2049          $processed_css = '';
2050  
2051          if ( empty( $css ) ) {
2052              return $processed_css;
2053          }
2054  
2055          // Split CSS nested rules.
2056          $parts = explode( '&', $css );
2057          foreach ( $parts as $part ) {
2058              if ( empty( $part ) ) {
2059                  continue;
2060              }
2061              $is_root_css = ( ! str_contains( $part, '{' ) );
2062              if ( $is_root_css ) {
2063                  // If the part doesn't contain braces, it applies to the root level.
2064                  $processed_css .= ':root :where(' . trim( $selector ) . '){' . trim( $part ) . '}';
2065              } else {
2066                  // If the part contains braces, it's a nested CSS rule.
2067                  $part = explode( '{', str_replace( '}', '', $part ) );
2068                  if ( count( $part ) !== 2 ) {
2069                      continue;
2070                  }
2071                  $nested_selector = $part[0];
2072                  $css_value       = $part[1];
2073  
2074                  /*
2075                   * Handle pseudo elements such as ::before, ::after etc. Regex will also
2076                   * capture any leading combinator such as >, +, or ~, as well as spaces.
2077                   * This allows pseudo elements as descendants e.g. `.parent ::before`.
2078                   */
2079                  $matches            = array();
2080                  $has_pseudo_element = preg_match( '/([>+~\s]*::[a-zA-Z-]+)/', $nested_selector, $matches );
2081                  $pseudo_part        = $has_pseudo_element ? $matches[1] : '';
2082                  $nested_selector    = $has_pseudo_element ? str_replace( $pseudo_part, '', $nested_selector ) : $nested_selector;
2083  
2084                  // Finalize selector and re-append pseudo element if required.
2085                  $part_selector  = str_starts_with( $nested_selector, ' ' )
2086                      ? static::scope_selector( $selector, $nested_selector )
2087                      : static::append_to_selector( $selector, $nested_selector );
2088                  $final_selector = ":root :where($part_selector)$pseudo_part";
2089  
2090                  $processed_css .= $final_selector . '{' . trim( $css_value ) . '}';
2091              }
2092          }
2093          return $processed_css;
2094      }
2095  
2096      /**
2097       * Returns the global styles custom CSS.
2098       *
2099       * @since 6.2.0
2100       * @deprecated 6.7.0 Use {@see 'get_stylesheet'} instead.
2101       *
2102       * @return string The global styles custom CSS.
2103       */
2104  	public function get_custom_css() {
2105          _deprecated_function( __METHOD__, '6.7.0', 'get_stylesheet' );
2106          // Add the global styles root CSS.
2107          $stylesheet = $this->theme_json['styles']['css'] ?? '';
2108  
2109          // Add the global styles block CSS.
2110          if ( isset( $this->theme_json['styles']['blocks'] ) ) {
2111              foreach ( $this->theme_json['styles']['blocks'] as $name => $node ) {
2112                  $custom_block_css = $this->theme_json['styles']['blocks'][ $name ]['css'] ?? null;
2113                  if ( $custom_block_css ) {
2114                      $selector    = static::$blocks_metadata[ $name ]['selector'];
2115                      $stylesheet .= $this->process_blocks_custom_css( $custom_block_css, $selector );
2116                  }
2117              }
2118          }
2119  
2120          return $stylesheet;
2121      }
2122  
2123      /**
2124       * Returns the page templates of the active theme.
2125       *
2126       * @since 5.9.0
2127       *
2128       * @return array
2129       */
2130  	public function get_custom_templates() {
2131          $custom_templates = array();
2132          if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) {
2133              return $custom_templates;
2134          }
2135  
2136          foreach ( $this->theme_json['customTemplates'] as $item ) {
2137              if ( isset( $item['name'] ) ) {
2138                  $custom_templates[ $item['name'] ] = array(
2139                      'title'     => $item['title'] ?? '',
2140                      'postTypes' => $item['postTypes'] ?? array( 'page' ),
2141                  );
2142              }
2143          }
2144          return $custom_templates;
2145      }
2146  
2147      /**
2148       * Returns the template part data of active theme.
2149       *
2150       * @since 5.9.0
2151       *
2152       * @return array
2153       */
2154  	public function get_template_parts() {
2155          $template_parts = array();
2156          if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) {
2157              return $template_parts;
2158          }
2159  
2160          foreach ( $this->theme_json['templateParts'] as $item ) {
2161              if ( isset( $item['name'] ) ) {
2162                  $template_parts[ $item['name'] ] = array(
2163                      'title' => $item['title'] ?? '',
2164                      'area'  => $item['area'] ?? '',
2165                  );
2166              }
2167          }
2168          return $template_parts;
2169      }
2170  
2171      /**
2172       * Converts each style section into a list of rulesets
2173       * containing the block styles to be appended to the stylesheet.
2174       *
2175       * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
2176       *
2177       * For each section this creates a new ruleset such as:
2178       *
2179       *   block-selector {
2180       *     style-property-one: value;
2181       *   }
2182       *
2183       * @since 5.8.0 As `get_block_styles()`.
2184       * @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()`
2185       *              and no longer returns preset classes.
2186       *              Removed the `$setting_nodes` parameter.
2187       * @since 6.1.0 Moved most internal logic to `get_styles_for_block()`.
2188       *
2189       * @param array $style_nodes Nodes with styles.
2190       * @return string The new stylesheet.
2191       */
2192  	protected function get_block_classes( $style_nodes ) {
2193          $block_rules = '';
2194  
2195          foreach ( $style_nodes as $metadata ) {
2196              if ( null === $metadata['selector'] ) {
2197                  continue;
2198              }
2199              $block_rules .= static::get_styles_for_block( $metadata );
2200          }
2201  
2202          return $block_rules;
2203      }
2204  
2205      /**
2206       * Gets the CSS layout rules for a particular block from theme.json layout definitions.
2207       *
2208       * @since 6.1.0
2209       * @since 6.3.0 Reduced specificity for layout margin rules.
2210       * @since 6.5.1 Only output rules referencing content and wide sizes when values exist.
2211       * @since 6.5.3 Add types parameter to check if only base layout styles are needed.
2212       * @since 6.6.0 Updated layout style specificity to be compatible with overall 0-1-0 specificity in global styles.
2213       * @since 7.0.0 Replaced `$types` parameter with `$options` array; base layout styles controlled via `base_layout_styles` option.
2214       *
2215       * @param array $block_metadata Metadata about the block to get styles for.
2216       * @param array $options        Optional. An array of options for now used for internal purposes only.
2217       * @return string Layout styles for the block.
2218       */
2219  	protected function get_layout_styles( $block_metadata, $options = array() ) {
2220          $block_rules = '';
2221          $block_type  = null;
2222  
2223          // Skip outputting layout styles if explicitly disabled.
2224          if ( current_theme_supports( 'disable-layout-styles' ) ) {
2225              return $block_rules;
2226          }
2227  
2228          if ( isset( $block_metadata['name'] ) ) {
2229              $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] );
2230              if ( ! block_has_support( $block_type, 'layout', false ) && ! block_has_support( $block_type, '__experimentalLayout', false ) ) {
2231                  return $block_rules;
2232              }
2233          }
2234  
2235          $selector                 = $block_metadata['selector'] ?? '';
2236          $has_block_gap_support    = isset( $this->theme_json['settings']['spacing']['blockGap'] );
2237          $has_fallback_gap_support = ! $has_block_gap_support; // This setting isn't useful yet: it exists as a placeholder for a future explicit fallback gap styles support.
2238          $node                     = $options['node'] ?? _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
2239          $layout_definitions       = wp_get_layout_definitions();
2240          $layout_selector_pattern  = '/^[a-zA-Z0-9\-\.\,\ *+>:\(\)]*$/'; // Allow alphanumeric classnames, spaces, wildcard, sibling, child combinator and pseudo class selectors.
2241  
2242          /*
2243           * Gap styles will only be output if the theme has block gap support, or supports a fallback gap.
2244           * Default layout gap styles will be skipped for themes that do not explicitly opt-in to blockGap with a `true` or `false` value.
2245           */
2246          if ( $has_block_gap_support || $has_fallback_gap_support ) {
2247              $block_gap_value = null;
2248              // Use a fallback gap value if block gap support is not available.
2249              if ( ! $has_block_gap_support ) {
2250                  $block_gap_value = static::ROOT_BLOCK_SELECTOR === $selector ? '0.5em' : null;
2251                  if ( ! empty( $block_type ) ) {
2252                      $block_gap_value = $block_type->supports['spacing']['blockGap']['__experimentalDefault'] ?? null;
2253                  }
2254              } else {
2255                  $block_gap_value = static::get_property_value( $node, array( 'spacing', 'blockGap' ) );
2256              }
2257  
2258              // Support split row / column values and concatenate to a shorthand value.
2259              if ( is_array( $block_gap_value ) ) {
2260                  if ( isset( $block_gap_value['top'] ) && isset( $block_gap_value['left'] ) ) {
2261                      $gap_row         = static::get_property_value( $node, array( 'spacing', 'blockGap', 'top' ) );
2262                      $gap_column      = static::get_property_value( $node, array( 'spacing', 'blockGap', 'left' ) );
2263                      $block_gap_value = $gap_row === $gap_column ? $gap_row : $gap_row . ' ' . $gap_column;
2264                  } else {
2265                      // Skip outputting gap value if not all sides are provided.
2266                      $block_gap_value = null;
2267                  }
2268              }
2269  
2270              // If the block should have custom gap, add the gap styles.
2271              if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) {
2272                  foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
2273                      // Allow outputting fallback gap styles for flex and grid layout types when block gap support isn't available.
2274                      if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key && 'grid' !== $layout_definition_key ) {
2275                          continue;
2276                      }
2277  
2278                      $class_name    = $layout_definition['className'] ?? false;
2279                      $spacing_rules = $layout_definition['spacingStyles'] ?? array();
2280  
2281                      if (
2282                          ! empty( $class_name ) &&
2283                          ! empty( $spacing_rules )
2284                      ) {
2285                          foreach ( $spacing_rules as $spacing_rule ) {
2286                              $declarations = array();
2287                              if (
2288                                  isset( $spacing_rule['selector'] ) &&
2289                                  preg_match( $layout_selector_pattern, $spacing_rule['selector'] ) &&
2290                                  ! empty( $spacing_rule['rules'] )
2291                              ) {
2292                                  // Iterate over each of the styling rules and substitute non-string values such as `null` with the real `blockGap` value.
2293                                  foreach ( $spacing_rule['rules'] as $css_property => $css_value ) {
2294                                      $current_css_value = is_string( $css_value ) ? $css_value : $block_gap_value;
2295                                      if ( static::is_safe_css_declaration( $css_property, $current_css_value ) ) {
2296                                          $declarations[] = array(
2297                                              'name'  => $css_property,
2298                                              'value' => $current_css_value,
2299                                          );
2300                                      }
2301                                  }
2302  
2303                                  if ( ! $has_block_gap_support ) {
2304                                      // For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles.
2305                                      $format          = static::ROOT_BLOCK_SELECTOR === $selector ? ':where(.%2$s%3$s)' : ':where(%1$s.%2$s%3$s)';
2306                                      $layout_selector = sprintf(
2307                                          $format,
2308                                          $selector,
2309                                          $class_name,
2310                                          $spacing_rule['selector']
2311                                      );
2312                                  } else {
2313                                      $format          = static::ROOT_BLOCK_SELECTOR === $selector ? ':root :where(.%2$s)%3$s' : ':root :where(%1$s-%2$s)%3$s';
2314                                      $layout_selector = sprintf(
2315                                          $format,
2316                                          $selector,
2317                                          $class_name,
2318                                          $spacing_rule['selector']
2319                                      );
2320                                  }
2321                                  $block_rules .= static::to_ruleset( $layout_selector, $declarations );
2322                              }
2323                          }
2324                      }
2325                  }
2326              }
2327          }
2328  
2329          // Output base styles.
2330          if (
2331              static::ROOT_BLOCK_SELECTOR === $selector
2332          ) {
2333              $valid_display_modes = array( 'block', 'flex', 'grid' );
2334              foreach ( $layout_definitions as $layout_definition ) {
2335                  $class_name       = $layout_definition['className'] ?? false;
2336                  $base_style_rules = $layout_definition['baseStyles'] ?? array();
2337  
2338                  if (
2339                      ! empty( $class_name ) &&
2340                      is_array( $base_style_rules )
2341                  ) {
2342                      // Output display mode. This requires special handling as `display` is not exposed in `safe_style_css_filter`.
2343                      if (
2344                          ! empty( $layout_definition['displayMode'] ) &&
2345                          is_string( $layout_definition['displayMode'] ) &&
2346                          in_array( $layout_definition['displayMode'], $valid_display_modes, true )
2347                      ) {
2348                          $layout_selector = sprintf(
2349                              '%s .%s',
2350                              $selector,
2351                              $class_name
2352                          );
2353                          $block_rules    .= static::to_ruleset(
2354                              $layout_selector,
2355                              array(
2356                                  array(
2357                                      'name'  => 'display',
2358                                      'value' => $layout_definition['displayMode'],
2359                                  ),
2360                              )
2361                          );
2362                      }
2363  
2364                      foreach ( $base_style_rules as $base_style_rule ) {
2365                          $declarations = array();
2366  
2367                          // Skip outputting base styles for flow and constrained layout types when base_layout_styles is enabled.
2368                          // These themes don't use .wp-site-blocks wrapper, so these layout-specific alignment styles aren't needed.
2369                          if ( ! empty( $options['base_layout_styles'] ) && ( 'default' === $layout_definition['name'] || 'constrained' === $layout_definition['name'] ) ) {
2370                              continue;
2371                          }
2372  
2373                          if (
2374                              isset( $base_style_rule['selector'] ) &&
2375                              preg_match( $layout_selector_pattern, $base_style_rule['selector'] ) &&
2376                              ! empty( $base_style_rule['rules'] )
2377                          ) {
2378                              foreach ( $base_style_rule['rules'] as $css_property => $css_value ) {
2379                                  // Skip rules that reference content size or wide size if they are not defined in the theme.json.
2380                                  if (
2381                                      is_string( $css_value ) &&
2382                                      ( str_contains( $css_value, '--global--content-size' ) || str_contains( $css_value, '--global--wide-size' ) ) &&
2383                                      ! isset( $this->theme_json['settings']['layout']['contentSize'] ) &&
2384                                      ! isset( $this->theme_json['settings']['layout']['wideSize'] )
2385                                  ) {
2386                                      continue;
2387                                  }
2388  
2389                                  if ( static::is_safe_css_declaration( $css_property, $css_value ) ) {
2390                                      $declarations[] = array(
2391                                          'name'  => $css_property,
2392                                          'value' => $css_value,
2393                                      );
2394                                  }
2395                              }
2396  
2397                              $layout_selector = sprintf(
2398                                  '.%s%s',
2399                                  $class_name,
2400                                  $base_style_rule['selector']
2401                              );
2402                              $block_rules    .= static::to_ruleset( $layout_selector, $declarations );
2403                          }
2404                      }
2405                  }
2406              }
2407          }
2408  
2409          if ( ! empty( $options['media_query'] ) && ! empty( $block_rules ) ) {
2410              $block_rules = $options['media_query'] . '{' . $block_rules . '}';
2411          }
2412  
2413          return $block_rules;
2414      }
2415  
2416      /**
2417       * Creates new rulesets as classes for each preset value such as:
2418       *
2419       *   .has-value-color {
2420       *     color: value;
2421       *   }
2422       *
2423       *   .has-value-background-color {
2424       *     background-color: value;
2425       *   }
2426       *
2427       *   .has-value-font-size {
2428       *     font-size: value;
2429       *   }
2430       *
2431       *   .has-value-gradient-background {
2432       *     background: value;
2433       *   }
2434       *
2435       *   :where(p).has-value-gradient-background {
2436       *     background: value;
2437       *   }
2438       *
2439       * @since 5.9.0
2440       *
2441       * @param array    $setting_nodes Nodes with settings.
2442       * @param string[] $origins       List of origins to process presets from.
2443       * @return string The new stylesheet.
2444       */
2445  	protected function get_preset_classes( $setting_nodes, $origins ) {
2446          $preset_rules = '';
2447  
2448          foreach ( $setting_nodes as $metadata ) {
2449              if ( null === $metadata['selector'] ) {
2450                  continue;
2451              }
2452  
2453              $selector      = $metadata['selector'];
2454              $node          = _wp_array_get( $this->theme_json, $metadata['path'], array() );
2455              $preset_rules .= static::compute_preset_classes( $node, $selector, $origins );
2456          }
2457  
2458          return $preset_rules;
2459      }
2460  
2461      /**
2462       * Converts each styles section into a list of rulesets
2463       * to be appended to the stylesheet.
2464       * These rulesets contain all the css variables (custom variables and preset variables).
2465       *
2466       * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
2467       *
2468       * For each section this creates a new ruleset such as:
2469       *
2470       *     block-selector {
2471       *       --wp--preset--category--slug: value;
2472       *       --wp--custom--variable: value;
2473       *     }
2474       *
2475       * @since 5.8.0
2476       * @since 5.9.0 Added the `$origins` parameter.
2477       *
2478       * @param array    $nodes   Nodes with settings.
2479       * @param string[] $origins List of origins to process.
2480       * @return string The new stylesheet.
2481       */
2482  	protected function get_css_variables( $nodes, $origins ) {
2483          $stylesheet = '';
2484          foreach ( $nodes as $metadata ) {
2485              if ( null === $metadata['selector'] ) {
2486                  continue;
2487              }
2488  
2489              $selector          = $metadata['selector'];
2490              $feature_selectors = $metadata['selectors'] ?? array();
2491              $node              = _wp_array_get( $this->theme_json, $metadata['path'], array() );
2492  
2493              /*
2494               * Group preset declarations by selector. Blocks that define
2495               * feature-level selectors need their preset CSS variables
2496               * output under that feature selector instead of the block's
2497               * root selector.
2498               */
2499              $vars_by_selector              = array();
2500              $vars_by_selector[ $selector ] = array();
2501  
2502              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2503                  if ( empty( $preset_metadata['css_vars'] ) ) {
2504                      continue;
2505                  }
2506  
2507                  $values_by_slug = static::get_settings_values_by_slug( $node, $preset_metadata, $origins );
2508                  if ( empty( $values_by_slug ) ) {
2509                      continue;
2510                  }
2511  
2512                  $target = static::get_feature_selector( $feature_selectors, $preset_metadata['path'][0], $selector );
2513  
2514                  if ( ! isset( $vars_by_selector[ $target ] ) ) {
2515                      $vars_by_selector[ $target ] = array();
2516                  }
2517  
2518                  foreach ( $values_by_slug as $slug => $value ) {
2519                      $vars_by_selector[ $target ][] = array(
2520                          'name'  => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
2521                          'value' => $value,
2522                      );
2523                  }
2524              }
2525  
2526              // Theme vars always use the block's default selector.
2527              foreach ( static::compute_theme_vars( $node ) as $theme_var ) {
2528                  $vars_by_selector[ $selector ][] = $theme_var;
2529              }
2530  
2531              foreach ( $vars_by_selector as $rule_selector => $declarations ) {
2532                  $stylesheet .= static::to_ruleset( $rule_selector, $declarations );
2533              }
2534          }
2535  
2536          return $stylesheet;
2537      }
2538  
2539      /**
2540       * Returns the appropriate selector for a block support feature's
2541       * preset CSS variables.
2542       *
2543       * If the block defines a feature-level selector (as a string or an
2544       * object with a `root` key), that selector is returned. Otherwise,
2545       * the block's default selector is used.
2546       *
2547       * @since 7.1.0
2548       *
2549       * @param array<string, string|array<string, string>> $feature_selectors The block's feature selectors map.
2550       * @param string                                      $feature_key       The feature to look up (e.g. 'dimensions').
2551       * @param string                                      $default_selector  Fallback selector.
2552       * @return string The resolved selector.
2553       */
2554  	private static function get_feature_selector( array $feature_selectors, string $feature_key, string $default_selector ): string {
2555          if ( ! isset( $feature_selectors[ $feature_key ] ) ) {
2556              return $default_selector;
2557          }
2558  
2559          $feature = $feature_selectors[ $feature_key ];
2560  
2561          if ( is_string( $feature ) ) {
2562              return $feature;
2563          }
2564  
2565          if ( isset( $feature['root'] ) && is_string( $feature['root'] ) ) {
2566              return $feature['root'];
2567          }
2568  
2569          return $default_selector;
2570      }
2571  
2572      /**
2573       * Given a selector and a declaration list,
2574       * creates the corresponding ruleset.
2575       *
2576       * @since 5.8.0
2577       * @since 7.1.0 Skip declarations whose value is not a plain string (booleans, arrays, objects, etc.).
2578       *
2579       * @param string $selector     CSS selector.
2580       * @param array  $declarations List of declarations.
2581       * @return string The resulting CSS ruleset.
2582       */
2583  	protected static function to_ruleset( $selector, $declarations ) {
2584          if ( empty( $declarations ) ) {
2585              return '';
2586          }
2587  
2588          $declaration_block = array_reduce(
2589              $declarations,
2590              static function ( $carry, $element ) {
2591                  $value = $element['value'];
2592  
2593                  if ( is_numeric( $value ) ) {
2594                      $value = (string) $value;
2595                  }
2596  
2597                  if ( ! is_string( $value ) ) {
2598                      return $carry;
2599                  }
2600  
2601                  return $carry .= $element['name'] . ': ' . $value . ';';
2602              },
2603              ''
2604          );
2605  
2606          return $selector . '{' . $declaration_block . '}';
2607      }
2608  
2609      /**
2610       * Given a settings array, returns the generated rulesets
2611       * for the preset classes.
2612       *
2613       * @since 5.8.0
2614       * @since 5.9.0 Added the `$origins` parameter.
2615       * @since 6.6.0 Added check for root CSS properties selector.
2616       * @since 7.1.0 Wraps block-level preset classes in `:where()` to match root-level specificity.
2617       *
2618       * @param array    $settings Settings to process.
2619       * @param string   $selector Selector wrapping the classes.
2620       * @param string[] $origins  List of origins to process.
2621       * @return string The result of processing the presets.
2622       */
2623  	protected static function compute_preset_classes( $settings, $selector, $origins ) {
2624          if ( static::ROOT_BLOCK_SELECTOR === $selector || static::ROOT_CSS_PROPERTIES_SELECTOR === $selector ) {
2625              /*
2626               * Classes at the global level do not need any CSS prefixed,
2627               * and we don't want to increase its specificity.
2628               */
2629              $selector = '';
2630          }
2631  
2632          $stylesheet = '';
2633          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2634              if ( empty( $preset_metadata['classes'] ) ) {
2635                  continue;
2636              }
2637              $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins );
2638              foreach ( $preset_metadata['classes'] as $class => $property ) {
2639                  foreach ( $slugs as $slug ) {
2640                      $css_var    = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
2641                      $class_name = static::replace_slug_in_string( $class, $slug );
2642  
2643                      /*
2644                       * $selector is often empty (root-level presets), in which case the
2645                       * bare class is used. For block-level presets the block selector is
2646                       * wrapped in `:where()` so the class keeps the same 0-1-0 specificity
2647                       * as a root-level preset. Without this, block-level palette rules
2648                       * (e.g. `p.has-x-color`) out-rank equally-important rules that also
2649                       * target the same property at 0-1-0, such as per-instance responsive
2650                       * state styles.
2651                       */
2652                      $new_selector = '' === $selector ? $class_name : ':where(' . $selector . ')' . $class_name;
2653                      $stylesheet  .= static::to_ruleset(
2654                          $new_selector,
2655                          array(
2656                              array(
2657                                  'name'  => $property,
2658                                  'value' => 'var(' . $css_var . ') !important',
2659                              ),
2660                          )
2661                      );
2662                  }
2663              }
2664          }
2665  
2666          return $stylesheet;
2667      }
2668  
2669      /**
2670       * Function that scopes a selector with another one. This works a bit like
2671       * SCSS nesting except the `&` operator isn't supported.
2672       *
2673       * <code>
2674       * $scope = '.a, .b .c';
2675       * $selector = '> .x, .y';
2676       * $merged = scope_selector( $scope, $selector );
2677       * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
2678       * </code>
2679       *
2680       * @since 5.9.0
2681       * @since 6.6.0 Added early return if missing scope or selector.
2682       *
2683       * @param string $scope    Selector to scope to.
2684       * @param string $selector Original selector.
2685       * @return string Scoped selector.
2686       */
2687  	public static function scope_selector( $scope, $selector ) {
2688          if ( ! $scope || ! $selector ) {
2689              return $selector;
2690          }
2691  
2692          $scopes    = static::split_selector_list( $scope );
2693          $selectors = static::split_selector_list( $selector );
2694  
2695          $selectors_scoped = array();
2696          foreach ( $scopes as $outer ) {
2697              foreach ( $selectors as $inner ) {
2698                  if ( ! empty( $outer ) && ! empty( $inner ) ) {
2699                      $selectors_scoped[] = $outer . ' ' . $inner;
2700                  } elseif ( empty( $outer ) ) {
2701                      $selectors_scoped[] = $inner;
2702                  } elseif ( empty( $inner ) ) {
2703                      $selectors_scoped[] = $outer;
2704                  }
2705              }
2706          }
2707  
2708          $result = implode( ', ', $selectors_scoped );
2709          return $result;
2710      }
2711  
2712      /**
2713       * Scopes the selectors for a given style node.
2714       *
2715       * This includes the primary selector, i.e. `$node['selector']`, as well as any custom
2716       * selectors for features and subfeatures, e.g. `$node['selectors']['border']` etc.
2717       *
2718       * @since 6.6.0
2719       *
2720       * @param string $scope Selector to scope to.
2721       * @param array  $node  Style node with selectors to scope.
2722       * @return array Node with updated selectors.
2723       */
2724  	protected static function scope_style_node_selectors( $scope, $node ) {
2725          $node['selector'] = static::scope_selector( $scope, $node['selector'] );
2726  
2727          if ( empty( $node['selectors'] ) ) {
2728              return $node;
2729          }
2730  
2731          foreach ( $node['selectors'] as $feature => $selector ) {
2732              if ( is_string( $selector ) ) {
2733                  $node['selectors'][ $feature ] = static::scope_selector( $scope, $selector );
2734              }
2735              if ( is_array( $selector ) ) {
2736                  foreach ( $selector as $subfeature => $subfeature_selector ) {
2737                      $node['selectors'][ $feature ][ $subfeature ] = static::scope_selector( $scope, $subfeature_selector );
2738                  }
2739              }
2740          }
2741  
2742          return $node;
2743      }
2744  
2745      /**
2746       * Gets preset values keyed by slugs based on settings and metadata.
2747       *
2748       * <code>
2749       * $settings = array(
2750       *     'typography' => array(
2751       *         'fontFamilies' => array(
2752       *             array(
2753       *                 'slug'       => 'sansSerif',
2754       *                 'fontFamily' => '"Helvetica Neue", sans-serif',
2755       *             ),
2756       *             array(
2757       *                 'slug'   => 'serif',
2758       *                 'colors' => 'Georgia, serif',
2759       *             )
2760       *         ),
2761       *     ),
2762       * );
2763       * $meta = array(
2764       *    'path'      => array( 'typography', 'fontFamilies' ),
2765       *    'value_key' => 'fontFamily',
2766       * );
2767       * $values_by_slug = get_settings_values_by_slug();
2768       * // $values_by_slug === array(
2769       * //   'sans-serif' => '"Helvetica Neue", sans-serif',
2770       * //   'serif'      => 'Georgia, serif',
2771       * // );
2772       * </code>
2773       *
2774       * @since 5.9.0
2775       * @since 6.6.0 Passing $settings to the callbacks defined in static::PRESETS_METADATA.
2776       *
2777       * @param array    $settings        Settings to process.
2778       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2779       * @param string[] $origins         List of origins to process.
2780       * @return array Array of presets where each key is a slug and each value is the preset value.
2781       */
2782  	protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
2783          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2784  
2785          $result = array();
2786          foreach ( $origins as $origin ) {
2787              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2788                  continue;
2789              }
2790              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2791                  $slug = _wp_to_kebab_case( $preset['slug'] );
2792  
2793                  $value = '';
2794                  if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
2795                      $value_key = $preset_metadata['value_key'];
2796                      $value     = $preset[ $value_key ];
2797                  } elseif (
2798                      isset( $preset_metadata['value_func'] ) &&
2799                      is_callable( $preset_metadata['value_func'] )
2800                  ) {
2801                      $value_func = $preset_metadata['value_func'];
2802                      $value      = call_user_func( $value_func, $preset, $settings );
2803                  } else {
2804                      // If we don't have a value, then don't add it to the result.
2805                      continue;
2806                  }
2807  
2808                  $result[ $slug ] = $value;
2809              }
2810          }
2811          return $result;
2812      }
2813  
2814      /**
2815       * Similar to get_settings_values_by_slug, but doesn't compute the value.
2816       *
2817       * @since 5.9.0
2818       *
2819       * @param array    $settings        Settings to process.
2820       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2821       * @param string[] $origins         List of origins to process.
2822       * @return array Array of presets where the key and value are both the slug.
2823       */
2824  	protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) {
2825          if ( null === $origins ) {
2826              $origins = static::VALID_ORIGINS;
2827          }
2828  
2829          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2830  
2831          $result = array();
2832          foreach ( $origins as $origin ) {
2833              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2834                  continue;
2835              }
2836              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2837                  $slug = _wp_to_kebab_case( $preset['slug'] );
2838  
2839                  // Use the array as a set so we don't get duplicates.
2840                  $result[ $slug ] = $slug;
2841              }
2842          }
2843          return $result;
2844      }
2845  
2846      /**
2847       * Transforms a slug into a CSS Custom Property.
2848       *
2849       * @since 5.9.0
2850       *
2851       * @param string $input String to replace.
2852       * @param string $slug  The slug value to use to generate the custom property.
2853       * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`.
2854       */
2855  	protected static function replace_slug_in_string( $input, $slug ) {
2856          return strtr( $input, array( '$slug' => $slug ) );
2857      }
2858  
2859      /**
2860       * Given the block settings, extracts the CSS Custom Properties
2861       * for the presets and adds them to the $declarations array
2862       * following the format:
2863       *
2864       *     array(
2865       *       'name'  => 'property_name',
2866       *       'value' => 'property_value,
2867       *     )
2868       *
2869       * @since 5.8.0
2870       * @since 5.9.0 Added the `$origins` parameter.
2871       *
2872       * @param array    $settings Settings to process.
2873       * @param string[] $origins  List of origins to process.
2874       * @return array The modified $declarations.
2875       */
2876  	protected static function compute_preset_vars( $settings, $origins ) {
2877          $declarations = array();
2878          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2879              if ( empty( $preset_metadata['css_vars'] ) ) {
2880                  continue;
2881              }
2882              $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins );
2883              foreach ( $values_by_slug as $slug => $value ) {
2884                  $declarations[] = array(
2885                      'name'  => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
2886                      'value' => $value,
2887                  );
2888              }
2889          }
2890  
2891          return $declarations;
2892      }
2893  
2894      /**
2895       * Given an array of settings, extracts the CSS Custom Properties
2896       * for the custom values and adds them to the $declarations
2897       * array following the format:
2898       *
2899       *     array(
2900       *       'name'  => 'property_name',
2901       *       'value' => 'property_value,
2902       *     )
2903       *
2904       * @since 5.8.0
2905       *
2906       * @param array $settings Settings to process.
2907       * @return array The modified $declarations.
2908       */
2909  	protected static function compute_theme_vars( $settings ) {
2910          $declarations  = array();
2911          $custom_values = $settings['custom'] ?? array();
2912          $css_vars      = static::flatten_tree( $custom_values );
2913          foreach ( $css_vars as $key => $value ) {
2914              $declarations[] = array(
2915                  'name'  => '--wp--custom--' . $key,
2916                  'value' => $value,
2917              );
2918          }
2919  
2920          return $declarations;
2921      }
2922  
2923      /**
2924       * Given a tree, it creates a flattened one
2925       * by merging the keys and binding the leaf values
2926       * to the new keys.
2927       *
2928       * It also transforms camelCase names into kebab-case
2929       * and substitutes '/' by '-'.
2930       *
2931       * This is thought to be useful to generate
2932       * CSS Custom Properties from a tree,
2933       * although there's nothing in the implementation
2934       * of this function that requires that format.
2935       *
2936       * For example, assuming the given prefix is '--wp'
2937       * and the token is '--', for this input tree:
2938       *
2939       *     {
2940       *       'some/property': 'value',
2941       *       'nestedProperty': {
2942       *         'sub-property': 'value'
2943       *       }
2944       *     }
2945       *
2946       * it'll return this output:
2947       *
2948       *     {
2949       *       '--wp--some-property': 'value',
2950       *       '--wp--nested-property--sub-property': 'value'
2951       *     }
2952       *
2953       * @since 5.8.0
2954       *
2955       * @param array  $tree   Input tree to process.
2956       * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string.
2957       * @param string $token  Optional. Token to use between levels. Default '--'.
2958       * @return array The flattened tree.
2959       */
2960  	protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
2961          $result = array();
2962          foreach ( $tree as $property => $value ) {
2963              $new_key = $prefix . str_replace(
2964                  '/',
2965                  '-',
2966                  strtolower( _wp_to_kebab_case( $property ) )
2967              );
2968  
2969              if ( is_array( $value ) ) {
2970                  $new_prefix        = $new_key . $token;
2971                  $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token );
2972                  foreach ( $flattened_subtree as $subtree_key => $subtree_value ) {
2973                      $result[ $subtree_key ] = $subtree_value;
2974                  }
2975              } else {
2976                  $result[ $new_key ] = $value;
2977              }
2978          }
2979          return $result;
2980      }
2981  
2982      /**
2983       * Given a styles array, it extracts the style properties
2984       * and adds them to the $declarations array following the format:
2985       *
2986       *     array(
2987       *       'name'  => 'property_name',
2988       *       'value' => 'property_value',
2989       *     )
2990       *
2991       * @since 5.8.0
2992       * @since 5.9.0 Added the `$settings` and `$properties` parameters.
2993       * @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters.
2994       * @since 6.5.0 Output a `min-height: unset` rule when `aspect-ratio` is set.
2995       * @since 6.6.0 Pass current theme JSON settings to wp_get_typography_font_size_value(), and process background properties.
2996       * @since 6.7.0 `ref` resolution of background properties, and assigning custom default values.
2997       *
2998       * @param array   $styles Styles to process.
2999       * @param array   $settings Theme settings.
3000       * @param array   $properties Properties metadata.
3001       * @param array   $theme_json Theme JSON array.
3002       * @param string  $selector The style block selector.
3003       * @param boolean $use_root_padding Whether to add custom properties at root level.
3004       * @return array Returns the modified $declarations.
3005       */
3006  	protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) {
3007          if ( empty( $styles ) ) {
3008              return array();
3009          }
3010  
3011          if ( null === $properties ) {
3012              $properties = static::PROPERTIES_METADATA;
3013          }
3014          $declarations             = array();
3015          $root_variable_duplicates = array();
3016          $root_style_length        = strlen( '--wp--style--root--' );
3017  
3018          foreach ( $properties as $css_property => $value_path ) {
3019              if ( ! is_array( $value_path ) ) {
3020                  continue;
3021              }
3022  
3023              $is_root_style = str_starts_with( $css_property, '--wp--style--root--' );
3024              if ( $is_root_style && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) {
3025                  continue;
3026              }
3027  
3028              $value = static::get_property_value( $styles, $value_path, $theme_json );
3029  
3030              /*
3031               * Root-level padding styles don't currently support strings with CSS shorthand values.
3032               * This may change: https://github.com/WordPress/gutenberg/issues/40132.
3033               */
3034              if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) {
3035                  continue;
3036              }
3037  
3038              if ( $is_root_style && $use_root_padding ) {
3039                  $root_variable_duplicates[] = substr( $css_property, $root_style_length );
3040              }
3041  
3042              /*
3043               * Processes background image styles.
3044               * If the value is a URL, it will be converted to a CSS `url()` value.
3045               * For uploaded image (images with a database ID), apply size and position defaults,
3046               * equal to those applied in block supports in lib/background.php.
3047               */
3048              if ( 'background-image' === $css_property ) {
3049                  $background_image_input = array();
3050                  if ( ! empty( $value ) ) {
3051                      $background_image_input['backgroundImage'] = $value;
3052                  }
3053                  $gradient_value = $styles['background']['gradient'] ?? null;
3054                  if ( ! empty( $gradient_value ) ) {
3055                      $background_image_input['gradient'] = $gradient_value;
3056                  }
3057                  if ( ! empty( $background_image_input ) ) {
3058                      $background_styles = wp_style_engine_get_styles(
3059                          array( 'background' => $background_image_input )
3060                      );
3061                      $value             = $background_styles['declarations'][ $css_property ] ?? null;
3062                  }
3063              }
3064              if ( empty( $value ) && static::ROOT_BLOCK_SELECTOR !== $selector && ! empty( $styles['background']['backgroundImage']['id'] ) ) {
3065                  if ( 'background-size' === $css_property ) {
3066                      $value = 'cover';
3067                  }
3068                  // If the background size is set to `contain` and no position is set, set the position to `center`.
3069                  if ( 'background-position' === $css_property ) {
3070                      $background_size = $styles['background']['backgroundSize'] ?? null;
3071                      $value           = 'contain' === $background_size ? '50% 50%' : null;
3072                  }
3073              }
3074  
3075              // Skip if empty and not "0" or value represents array of longhand values.
3076              $has_missing_value = empty( $value ) && ! is_numeric( $value );
3077              if ( $has_missing_value || is_array( $value ) ) {
3078                  continue;
3079              }
3080  
3081              // Calculates fluid typography rules where available.
3082              if ( 'font-size' === $css_property ) {
3083                  /*
3084                   * wp_get_typography_font_size_value() will check
3085                   * if fluid typography has been activated and also
3086                   * whether the incoming value can be converted to a fluid value.
3087                   * Values that already have a clamp() function will not pass the test,
3088                   * and therefore the original $value will be returned.
3089                   * Pass the current theme_json settings to override any global settings.
3090                   */
3091                  $value = wp_get_typography_font_size_value( array( 'size' => $value ), $settings );
3092              }
3093  
3094              if ( 'aspect-ratio' === $css_property ) {
3095                  // For aspect ratio to work, other dimensions rules must be unset.
3096                  // This ensures that a fixed height does not override the aspect ratio.
3097                  $declarations[] = array(
3098                      'name'  => 'min-height',
3099                      'value' => 'unset',
3100                  );
3101              }
3102  
3103              $declarations[] = array(
3104                  'name'  => $css_property,
3105                  'value' => $value,
3106              );
3107          }
3108  
3109          // If a variable value is added to the root, the corresponding property should be removed.
3110          foreach ( $root_variable_duplicates as $duplicate ) {
3111              $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true );
3112              if ( is_numeric( $discard ) ) {
3113                  array_splice( $declarations, $discard, 1 );
3114              }
3115          }
3116  
3117          return $declarations;
3118      }
3119  
3120      /**
3121       * Returns the style property for the given path.
3122       *
3123       * It also converts references to a path to the value
3124       * stored at that location, e.g.
3125       * { "ref": "style.color.background" } => "#fff".
3126       *
3127       * @since 5.8.0
3128       * @since 5.9.0 Added support for values of array type, which are returned as is.
3129       * @since 6.1.0 Added the `$theme_json` parameter.
3130       * @since 6.3.0 It no longer converts the internal format "var:preset|color|secondary"
3131       *              to the standard form "--wp--preset--color--secondary".
3132       *              This is already done by the sanitize method,
3133       *              so every property will be in the standard form.
3134       * @since 6.7.0 Added support for background image refs.
3135       *
3136       * @param array $styles Styles subtree.
3137       * @param array $path   Which property to process.
3138       * @param array $theme_json Theme JSON array.
3139       * @return string|array Style property value.
3140       */
3141  	protected static function get_property_value( $styles, $path, $theme_json = null ) {
3142          $value = _wp_array_get( $styles, $path, '' );
3143  
3144          if ( '' === $value || null === $value ) {
3145              // No need to process the value further.
3146              return '';
3147          }
3148  
3149          /*
3150           * This converts references to a path to the value at that path
3151           * where the value is an array with a "ref" key, pointing to a path.
3152           * For example: { "ref": "style.color.background" } => "#fff".
3153           * In the case of backgroundImage, if both a ref and a URL are present in the value,
3154           * the URL takes precedence and the ref is ignored.
3155           */
3156          if ( is_array( $value ) && isset( $value['ref'] ) ) {
3157              $value_path = explode( '.', $value['ref'] );
3158              $ref_value  = _wp_array_get( $theme_json, $value_path );
3159              // Background Image refs can refer to a string or an array containing a URL string.
3160              $ref_value_url = $ref_value['url'] ?? null;
3161              // Only use the ref value if we find anything.
3162              if ( ! empty( $ref_value ) && ( is_string( $ref_value ) || is_string( $ref_value_url ) ) ) {
3163                  $value = $ref_value;
3164              }
3165  
3166              if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) {
3167                  $path_string      = json_encode( $path );
3168                  $ref_value_string = json_encode( $ref_value );
3169                  _doing_it_wrong(
3170                      'get_property_value',
3171                      sprintf(
3172                          /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */
3173                          __( 'Your %1$s file uses a dynamic value (%2$s) for the path at %3$s. However, the value at %3$s is also a dynamic value (pointing to %4$s) and pointing to another dynamic value is not supported. Please update %3$s to point directly to %4$s.' ),
3174                          'theme.json',
3175                          $ref_value_string,
3176                          $path_string,
3177                          $ref_value['ref']
3178                      ),
3179                      '6.1.0'
3180                  );
3181              }
3182          }
3183  
3184          return $value;
3185      }
3186  
3187      /**
3188       * Builds metadata for the setting nodes, which returns in the form of:
3189       *
3190       *     [
3191       *       [
3192       *         'path'     => ['path', 'to', 'some', 'node' ],
3193       *         'selector' => 'CSS selector for some node'
3194       *       ],
3195       *       [
3196       *         'path'     => [ 'path', 'to', 'other', 'node' ],
3197       *         'selector' => 'CSS selector for other node'
3198       *       ],
3199       *     ]
3200       *
3201       * @since 5.8.0
3202       *
3203       * @param array $theme_json The tree to extract setting nodes from.
3204       * @param array $selectors  List of selectors per block.
3205       * @return array An array of setting nodes metadata.
3206       */
3207  	protected static function get_setting_nodes( $theme_json, $selectors = array() ) {
3208          $nodes = array();
3209          if ( ! isset( $theme_json['settings'] ) ) {
3210              return $nodes;
3211          }
3212  
3213          // Top-level.
3214          $nodes[] = array(
3215              'path'     => array( 'settings' ),
3216              'selector' => static::ROOT_CSS_PROPERTIES_SELECTOR,
3217          );
3218  
3219          // Calculate paths for blocks.
3220          if ( ! isset( $theme_json['settings']['blocks'] ) ) {
3221              return $nodes;
3222          }
3223  
3224          foreach ( $theme_json['settings']['blocks'] as $name => $node ) {
3225              $selector = null;
3226              if ( isset( $selectors[ $name ]['selector'] ) ) {
3227                  $selector = $selectors[ $name ]['selector'];
3228              }
3229  
3230              $nodes[] = array(
3231                  'path'      => array( 'settings', 'blocks', $name ),
3232                  'selector'  => $selector,
3233                  'selectors' => $selectors[ $name ]['selectors'] ?? array(),
3234              );
3235          }
3236  
3237          return $nodes;
3238      }
3239  
3240      /**
3241       * Builds metadata for the style nodes, which returns in the form of:
3242       *
3243       *     [
3244       *       [
3245       *         'path'     => [ 'path', 'to', 'some', 'node' ],
3246       *         'selector' => 'CSS selector for some node',
3247       *         'duotone'  => 'CSS selector for duotone for some node'
3248       *       ],
3249       *       [
3250       *         'path'     => ['path', 'to', 'other', 'node' ],
3251       *         'selector' => 'CSS selector for other node',
3252       *         'duotone'  => null
3253       *       ],
3254       *     ]
3255       *
3256       * @since 5.8.0
3257       * @since 6.6.0 Added options array for modifying generated nodes.
3258       *
3259       * @param array $theme_json The tree to extract style nodes from.
3260       * @param array $selectors  List of selectors per block.
3261       * @param array $options {
3262       *     Optional. An array of options for now used for internal purposes only (may change without notice).
3263       *
3264       *     @type bool $include_block_style_variations Includes style nodes for block style variations. Default false.
3265       * }
3266       * @return array An array of style nodes metadata.
3267       */
3268  	protected static function get_style_nodes( $theme_json, $selectors = array(), $options = array() ) {
3269          $nodes = array();
3270          if ( ! isset( $theme_json['styles'] ) ) {
3271              return $nodes;
3272          }
3273  
3274          // Top-level.
3275          $nodes[] = array(
3276              'path'     => array( 'styles' ),
3277              'selector' => static::ROOT_BLOCK_SELECTOR,
3278          );
3279  
3280          if ( isset( $theme_json['styles']['elements'] ) ) {
3281              foreach ( self::ELEMENTS as $element => $selector ) {
3282                  if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) {
3283                      continue;
3284                  }
3285                  $nodes[] = array(
3286                      'path'     => array( 'styles', 'elements', $element ),
3287                      'selector' => static::ELEMENTS[ $element ],
3288                  );
3289  
3290                  // Handle any pseudo selectors for the element.
3291                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
3292                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
3293  
3294                          if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) {
3295                              $nodes[] = array(
3296                                  'path'     => array( 'styles', 'elements', $element ),
3297                                  'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ),
3298                              );
3299                          }
3300                      }
3301                  }
3302              }
3303          }
3304  
3305          // Blocks.
3306          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
3307              return $nodes;
3308          }
3309  
3310          $block_nodes = static::get_block_nodes( $theme_json, $selectors, $options );
3311          foreach ( $block_nodes as $block_node ) {
3312              $nodes[] = $block_node;
3313          }
3314  
3315          /**
3316           * Filters the list of style nodes with metadata.
3317           *
3318           * This allows for things like loading block CSS independently.
3319           *
3320           * @since 6.1.0
3321           *
3322           * @param array $nodes Style nodes with metadata.
3323           */
3324          return apply_filters( 'wp_theme_json_get_style_nodes', $nodes );
3325      }
3326  
3327      /**
3328       * A public helper to get the block nodes from a theme.json file.
3329       *
3330       * @since 6.1.0
3331       *
3332       * @return array The block nodes in theme.json.
3333       */
3334  	public function get_styles_block_nodes() {
3335          return static::get_block_nodes( $this->theme_json );
3336      }
3337  
3338      /**
3339       * Returns a filtered declarations array if there is a separator block with only a background
3340       * style defined in theme.json by adding a color attribute to reflect the changes in the front.
3341       *
3342       * @since 6.1.1
3343       *
3344       * @param array $declarations List of declarations.
3345       * @return array $declarations List of declarations filtered.
3346       */
3347  	private static function update_separator_declarations( $declarations ) {
3348          $background_color     = '';
3349          $border_color_matches = false;
3350          $text_color_matches   = false;
3351  
3352          foreach ( $declarations as $declaration ) {
3353              if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) {
3354                  $background_color = $declaration['value'];
3355              } elseif ( 'border-color' === $declaration['name'] ) {
3356                  $border_color_matches = true;
3357              } elseif ( 'color' === $declaration['name'] ) {
3358                  $text_color_matches = true;
3359              }
3360  
3361              if ( $background_color && $border_color_matches && $text_color_matches ) {
3362                  break;
3363              }
3364          }
3365  
3366          if ( $background_color && ! $border_color_matches && ! $text_color_matches ) {
3367              $declarations[] = array(
3368                  'name'  => 'color',
3369                  'value' => $background_color,
3370              );
3371          }
3372  
3373          return $declarations;
3374      }
3375  
3376      /**
3377       * Updates the text indent selector for paragraph blocks based on the textIndent setting.
3378       *
3379       * The textIndent setting can be 'subsequent' (default), 'all', or false.
3380       * When set to 'all', the selector should be '.wp-block-paragraph' instead of
3381       * '.wp-block-paragraph + .wp-block-paragraph' to apply indent to all paragraphs.
3382       *
3383       * @since 7.0.0
3384       *
3385       * @param array  $feature_declarations The feature declarations keyed by selector.
3386       * @param array  $settings             The theme.json settings.
3387       * @param string $block_name           The block name being processed.
3388       * @return array The updated feature declarations.
3389       */
3390  	private static function update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name ) {
3391          if ( 'core/paragraph' !== $block_name ) {
3392              return $feature_declarations;
3393          }
3394  
3395          // Check block-level settings first, then fall back to global settings.
3396          $block_settings      = $settings['blocks']['core/paragraph'] ?? null;
3397          $text_indent_setting = $block_settings['typography']['textIndent']
3398              ?? $settings['typography']['textIndent']
3399              ?? 'subsequent';
3400  
3401          if ( 'all' !== $text_indent_setting ) {
3402              return $feature_declarations;
3403          }
3404  
3405          // Look for the text indent selector and replace it.
3406          $old_selector = '.wp-block-paragraph + .wp-block-paragraph';
3407          $new_selector = '.wp-block-paragraph';
3408  
3409          if ( isset( $feature_declarations[ $old_selector ] ) ) {
3410              $declarations = $feature_declarations[ $old_selector ];
3411              unset( $feature_declarations[ $old_selector ] );
3412              $feature_declarations[ $new_selector ] = $declarations;
3413          }
3414  
3415          return $feature_declarations;
3416      }
3417  
3418      /**
3419       * Updates button width declarations to use a calc() formula for percentage values.
3420       *
3421       * When a percentage width is set on the Button block via Global Styles, the
3422       * resulting CSS needs to account for block gap spacing so that buttons tile
3423       * correctly on a row (e.g. 4 buttons at 25% width all fit on one row).
3424       *
3425       * This mirrors the dynamic calc() formula applied at the block instance level
3426       * in the button block's stylesheet (style.scss).
3427       *
3428       * @since 7.1.0
3429       *
3430       * @param array $feature_declarations The feature declarations keyed by selector.
3431       * @param array $settings             The theme.json settings.
3432       * @return array The updated feature declarations.
3433       */
3434  	private static function update_button_width_declarations( $feature_declarations, $settings ) {
3435          if ( ! isset( $feature_declarations['.wp-block-button'] ) ) {
3436              return $feature_declarations;
3437          }
3438  
3439          foreach ( $feature_declarations['.wp-block-button'] as &$declaration ) {
3440              if ( 'width' !== $declaration['name'] || ! isset( $declaration['value'] ) ) {
3441                  continue;
3442              }
3443  
3444              $value      = $declaration['value'];
3445              $percentage = null;
3446  
3447              // Case 1: Direct percentage value e.g. "25%".
3448              if ( is_string( $value ) && str_ends_with( $value, '%' ) ) {
3449                  $percentage = (float) $value;
3450              }
3451  
3452              // Case 2: Preset CSS var e.g. "var(--wp--preset--dimension--50)".
3453              if ( null === $percentage && is_string( $value ) && str_starts_with( $value, 'var(--wp--preset--dimension--' ) ) {
3454                  // Extract the slug from the var name.
3455                  $slug = substr( $value, strlen( 'var(--wp--preset--dimension--' ), -1 );
3456  
3457                  /*
3458                   * Look up the preset size across all origins.
3459                   * Check block-level settings first (core/button), then top-level settings.
3460                   */
3461                  $dimension_sizes = ( $settings['blocks']['core/button']['dimensions']['dimensionSizes'] ?? array() )
3462                      + ( $settings['dimensions']['dimensionSizes'] ?? array() );
3463                  foreach ( $dimension_sizes as $origin_sizes ) {
3464                      if ( ! is_array( $origin_sizes ) ) {
3465                          continue;
3466                      }
3467                      foreach ( $origin_sizes as $preset ) {
3468                          if ( isset( $preset['slug'] ) && $slug === $preset['slug'] && isset( $preset['size'] ) ) {
3469                              $size = $preset['size'];
3470                              if ( is_string( $size ) && str_ends_with( $size, '%' ) ) {
3471                                  $percentage = (float) $size;
3472                              }
3473                              break 2;
3474                          }
3475                      }
3476                  }
3477              }
3478  
3479              if ( null === $percentage ) {
3480                  continue;
3481              }
3482  
3483              /*
3484               * Apply the same calc() formula as the block instance level (style.scss).
3485               * The numeric percentage value is used as a unitless number:
3486               * - Multiplied by 1% to get the percentage width.
3487               * - Divided by 100 to calculate the gap adjustment proportion.
3488               */
3489              $declaration['value'] = sprintf(
3490                  'calc(%s * 1%% - (var(--wp--style--block-gap, 0.5em) * (1 - %s / 100)))',
3491                  $percentage,
3492                  $percentage
3493              );
3494          }
3495          unset( $declaration );
3496  
3497          return $feature_declarations;
3498      }
3499  
3500      /**
3501       * An internal method to get the block nodes from a theme.json file.
3502       *
3503       * @since 6.1.0
3504       * @since 6.3.0 Refactored and stabilized selectors API.
3505       * @since 6.6.0 Added optional selectors and options for generating block nodes.
3506       * @since 6.7.0 Added $include_node_paths_only option.
3507       * @since 7.1.0 Added responsive block nodes for breakpoint-based styles.
3508       *
3509       * @param array $theme_json The theme.json converted to an array.
3510       * @param array $selectors  Optional list of selectors per block.
3511       * @param array $options {
3512       *     Optional. An array of options for now used for internal purposes only (may change without notice).
3513       *
3514       *     @type bool $include_block_style_variations Include nodes for block style variations. Default false.
3515       *     @type bool $include_node_paths_only        Return only block nodes node paths. Default false.
3516       * }
3517       * @return array The block nodes in theme.json.
3518       */
3519  	private static function get_block_nodes( $theme_json, $selectors = array(), $options = array() ) {
3520          $nodes = array();
3521  
3522          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
3523              return $nodes;
3524          }
3525  
3526          $include_variations       = $options['include_block_style_variations'] ?? false;
3527          $include_node_paths_only  = $options['include_node_paths_only'] ?? false;
3528          $responsive_media_queries = static::get_viewport_media_queries( $theme_json['settings']['viewport'] ?? null );
3529  
3530          // If only node paths are to be returned, skip selector assignment.
3531          if ( ! $include_node_paths_only ) {
3532              $selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors;
3533          }
3534  
3535          foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
3536              $node_path = array( 'styles', 'blocks', $name );
3537              if ( $include_node_paths_only ) {
3538                  $variation_paths = array();
3539                  if ( $include_variations && isset( $node['variations'] ) ) {
3540                      foreach ( $node['variations'] as $variation => $variation_node ) {
3541                          $variation_paths[] = array(
3542                              'path' => array( 'styles', 'blocks', $name, 'variations', $variation ),
3543                          );
3544                      }
3545                  }
3546                  $node = array(
3547                      'path' => $node_path,
3548                  );
3549                  if ( ! empty( $variation_paths ) ) {
3550                      $node['variations'] = $variation_paths;
3551                  }
3552                  $nodes[] = $node;
3553              } else {
3554                  $selector = null;
3555                  if ( isset( $selectors[ $name ]['selector'] ) ) {
3556                      $selector = $selectors[ $name ]['selector'];
3557                  }
3558  
3559                  $duotone_selector = null;
3560                  if ( isset( $selectors[ $name ]['duotone'] ) ) {
3561                      $duotone_selector = $selectors[ $name ]['duotone'];
3562                  }
3563  
3564                  $feature_selectors = null;
3565                  if ( isset( $selectors[ $name ]['selectors'] ) ) {
3566                      $feature_selectors = $selectors[ $name ]['selectors'];
3567                  }
3568  
3569                  $variation_selectors = array();
3570  
3571                  if ( $include_variations && isset( $node['variations'] ) ) {
3572                      foreach ( $node['variations'] as $variation => $node ) {
3573                          $variation_selectors[] = array(
3574                              'name'     => $variation,
3575                              'path'     => array( 'styles', 'blocks', $name, 'variations', $variation ),
3576                              'selector' => $selectors[ $name ]['styleVariations'][ $variation ],
3577                          );
3578                      }
3579                  }
3580  
3581                  $nodes[] = array(
3582                      'name'       => $name,
3583                      'path'       => $node_path,
3584                      'selector'   => $selector,
3585                      'selectors'  => $feature_selectors,
3586                      'elements'   => $selectors[ $name ]['elements'] ?? array(),
3587                      'duotone'    => $duotone_selector,
3588                      'variations' => $variation_selectors,
3589                      'css'        => $selector,
3590                  );
3591  
3592                  // Responsive block nodes: emit one node per breakpoint that has styles.
3593                  // These are rendered immediately after the base block node so that
3594                  // the cascade order is: .block{} → @media{.block{}}
3595                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3596                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ] ) ) {
3597                          $nodes[] = array(
3598                              'name'        => $name,
3599                              'path'        => array( 'styles', 'blocks', $name, $breakpoint ),
3600                              'media_query' => $responsive_media_queries[ $breakpoint ],
3601                              'selector'    => $selector,
3602                              'selectors'   => $feature_selectors,
3603                              'elements'    => $selectors[ $name ]['elements'] ?? array(),
3604                              'variations'  => $variation_selectors,
3605                              'css'         => $selector,
3606                          );
3607                      }
3608                  }
3609  
3610                  // Handle any pseudo selectors for the block.
3611                  if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] ) ) {
3612                      foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] as $pseudo_selector ) {
3613                          $has_pseudo            = isset( $theme_json['styles']['blocks'][ $name ][ $pseudo_selector ] );
3614                          $has_responsive_pseudo = false;
3615                          foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3616                              if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ][ $pseudo_selector ] ) ) {
3617                                  $has_responsive_pseudo = true;
3618                                  break;
3619                              }
3620                          }
3621  
3622                          if ( ! $has_pseudo && ! $has_responsive_pseudo ) {
3623                              continue;
3624                          }
3625  
3626                          /*
3627                           * Append the pseudo-selector to each feature selector so that
3628                           * get_feature_declarations_for_node generates CSS scoped to the
3629                           * pseudo-state (e.g. '.wp-block-button:hover') rather than the
3630                           * default state (e.g. '.wp-block-button').
3631                           */
3632                          $pseudo_feature_selectors = array();
3633                          foreach ( $feature_selectors ?? array() as $feature => $feature_selector ) {
3634                              if ( is_array( $feature_selector ) ) {
3635                                  $pseudo_feature_selectors[ $feature ] = array();
3636                                  foreach ( $feature_selector as $subfeature => $subfeature_selector ) {
3637                                      $pseudo_feature_selectors[ $feature ][ $subfeature ] = static::append_to_selector( $subfeature_selector, $pseudo_selector );
3638                                  }
3639                              } else {
3640                                  $pseudo_feature_selectors[ $feature ] = static::append_to_selector( $feature_selector, $pseudo_selector );
3641                              }
3642                          }
3643  
3644                          if ( $has_pseudo ) {
3645                              $nodes[] = array(
3646                                  'name'       => $name,
3647                                  'path'       => array( 'styles', 'blocks', $name, $pseudo_selector ),
3648                                  'selector'   => static::append_to_selector( $selector, $pseudo_selector ),
3649                                  'selectors'  => $pseudo_feature_selectors,
3650                                  'elements'   => $selectors[ $name ]['elements'] ?? array(),
3651                                  'duotone'    => $duotone_selector,
3652                                  'variations' => $variation_selectors,
3653                                  'css'        => static::append_to_selector( $selector, $pseudo_selector ),
3654                              );
3655                          }
3656  
3657                          // Responsive pseudo nodes: emit one node per breakpoint that has
3658                          // this pseudo state, immediately after the default pseudo node.
3659                          // Cascade order: .block:hover{} → @media{.block:hover{}}
3660                          foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3661                              if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ][ $pseudo_selector ] ) ) {
3662                                  $nodes[] = array(
3663                                      'name'        => $name,
3664                                      'path'        => array( 'styles', 'blocks', $name, $breakpoint, $pseudo_selector ),
3665                                      'media_query' => $responsive_media_queries[ $breakpoint ],
3666                                      'selector'    => static::append_to_selector( $selector, $pseudo_selector ),
3667                                      'selectors'   => $pseudo_feature_selectors,
3668                                      'elements'    => $selectors[ $name ]['elements'] ?? array(),
3669                                      'variations'  => $variation_selectors,
3670                                      'css'         => static::append_to_selector( $selector, $pseudo_selector ),
3671                                  );
3672                              }
3673                          }
3674                      }
3675                  }
3676  
3677                  // Handle custom states (e.g. '-current' for navigation).
3678                  if ( isset( static::VALID_BLOCK_CUSTOM_STATES[ $name ] ) ) {
3679                      foreach ( static::VALID_BLOCK_CUSTOM_STATES[ $name ] as $custom_state ) {
3680                          if (
3681                              isset( $theme_json['styles']['blocks'][ $name ][ $custom_state ] ) &&
3682                              isset( $selectors[ $name ]['states'][ $custom_state ] )
3683                          ) {
3684                              $custom_css_selector = $selectors[ $name ]['states'][ $custom_state ];
3685                              $nodes[]             = array(
3686                                  'name'       => $name,
3687                                  'path'       => array( 'styles', 'blocks', $name, $custom_state ),
3688                                  'selector'   => $custom_css_selector,
3689                                  'selectors'  => $feature_selectors,
3690                                  'elements'   => $selectors[ $name ]['elements'] ?? array(),
3691                                  'duotone'    => $duotone_selector,
3692                                  'variations' => $variation_selectors,
3693                                  'css'        => $custom_css_selector,
3694                              );
3695  
3696                              // Sub-pseudo-selectors within the custom state.
3697                              if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] ) ) {
3698                                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] as $pseudo ) {
3699                                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $custom_state ][ $pseudo ] ) ) {
3700                                          $compound_css_selector = static::append_to_selector( $custom_css_selector, $pseudo );
3701                                          $nodes[]               = array(
3702                                              'name'       => $name,
3703                                              'path'       => array( 'styles', 'blocks', $name, $custom_state, $pseudo ),
3704                                              'selector'   => $compound_css_selector,
3705                                              'selectors'  => $feature_selectors,
3706                                              'elements'   => $selectors[ $name ]['elements'] ?? array(),
3707                                              'duotone'    => $duotone_selector,
3708                                              'variations' => $variation_selectors,
3709                                              'css'        => $compound_css_selector,
3710                                          );
3711                                      }
3712                                  }
3713                              }
3714                          }
3715                      }
3716                  }
3717              }
3718              if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) {
3719                  foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) {
3720                      $element_path = array( 'styles', 'blocks', $name, 'elements', $element );
3721                      if ( $include_node_paths_only ) {
3722                          $nodes[] = array(
3723                              'path' => $element_path,
3724                          );
3725                          continue;
3726                      }
3727  
3728                      $element_selector = $selectors[ $name ]['elements'][ $element ];
3729  
3730                      $nodes[] = array(
3731                          'path'     => $element_path,
3732                          'selector' => $element_selector,
3733                      );
3734  
3735                      // Responsive element nodes: one node per breakpoint that has
3736                      // styles for this element. Cascade: a{} → @media{a{}}
3737                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3738                          if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ]['elements'][ $element ] ) ) {
3739                              $nodes[] = array(
3740                                  'path'        => array( 'styles', 'blocks', $name, $breakpoint, 'elements', $element ),
3741                                  'selector'    => $element_selector,
3742                                  'media_query' => $responsive_media_queries[ $breakpoint ],
3743                              );
3744                          }
3745                      }
3746  
3747                      // Handle any pseudo selectors for the element.
3748                      if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
3749                          foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
3750                              // Create element pseudo node if default or any responsive breakpoint has the pseudo.
3751                              $has_element_pseudo = isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] );
3752                              if ( ! $has_element_pseudo ) {
3753                                  foreach ( array_keys( $responsive_media_queries ) as $bp ) {
3754                                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $bp ]['elements'][ $element ][ $pseudo_selector ] ) ) {
3755                                          $has_element_pseudo = true;
3756                                          break;
3757                                      }
3758                                  }
3759                              }
3760  
3761                              if ( $has_element_pseudo ) {
3762                                  $element_pseudo_path = array( 'styles', 'blocks', $name, 'elements', $element );
3763                                  if ( $include_node_paths_only ) {
3764                                      $nodes[] = array(
3765                                          'path' => $element_pseudo_path,
3766                                      );
3767                                      continue;
3768                                  }
3769  
3770                                  $nodes[] = array(
3771                                      'path'     => $element_pseudo_path,
3772                                      'selector' => static::append_to_selector( $element_selector, $pseudo_selector ),
3773                                  );
3774  
3775                                  // Responsive element pseudo nodes: one node per breakpoint
3776                                  // that has this pseudo state for this element.
3777                                  // Cascade: a:hover{} → @media{a:hover{}}
3778                                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3779                                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ]['elements'][ $element ][ $pseudo_selector ] ) ) {
3780                                          $nodes[] = array(
3781                                              'path'        => array( 'styles', 'blocks', $name, $breakpoint, 'elements', $element ),
3782                                              'selector'    => static::append_to_selector( $element_selector, $pseudo_selector ),
3783                                              'media_query' => $responsive_media_queries[ $breakpoint ],
3784                                          );
3785                                      }
3786                                  }
3787                              }
3788                          }
3789                      }
3790                  }
3791              }
3792          }
3793  
3794          return $nodes;
3795      }
3796  
3797      /**
3798       * Gets the CSS rules for a particular block from theme.json.
3799       *
3800       * @since 6.1.0
3801       * @since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image.
3802       *              Updated general global styles specificity to 0-1-0.
3803       *              Fixed custom CSS output in block style variations.
3804       *
3805       * @param array $block_metadata Metadata about the block to get styles for.
3806       * @return string Styles for the block.
3807       */
3808  	public function get_styles_for_block( $block_metadata ) {
3809          $node                     = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
3810          $use_root_padding         = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
3811          $selector                 = $block_metadata['selector'];
3812          $settings                 = $this->theme_json['settings'] ?? array();
3813          $feature_declarations     = static::get_feature_declarations_for_node( $block_metadata, $node );
3814          $is_root_selector         = static::ROOT_BLOCK_SELECTOR === $selector;
3815          $media_query              = $block_metadata['media_query'] ?? null;
3816          $responsive_media_queries = static::get_viewport_media_queries( $settings['viewport'] ?? null );
3817  
3818          // Update text indent selector for paragraph blocks based on the textIndent setting.
3819          $block_name           = $block_metadata['name'] ?? null;
3820          $feature_declarations = static::update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name );
3821          $block_elements       = $block_metadata['elements'] ?? array();
3822  
3823          // Update button width declarations for percentage values to use calc() with block gap.
3824          $feature_declarations = static::update_button_width_declarations( $feature_declarations, $settings );
3825  
3826          // If there are style variations, generate the declarations for them, including any feature selectors the block may have.
3827          $style_variation_declarations          = array();
3828          $style_variation_custom_css            = array();
3829          $style_variation_responsive_css        = array();
3830          $style_variation_responsive_pseudo_css = array();
3831          $style_variation_layout_metadata       = array();
3832          if ( ! $media_query && ! empty( $block_metadata['variations'] ) ) {
3833              foreach ( $block_metadata['variations'] as $style_variation ) {
3834                  $style_variation_node = _wp_array_get( $this->theme_json, $style_variation['path'], array() );
3835  
3836                  // Generate any feature/subfeature style declarations for the current style variation.
3837                  $variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node );
3838  
3839                  // Update text indent selector for paragraph blocks based on the textIndent setting.
3840                  $variation_declarations = static::update_paragraph_text_indent_selector( $variation_declarations, $settings, $block_name );
3841  
3842                  // Update button width declarations for percentage values to use calc() with block gap.
3843                  $variation_declarations = static::update_button_width_declarations( $variation_declarations, $settings );
3844  
3845                  // Combine selectors with style variation's selector and add to overall style variation declarations.
3846                  foreach ( $variation_declarations as $current_selector => $new_declarations ) {
3847                      $combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $current_selector );
3848  
3849                      // Add the new declarations to the overall results under the modified selector.
3850                      $style_variation_declarations[ $combined_selectors ] = $new_declarations;
3851                  }
3852  
3853                  // Compute declarations for remaining styles not covered by feature level selectors.
3854                  $style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json );
3855  
3856                  // Process pseudo-selectors for this variation (e.g., :hover, :focus)
3857                  if ( isset( $block_metadata['name'] ) ) {
3858                      $block_name = $block_metadata['name'];
3859                  } elseif ( in_array( 'blocks', $block_metadata['path'], true ) && count( $block_metadata['path'] ) >= 3 ) {
3860                      $block_name = static::get_block_name_from_metadata_path( $block_metadata );
3861                  } else {
3862                      $block_name = null;
3863                  }
3864                  $variation_pseudo_declarations = $this->process_pseudo_selectors( $style_variation_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
3865                  $style_variation_declarations  = array_merge( $style_variation_declarations, $variation_pseudo_declarations );
3866  
3867                  // Store custom CSS for the style variation.
3868                  if ( isset( $style_variation_node['css'] ) ) {
3869                      $style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] );
3870                  }
3871  
3872                  // Store variation metadata and node for layout styles generation.
3873                  // Only store if the variation has blockGap defined.
3874                  if ( isset( $style_variation_node['spacing']['blockGap'] ) ) {
3875                      // Append block selector to the variation selector for proper targeting.
3876                      $variation_metadata_with_selector                                = $style_variation;
3877                      $variation_metadata_with_selector['selector']                    = $style_variation['selector'] . $block_metadata['css'];
3878                      $style_variation_layout_metadata[ $style_variation['selector'] ] = array(
3879                          'metadata' => $variation_metadata_with_selector,
3880                          'node'     => $style_variation_node,
3881                      );
3882                  }
3883  
3884                  // Store responsive breakpoint CSS for the style variation.
3885                  // This includes both base properties and feature-level selectors.
3886                  $variation_responsive_css        = '';
3887                  $variation_responsive_pseudo_css = '';
3888  
3889                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3890                      if ( ! isset( $style_variation_node[ $breakpoint ] ) ) {
3891                          continue;
3892                      }
3893  
3894                      $breakpoint_node  = $style_variation_node[ $breakpoint ];
3895                      $breakpoint_media = $responsive_media_queries[ $breakpoint ];
3896                      // Process feature-level declarations for this breakpoint.
3897                      $breakpoint_feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $breakpoint_node );
3898                      $breakpoint_feature_declarations = static::update_paragraph_text_indent_selector( $breakpoint_feature_declarations, $settings, $block_name );
3899                      $breakpoint_feature_declarations = static::update_button_width_declarations( $breakpoint_feature_declarations, $settings );
3900                      foreach ( $breakpoint_feature_declarations as $feature_selector => $feature_decl ) {
3901                          $combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $feature_selector );
3902  
3903                          $feature_ruleset           = static::to_ruleset( ':root :where(' . $combined_selectors . ')', $feature_decl );
3904                          $variation_responsive_css .= $breakpoint_media . '{' . $feature_ruleset . '}';
3905                      }
3906  
3907                      // Process base properties for this breakpoint.
3908                      $breakpoint_declarations = static::compute_style_properties( $breakpoint_node, $settings, null, $this->theme_json );
3909                      if ( ! empty( $breakpoint_declarations ) ) {
3910                          $base_ruleset              = static::to_ruleset( ':root :where(' . $style_variation['selector'] . ')', $breakpoint_declarations );
3911                          $variation_responsive_css .= $breakpoint_media . '{' . $base_ruleset . '}';
3912                      }
3913  
3914                      $breakpoint_pseudo_declarations = $this->process_pseudo_selectors( $breakpoint_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
3915                      foreach ( $breakpoint_pseudo_declarations as $pseudo_selector => $pseudo_declarations ) {
3916                          if ( empty( $pseudo_declarations ) ) {
3917                              continue;
3918                          }
3919                          $pseudo_ruleset                   = static::to_ruleset( ':root :where(' . $pseudo_selector . ')', $pseudo_declarations );
3920                          $variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_ruleset . '}';
3921                      }
3922  
3923                      // Process custom CSS for this breakpoint.
3924                      if ( isset( $breakpoint_node['css'] ) ) {
3925                          $breakpoint_custom_css     = static::process_blocks_custom_css( $breakpoint_node['css'], $style_variation['selector'] );
3926                          $variation_responsive_css .= $breakpoint_media . '{' . $breakpoint_custom_css . '}';
3927                      }
3928  
3929                      // Process blockGap responsive layout styles for this variation.
3930                      if ( isset( $breakpoint_node['spacing']['blockGap'] ) ) {
3931                          $variation_layout_metadata             = $style_variation;
3932                          $variation_layout_metadata['selector'] = $style_variation['selector'] . $block_metadata['css'];
3933                          $variation_responsive_css             .= $this->get_layout_styles(
3934                              $variation_layout_metadata,
3935                              array(
3936                                  'node'        => $breakpoint_node,
3937                                  'media_query' => $breakpoint_media,
3938                              )
3939                          );
3940                      }
3941  
3942                      // Process nested element styles for this breakpoint state.
3943                      if ( isset( $breakpoint_node['elements'] ) && ! empty( $block_elements ) ) {
3944                          foreach ( $breakpoint_node['elements'] as $element_name => $element_node ) {
3945                              if ( ! isset( $block_elements[ $element_name ] ) ) {
3946                                  continue;
3947                              }
3948  
3949                              $variation_element_selector = static::get_block_style_variation_feature_selector( $style_variation, $block_elements[ $element_name ] );
3950  
3951                              $element_declarations = static::compute_style_properties( $element_node, $settings, null, $this->theme_json );
3952                              if ( ! empty( $element_declarations ) ) {
3953                                  $element_ruleset           = static::to_ruleset( ':root :where(' . $variation_element_selector . ')', $element_declarations );
3954                                  $variation_responsive_css .= $breakpoint_media . '{' . $element_ruleset . '}';
3955                              }
3956  
3957                              if ( isset( $element_node['css'] ) ) {
3958                                  $element_custom_css        = static::process_blocks_custom_css( $element_node['css'], $variation_element_selector );
3959                                  $variation_responsive_css .= $breakpoint_media . '{' . $element_custom_css . '}';
3960                              }
3961  
3962                              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
3963                                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
3964                                      if ( ! isset( $element_node[ $pseudo_selector ] ) ) {
3965                                          continue;
3966                                      }
3967  
3968                                      $pseudo_declarations = static::compute_style_properties( $element_node[ $pseudo_selector ], $settings, null, $this->theme_json );
3969                                      if ( empty( $pseudo_declarations ) ) {
3970                                          continue;
3971                                      }
3972  
3973                                      $pseudo_selector_ruleset          = static::to_ruleset( ':root :where(' . static::append_to_selector( $variation_element_selector, $pseudo_selector ) . ')', $pseudo_declarations );
3974                                      $variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_selector_ruleset . '}';
3975                                  }
3976                              }
3977                          }
3978                      }
3979                  }
3980  
3981                  if ( ! empty( $variation_responsive_css ) ) {
3982                      $style_variation_responsive_css[ $style_variation['selector'] ] = $variation_responsive_css;
3983                  }
3984                  if ( ! empty( $variation_responsive_pseudo_css ) ) {
3985                      $style_variation_responsive_pseudo_css[ $style_variation['selector'] ] = $variation_responsive_pseudo_css;
3986                  }
3987              }
3988          }
3989          /*
3990           * Get a reference to element name from path.
3991           * $block_metadata['path'] = array( 'styles','elements','link' );
3992           * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ].
3993           * Skip non-element paths like just ['styles'].
3994           */
3995          $is_processing_element = in_array( 'elements', $block_metadata['path'], true );
3996  
3997          $current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null;
3998  
3999          $element_pseudo_allowed = array();
4000  
4001          if ( isset( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
4002              $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ];
4003          }
4004  
4005          /*
4006           * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
4007           * This also resets the array keys.
4008           */
4009          $pseudo_matches = array_values(
4010              array_filter(
4011                  $element_pseudo_allowed,
4012                  static function ( $pseudo_selector ) use ( $selector ) {
4013                      /*
4014                       * Check if the pseudo selector is in the current selector,
4015                       * ensuring it is not followed by a dash (e.g., :focus should not match :focus-visible).
4016                       */
4017                      return preg_match( '/' . preg_quote( $pseudo_selector, '/' ) . '(?!-)/', $selector ) === 1;
4018                  }
4019              )
4020          );
4021  
4022          $pseudo_selector = $pseudo_matches[0] ?? null;
4023  
4024          /*
4025           * If the current selector is a pseudo selector that's defined in the allow list for the current
4026           * element then compute the style properties for it.
4027           * Otherwise just compute the styles for the default selector as normal.
4028           */
4029          if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) &&
4030              isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] )
4031              && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true )
4032          ) {
4033              $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
4034          } else {
4035              /*
4036               * For block pseudo-selector nodes (e.g. ':hover'), $node has already had any
4037               * feature-selector properties (e.g. writingMode) removed by get_feature_declarations_for_node,
4038               * so those properties are not output twice.
4039               */
4040              $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
4041          }
4042  
4043          $block_rules = '';
4044  
4045          /*
4046           * 1. Bespoke declaration modifiers:
4047           * - 'filter': Separate the declarations that use the general selector
4048           * from the ones using the duotone selector.
4049           * - 'background|background-image': set the html min-height to 100%
4050           * to ensure the background covers the entire viewport.
4051           */
4052          $declarations_duotone       = array();
4053          $should_set_root_min_height = false;
4054  
4055          foreach ( $declarations as $index => $declaration ) {
4056              if ( 'filter' === $declaration['name'] ) {
4057                  /*
4058                   * 'unset' filters happen when a filter is unset
4059                   * in the site-editor UI. Because the 'unset' value
4060                   * in the user origin overrides the value in the
4061                   * theme origin, we can skip rendering anything
4062                   * here as no filter needs to be applied anymore.
4063                   * So only add declarations to with values other
4064                   * than 'unset'.
4065                   */
4066                  if ( 'unset' !== $declaration['value'] ) {
4067                      $declarations_duotone[] = $declaration;
4068                  }
4069                  unset( $declarations[ $index ] );
4070              }
4071  
4072              if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) {
4073                  $should_set_root_min_height = true;
4074              }
4075          }
4076  
4077          /*
4078           * If root styles has a background-image or a background (gradient) set,
4079           * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view.
4080           * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly,
4081           * and matches the behavior of the site editor.
4082           */
4083          if ( $should_set_root_min_height ) {
4084              $block_rules .= static::to_ruleset(
4085                  'html',
4086                  array(
4087                      array(
4088                          'name'  => 'min-height',
4089                          'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))',
4090                      ),
4091                  )
4092              );
4093          }
4094  
4095          // Update declarations if there are separators with only background color defined.
4096          if ( '.wp-block-separator' === $selector ) {
4097              $declarations = static::update_separator_declarations( $declarations );
4098          }
4099  
4100          /*
4101           * Root selector (body) styles should not be wrapped in `:root where()` to keep
4102           * specificity at (0,0,1) and maintain backwards compatibility.
4103           *
4104           * Top-level element styles using element-only specificity selectors should
4105           * not get wrapped in `:root :where()` to maintain backwards compatibility.
4106           *
4107           * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so
4108           * still need to be wrapped in `:root :where` to cap specificity for nested
4109           * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly.
4110           */
4111          $element_only_selector = $is_root_selector || (
4112              $current_element &&
4113              isset( static::ELEMENTS[ $current_element ] ) &&
4114              // buttons, captions etc. still need `:root :where()` as they are class based selectors.
4115              ! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) &&
4116              static::ELEMENTS[ $current_element ] === $selector
4117          );
4118  
4119          // 2. Generate and append the rules that use the general selector.
4120          $general_selector = $element_only_selector ? $selector : ":root :where($selector)";
4121          $block_rules     .= static::to_ruleset( $general_selector, $declarations );
4122  
4123          // 3. Generate and append the rules that use the duotone selector.
4124          if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
4125              $block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone );
4126          }
4127  
4128          // 4. Generate Layout block gap styles.
4129          if (
4130              ! $is_root_selector &&
4131              ! empty( $block_metadata['name'] )
4132          ) {
4133              $block_rules .= $this->get_layout_styles( $block_metadata );
4134          }
4135  
4136          // 5. Generate and append the feature level rulesets.
4137          foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
4138              $block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations );
4139          }
4140  
4141          // 6. Generate and append the style variation rulesets.
4142          foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) {
4143              $block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations );
4144              if ( isset( $style_variation_layout_metadata[ $style_variation_selector ] ) ) {
4145                  $variation_data = $style_variation_layout_metadata[ $style_variation_selector ];
4146                  $block_rules   .= $this->get_layout_styles( $variation_data['metadata'], array( 'node' => $variation_data['node'] ) );
4147              }
4148              if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) {
4149                  $block_rules .= $style_variation_custom_css[ $style_variation_selector ];
4150              }
4151              if ( isset( $style_variation_responsive_css[ $style_variation_selector ] ) ) {
4152                  $block_rules .= $style_variation_responsive_css[ $style_variation_selector ];
4153              }
4154          }
4155          /*
4156           * Responsive pseudo styles must be output after default pseudo styles
4157           * so viewport state styles win in the cascade.
4158           */
4159          foreach ( $style_variation_responsive_pseudo_css as $responsive_pseudo_css ) {
4160              $block_rules .= $responsive_pseudo_css;
4161          }
4162  
4163          // 7. Generate and append any custom CSS rules.
4164          if ( isset( $node['css'] ) && ! $is_root_selector ) {
4165              $css_feature_selector = $block_metadata['selectors']['css'] ?? null;
4166              if ( is_array( $css_feature_selector ) ) {
4167                  $css_feature_selector = $css_feature_selector['root'] ?? null;
4168              }
4169              $css_selector = is_string( $css_feature_selector ) ? $css_feature_selector : $selector;
4170              $block_rules .= $this->process_blocks_custom_css( $node['css'], $css_selector );
4171          }
4172  
4173          // 8. Wrap the entire block output in a media query if this is a responsive node.
4174          // Responsive nodes are created by get_block_nodes() for each breakpoint and carry
4175          // a 'media_query' key.
4176          if ( $media_query && ! empty( $block_rules ) ) {
4177              $block_rules = $media_query . '{' . $block_rules . '}';
4178          }
4179  
4180          return $block_rules;
4181      }
4182  
4183      /**
4184       * Outputs the CSS for layout rules on the root.
4185       *
4186       * @since 6.1.0
4187       * @since 6.6.0 Use `ROOT_CSS_PROPERTIES_SELECTOR` for CSS custom properties and improved consistency of root padding rules.
4188       *              Updated specificity of body margin reset and first/last child selectors.
4189       * @since 7.0.0 Added `$options` parameter to control alignment styles output for classic themes.
4190       *
4191       * @param string $selector The root node selector.
4192       * @param array  $block_metadata The metadata for the root block.
4193       * @param array  $options        Optional. An array of options for now used for internal purposes only.
4194       * @return string The additional root rules CSS.
4195       */
4196  	public function get_root_layout_rules( $selector, $block_metadata, $options = array() ) {
4197          $css              = '';
4198          $settings         = $this->theme_json['settings'] ?? array();
4199          $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
4200  
4201          /*
4202           * If there are content and wide widths in theme.json, output them
4203           * as custom properties on the body element so all blocks can use them.
4204           */
4205          if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) {
4206              $content_size = $settings['layout']['contentSize'] ?? $settings['layout']['wideSize'];
4207              $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial';
4208              $wide_size    = $settings['layout']['wideSize'] ?? $settings['layout']['contentSize'];
4209              $wide_size    = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial';
4210              $css         .= static::ROOT_CSS_PROPERTIES_SELECTOR . ' { --wp--style--global--content-size: ' . $content_size . ';';
4211              $css         .= '--wp--style--global--wide-size: ' . $wide_size . '; }';
4212          }
4213  
4214          /*
4215           * Reset default browser margin on the body element.
4216           * This is set on the body selector **before** generating the ruleset
4217           * from the `theme.json`. This is to ensure that if the `theme.json` declares
4218           * `margin` in its `spacing` declaration for the `body` element then these
4219           * user-generated values take precedence in the CSS cascade.
4220           * @link https://github.com/WordPress/gutenberg/issues/36147.
4221           */
4222          $css .= ':where(body) { margin: 0; }';
4223  
4224          if ( $use_root_padding ) {
4225              // Top and bottom padding are applied to the outer block container.
4226              $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }';
4227              // Right and left padding are applied to the first container with `.has-global-padding` class.
4228              $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
4229              // Alignfull children of the container with left and right padding have negative margins so they can still be full width.
4230              $css .= '.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }';
4231              // Nested children of the container with left and right padding that are not full aligned do not get padding, unless they are direct children of an alignfull flow container.
4232              $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }';
4233              // Alignfull direct children of the containers that are targeted by the rule above do not need negative margins.
4234              $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) > .alignfull { margin-left: 0; margin-right: 0; }';
4235          }
4236  
4237          // Skip outputting alignment styles when base_layout_styles is enabled.
4238          // These styles target .wp-site-blocks which is only used by block themes.
4239          if ( empty( $options['base_layout_styles'] ) ) {
4240              $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
4241              $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
4242              $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
4243          }
4244  
4245          // Block gap styles will be output unless explicitly set to `null`.
4246          if ( isset( $this->theme_json['settings']['spacing']['blockGap'] ) ) {
4247              $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) );
4248              $css            .= ":where(.wp-site-blocks) > * { margin-block-start: $block_gap_value; margin-block-end: 0; }";
4249              $css            .= ':where(.wp-site-blocks) > :first-child { margin-block-start: 0; }';
4250              $css            .= ':where(.wp-site-blocks) > :last-child { margin-block-end: 0; }';
4251  
4252              // For backwards compatibility, ensure the legacy block gap CSS variable is still available.
4253              $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . " { --wp--style--block-gap: $block_gap_value; }";
4254          }
4255          $css .= $this->get_layout_styles( $block_metadata, $options );
4256  
4257          return $css;
4258      }
4259  
4260      /**
4261       * For metadata values that can either be booleans or paths to booleans, gets the value.
4262       *
4263       *     $data = array(
4264       *       'color' => array(
4265       *         'defaultPalette' => true
4266       *       )
4267       *     );
4268       *
4269       *     static::get_metadata_boolean( $data, false );
4270       *     // => false
4271       *
4272       *     static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) );
4273       *     // => true
4274       *
4275       * @since 6.0.0
4276       *
4277       * @param array      $data          The data to inspect.
4278       * @param bool|array $path          Boolean or path to a boolean.
4279       * @param bool       $default_value Default value if the referenced path is missing.
4280       *                                  Default false.
4281       * @return bool Value of boolean metadata.
4282       */
4283  	protected static function get_metadata_boolean( $data, $path, $default_value = false ) {
4284          if ( is_bool( $path ) ) {
4285              return $path;
4286          }
4287  
4288          if ( is_array( $path ) ) {
4289              $value = _wp_array_get( $data, $path );
4290              if ( null !== $value ) {
4291                  return $value;
4292              }
4293          }
4294  
4295          return $default_value;
4296      }
4297  
4298      /**
4299       * Merges new incoming data.
4300       *
4301       * @since 5.8.0
4302       * @since 5.9.0 Duotone preset also has origins.
4303       * @since 6.7.0 Replace background image objects during merge.
4304       *
4305       * @param WP_Theme_JSON $incoming Data to merge.
4306       */
4307  	public function merge( $incoming ) {
4308          $incoming_data    = $incoming->get_raw_data();
4309          $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data );
4310  
4311          /*
4312           * Recompute all the spacing sizes based on the new hierarchy of data. In the constructor
4313           * spacingScale and spacingSizes are both keyed by origin and VALID_ORIGINS is ordered, so
4314           * we can allow partial spacingScale data to inherit missing data from earlier layers when
4315           * computing the spacing sizes.
4316           *
4317           * This happens before the presets are merged to ensure that default spacing sizes can be
4318           * removed from the theme origin if $prevent_override is true.
4319           */
4320          $flattened_spacing_scale = array();
4321          foreach ( static::VALID_ORIGINS as $origin ) {
4322              $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin );
4323  
4324              // Apply the base spacing scale to the current layer.
4325              $base_spacing_scale      = _wp_array_get( $this->theme_json, $scale_path, array() );
4326              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $base_spacing_scale );
4327  
4328              $spacing_scale = _wp_array_get( $incoming_data, $scale_path, null );
4329              if ( ! isset( $spacing_scale ) ) {
4330                  continue;
4331              }
4332  
4333              // Allow partial scale settings by merging with lower layers.
4334              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $spacing_scale );
4335  
4336              // Generate and merge the scales for this layer.
4337              $sizes_path           = array( 'settings', 'spacing', 'spacingSizes', $origin );
4338              $spacing_sizes        = _wp_array_get( $incoming_data, $sizes_path, array() );
4339              $spacing_scale_sizes  = static::compute_spacing_sizes( $flattened_spacing_scale );
4340              $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes );
4341  
4342              _wp_array_set( $incoming_data, $sizes_path, $merged_spacing_sizes );
4343          }
4344  
4345          /*
4346           * The array_replace_recursive algorithm merges at the leaf level,
4347           * but we don't want leaf arrays to be merged, so we overwrite it.
4348           *
4349           * For leaf values that are sequential arrays it will use the numeric indexes for replacement.
4350           * We rather replace the existing with the incoming value, if it exists.
4351           * This is the case of spacing.units.
4352           *
4353           * For leaf values that are associative arrays it will merge them as expected.
4354           * This is also not the behavior we want for the current associative arrays (presets).
4355           * We rather replace the existing with the incoming value, if it exists.
4356           * This happens, for example, when we merge data from theme.json upon existing
4357           * theme supports or when we merge anything coming from the same source twice.
4358           * This is the case of color.palette, color.gradients, color.duotone,
4359           * typography.fontSizes, or typography.fontFamilies.
4360           *
4361           * Additionally, for some preset types, we also want to make sure the
4362           * values they introduce don't conflict with default values. We do so
4363           * by checking the incoming slugs for theme presets and compare them
4364           * with the equivalent default presets: if a slug is present as a default
4365           * we remove it from the theme presets.
4366           */
4367          $nodes        = static::get_setting_nodes( $incoming_data );
4368          $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) );
4369          foreach ( $nodes as $node ) {
4370              // Replace the spacing.units.
4371              $path   = $node['path'];
4372              $path[] = 'spacing';
4373              $path[] = 'units';
4374  
4375              $content = _wp_array_get( $incoming_data, $path, null );
4376              if ( isset( $content ) ) {
4377                  _wp_array_set( $this->theme_json, $path, $content );
4378              }
4379  
4380              // Replace the presets.
4381              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
4382                  $prevent_override = $preset_metadata['prevent_override'];
4383                  if ( is_array( $prevent_override ) ) {
4384                      $global_path  = array_merge( array( 'settings' ), $prevent_override );
4385                      $global_value = _wp_array_get( $this->theme_json, $global_path, null );
4386  
4387                      $node_level_path  = array_merge( $node['path'], $prevent_override );
4388                      $prevent_override = _wp_array_get( $this->theme_json, $node_level_path, $global_value );
4389                  }
4390  
4391                  foreach ( static::VALID_ORIGINS as $origin ) {
4392                      $base_path = $node['path'];
4393                      foreach ( $preset_metadata['path'] as $leaf ) {
4394                          $base_path[] = $leaf;
4395                      }
4396  
4397                      $path   = $base_path;
4398                      $path[] = $origin;
4399  
4400                      $content = _wp_array_get( $incoming_data, $path, null );
4401                      if ( ! isset( $content ) ) {
4402                          continue;
4403                      }
4404  
4405                      // Set names for theme presets based on the slug if they are not set and can use default names.
4406                      if ( 'theme' === $origin && $preset_metadata['use_default_names'] ) {
4407                          foreach ( $content as $key => $item ) {
4408                              if ( ! isset( $item['name'] ) ) {
4409                                  $name = static::get_name_from_defaults( $item['slug'], $base_path );
4410                                  if ( null !== $name ) {
4411                                      $content[ $key ]['name'] = $name;
4412                                  }
4413                              }
4414                          }
4415                      }
4416  
4417                      // Filter out default slugs from theme presets when defaults should not be overridden.
4418                      if ( 'theme' === $origin && $prevent_override ) {
4419                          $slugs_node    = static::get_default_slugs( $this->theme_json, $node['path'] );
4420                          $preset_global = _wp_array_get( $slugs_global, $preset_metadata['path'], array() );
4421                          $preset_node   = _wp_array_get( $slugs_node, $preset_metadata['path'], array() );
4422                          $preset_slugs  = array_merge_recursive( $preset_global, $preset_node );
4423  
4424                          $content = static::filter_slugs( $content, $preset_slugs );
4425                      }
4426  
4427                      _wp_array_set( $this->theme_json, $path, $content );
4428                  }
4429              }
4430          }
4431  
4432          /*
4433           * Style values are merged at the leaf level, however
4434           * some values provide exceptions, namely style values that are
4435           * objects and represent unique definitions for the style.
4436           */
4437          $style_nodes = static::get_block_nodes(
4438              $this->theme_json,
4439              array(),
4440              array( 'include_node_paths_only' => true )
4441          );
4442  
4443          // Add top-level styles.
4444          $style_nodes[] = array( 'path' => array( 'styles' ) );
4445  
4446          foreach ( $style_nodes as $style_node ) {
4447              $path = $style_node['path'];
4448              /*
4449               * Background image styles should be replaced, not merged,
4450               * as they themselves are specific object definitions for the style.
4451               */
4452              $background_image_path = array_merge( $path, static::PROPERTIES_METADATA['background-image'] );
4453              $content               = _wp_array_get( $incoming_data, $background_image_path, null );
4454              if ( isset( $content ) ) {
4455                  _wp_array_set( $this->theme_json, $background_image_path, $content );
4456              }
4457          }
4458      }
4459  
4460      /**
4461       * Converts all filter (duotone) presets into SVGs.
4462       *
4463       * @since 5.9.1
4464       *
4465       * @param array $origins List of origins to process.
4466       * @return string SVG filters.
4467       */
4468  	public function get_svg_filters( $origins ) {
4469          $blocks_metadata = static::get_blocks_metadata();
4470          $setting_nodes   = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
4471  
4472          $filters = '';
4473          foreach ( $setting_nodes as $metadata ) {
4474              $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
4475              if ( empty( $node['color']['duotone'] ) ) {
4476                  continue;
4477              }
4478  
4479              $duotone_presets = $node['color']['duotone'];
4480  
4481              foreach ( $origins as $origin ) {
4482                  if ( ! isset( $duotone_presets[ $origin ] ) ) {
4483                      continue;
4484                  }
4485                  foreach ( $duotone_presets[ $origin ] as $duotone_preset ) {
4486                      $filters .= WP_Duotone::get_filter_svg_from_preset( $duotone_preset );
4487                  }
4488              }
4489          }
4490  
4491          return $filters;
4492      }
4493  
4494      /**
4495       * Determines whether a presets should be overridden or not.
4496       *
4497       * @since 5.9.0
4498       * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead.
4499       *
4500       * @param array      $theme_json The theme.json like structure to inspect.
4501       * @param array      $path       Path to inspect.
4502       * @param bool|array $override   Data to compute whether to override the preset.
4503       * @return bool|null True if the preset should override the defaults, false if not. Null if the override parameter is invalid.
4504       */
4505  	protected static function should_override_preset( $theme_json, $path, $override ) {
4506          _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' );
4507  
4508          if ( is_bool( $override ) ) {
4509              return $override;
4510          }
4511  
4512          /*
4513           * The relationship between whether to override the defaults
4514           * and whether the defaults are enabled is inverse:
4515           *
4516           * - If defaults are enabled  => theme presets should not be overridden
4517           * - If defaults are disabled => theme presets should be overridden
4518           *
4519           * For example, a theme sets defaultPalette to false,
4520           * making the default palette hidden from the user.
4521           * In that case, we want all the theme presets to be present,
4522           * so they should override the defaults.
4523           */
4524          if ( is_array( $override ) ) {
4525              $value = _wp_array_get( $theme_json, array_merge( $path, $override ) );
4526              if ( isset( $value ) ) {
4527                  return ! $value;
4528              }
4529  
4530              // Search the top-level key if none was found for this node.
4531              $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) );
4532              if ( isset( $value ) ) {
4533                  return ! $value;
4534              }
4535  
4536              return true;
4537          }
4538  
4539          return null;
4540      }
4541  
4542      /**
4543       * Returns the default slugs for all the presets in an associative array
4544       * whose keys are the preset paths and the leaves is the list of slugs.
4545       *
4546       * For example:
4547       *
4548       *     array(
4549       *       'color' => array(
4550       *         'palette'   => array( 'slug-1', 'slug-2' ),
4551       *         'gradients' => array( 'slug-3', 'slug-4' ),
4552       *       ),
4553       *     )
4554       *
4555       * @since 5.9.0
4556       *
4557       * @param array $data      A theme.json like structure.
4558       * @param array $node_path The path to inspect. It's 'settings' by default.
4559       * @return array
4560       */
4561  	protected static function get_default_slugs( $data, $node_path ) {
4562          $slugs = array();
4563  
4564          foreach ( static::PRESETS_METADATA as $metadata ) {
4565              $path = $node_path;
4566              foreach ( $metadata['path'] as $leaf ) {
4567                  $path[] = $leaf;
4568              }
4569              $path[] = 'default';
4570  
4571              $preset = _wp_array_get( $data, $path, null );
4572              if ( ! isset( $preset ) ) {
4573                  continue;
4574              }
4575  
4576              $slugs_for_preset = array();
4577              foreach ( $preset as $item ) {
4578                  if ( isset( $item['slug'] ) ) {
4579                      $slugs_for_preset[] = $item['slug'];
4580                  }
4581              }
4582  
4583              _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset );
4584          }
4585  
4586          return $slugs;
4587      }
4588  
4589      /**
4590       * Gets a `default`'s preset name by a provided slug.
4591       *
4592       * @since 5.9.0
4593       *
4594       * @param string $slug The slug we want to find a match from default presets.
4595       * @param array  $base_path The path to inspect. It's 'settings' by default.
4596       * @return string|null
4597       */
4598  	protected function get_name_from_defaults( $slug, $base_path ) {
4599          $path            = $base_path;
4600          $path[]          = 'default';
4601          $default_content = _wp_array_get( $this->theme_json, $path, null );
4602          if ( ! $default_content ) {
4603              return null;
4604          }
4605          foreach ( $default_content as $item ) {
4606              if ( $slug === $item['slug'] ) {
4607                  return $item['name'];
4608              }
4609          }
4610          return null;
4611      }
4612  
4613      /**
4614       * Removes the preset values whose slug is equal to any of given slugs.
4615       *
4616       * @since 5.9.0
4617       *
4618       * @param array $node  The node with the presets to validate.
4619       * @param array $slugs The slugs that should not be overridden.
4620       * @return array The new node.
4621       */
4622  	protected static function filter_slugs( $node, $slugs ) {
4623          if ( empty( $slugs ) ) {
4624              return $node;
4625          }
4626  
4627          $new_node = array();
4628          foreach ( $node as $value ) {
4629              if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) {
4630                  $new_node[] = $value;
4631              }
4632          }
4633  
4634          return $new_node;
4635      }
4636  
4637      /**
4638       * Removes insecure data from theme.json.
4639       *
4640       * @since 5.9.0
4641       * @since 6.3.2 Preserves global styles block variations when securing styles.
4642       * @since 6.6.0 Updated to allow variation element styles and $origin parameter.
4643       *
4644       * @param array  $theme_json Structure to sanitize.
4645       * @param string $origin     Optional. What source of data this object represents.
4646       *                           One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'.
4647       * @return array Sanitized structure.
4648       */
4649  	public static function remove_insecure_properties( $theme_json, $origin = 'theme' ) {
4650          if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
4651              $origin = 'theme';
4652          }
4653  
4654          $sanitized = array();
4655  
4656          $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin );
4657  
4658          $blocks_metadata     = static::get_blocks_metadata();
4659          $valid_block_names   = array_keys( $blocks_metadata );
4660          $valid_element_names = array_keys( static::ELEMENTS );
4661          $valid_variations    = static::get_valid_block_style_variations( $blocks_metadata );
4662  
4663          $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names, $valid_variations );
4664  
4665          $blocks_metadata          = static::get_blocks_metadata();
4666          $style_options            = array( 'include_block_style_variations' => true ); // Allow variations data.
4667          $style_nodes              = static::get_style_nodes( $theme_json, $blocks_metadata, $style_options );
4668          $responsive_media_queries = static::get_viewport_media_queries( $theme_json['settings']['viewport'] ?? null );
4669  
4670          foreach ( $style_nodes as $metadata ) {
4671              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
4672              if ( empty( $input ) ) {
4673                  continue;
4674              }
4675  
4676              $block_name = in_array( 'blocks', $metadata['path'], true )
4677                  ? static::get_block_name_from_metadata_path( $metadata )
4678                  : null;
4679  
4680              // The global styles custom CSS is not sanitized, but can only be edited by users with 'edit_css' capability.
4681              if ( isset( $input['css'] ) && current_user_can( 'edit_css' ) ) {
4682                  $output = $input;
4683              } else {
4684                  $output = static::remove_insecure_styles( $input );
4685              }
4686  
4687              /*
4688               * Get a reference to element name from path.
4689               * $metadata['path'] = array( 'styles', 'elements', 'link' );
4690               */
4691              $current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ];
4692  
4693              /*
4694               * $output is stripped of pseudo selectors. Re-add and process them
4695               * or insecure styles here.
4696               */
4697              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
4698                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) {
4699                      if ( isset( $input[ $pseudo_selector ] ) ) {
4700                          $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] );
4701                      }
4702                  }
4703              }
4704  
4705              // Re-add and process responsive breakpoint styles.
4706              foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4707                  if ( isset( $input[ $breakpoint ] ) ) {
4708                      $output[ $breakpoint ] = static::remove_insecure_styles( $input[ $breakpoint ] );
4709  
4710                      if ( isset( $input[ $breakpoint ]['elements'] ) ) {
4711                          $output[ $breakpoint ]['elements'] = static::remove_insecure_element_styles( $input[ $breakpoint ]['elements'], $responsive_media_queries );
4712                      }
4713  
4714                      if ( isset( $input[ $breakpoint ]['blocks'] ) ) {
4715                          $output[ $breakpoint ]['blocks'] = static::remove_insecure_inner_block_styles( $input[ $breakpoint ]['blocks'], $responsive_media_queries );
4716                      }
4717  
4718                      if ( $block_name && isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
4719                          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
4720                              if ( isset( $input[ $breakpoint ][ $pseudo_selector ] ) ) {
4721                                  $output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $input[ $breakpoint ][ $pseudo_selector ] );
4722                              }
4723                          }
4724                      }
4725  
4726                      // Responsive custom CSS is allowed for users with 'edit_css' capability.
4727                      if ( isset( $input[ $breakpoint ]['css'] ) && current_user_can( 'edit_css' ) ) {
4728                          $output[ $breakpoint ]['css'] = $input[ $breakpoint ]['css'];
4729                      }
4730                  }
4731              }
4732  
4733              if ( ! empty( $output ) ) {
4734                  _wp_array_set( $sanitized, $metadata['path'], $output );
4735              }
4736  
4737              if ( isset( $metadata['variations'] ) ) {
4738                  foreach ( $metadata['variations'] as $variation ) {
4739                      $variation_input = _wp_array_get( $theme_json, $variation['path'], array() );
4740                      if ( empty( $variation_input ) ) {
4741                          continue;
4742                      }
4743  
4744                      $variation_output = static::remove_insecure_styles( $variation_input );
4745  
4746                      if ( isset( $variation_input['blocks'] ) ) {
4747                          $variation_output['blocks'] = static::remove_insecure_inner_block_styles( $variation_input['blocks'], $responsive_media_queries );
4748                      }
4749  
4750                      if ( isset( $variation_input['elements'] ) ) {
4751                          $variation_output['elements'] = static::remove_insecure_element_styles( $variation_input['elements'], $responsive_media_queries );
4752                      }
4753  
4754                      // Re-add and process responsive breakpoint styles for variations.
4755                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4756                          if ( isset( $variation_input[ $breakpoint ] ) ) {
4757                              $variation_output[ $breakpoint ] = static::remove_insecure_styles( $variation_input[ $breakpoint ] );
4758  
4759                              if ( isset( $variation_input[ $breakpoint ]['elements'] ) ) {
4760                                  $variation_output[ $breakpoint ]['elements'] = static::remove_insecure_element_styles( $variation_input[ $breakpoint ]['elements'], $responsive_media_queries );
4761                              }
4762  
4763                              if ( isset( $variation_input[ $breakpoint ]['blocks'] ) ) {
4764                                  $variation_output[ $breakpoint ]['blocks'] = static::remove_insecure_inner_block_styles( $variation_input[ $breakpoint ]['blocks'], $responsive_media_queries );
4765                              }
4766  
4767                              if ( $block_name && isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
4768                                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
4769                                      if ( isset( $variation_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4770                                          $variation_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $variation_input[ $breakpoint ][ $pseudo_selector ] );
4771                                      }
4772                                  }
4773                              }
4774  
4775                              // Responsive custom CSS is allowed for users with 'edit_css' capability.
4776                              if ( isset( $variation_input[ $breakpoint ]['css'] ) && current_user_can( 'edit_css' ) ) {
4777                                  $variation_output[ $breakpoint ]['css'] = $variation_input[ $breakpoint ]['css'];
4778                              }
4779                          }
4780                      }
4781  
4782                      if ( ! empty( $variation_output ) ) {
4783                          _wp_array_set( $sanitized, $variation['path'], $variation_output );
4784                      }
4785                  }
4786              }
4787          }
4788  
4789          $setting_nodes = static::get_setting_nodes( $theme_json );
4790          foreach ( $setting_nodes as $metadata ) {
4791              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
4792              if ( empty( $input ) ) {
4793                  continue;
4794              }
4795  
4796              $output = static::remove_insecure_settings( $input, array( 'settings' ) === $metadata['path'] );
4797              if ( ! empty( $output ) ) {
4798                  _wp_array_set( $sanitized, $metadata['path'], $output );
4799              }
4800          }
4801  
4802          if ( empty( $sanitized['styles'] ) ) {
4803              unset( $theme_json['styles'] );
4804          } else {
4805              $theme_json['styles'] = $sanitized['styles'];
4806          }
4807  
4808          if ( empty( $sanitized['settings'] ) ) {
4809              unset( $theme_json['settings'] );
4810          } else {
4811              $theme_json['settings'] = $sanitized['settings'];
4812          }
4813  
4814          return $theme_json;
4815      }
4816  
4817      /**
4818       * Remove insecure element styles within a variation or block.
4819       *
4820       *  * When responsive media queries are provided, nested responsive state styles
4821       * matching those viewport state keys are re-added after the base sanitization pass.
4822       *
4823       * @since 6.8.0
4824       * @since 7.1.0 Added the `$responsive_media_queries` parameter.
4825       *
4826       * @param array      $elements                 The elements to process.
4827       * @param array|null $responsive_media_queries Optional. Media queries whose keys define allowed
4828       *                                             viewport states. Default null.
4829       * @return array The sanitized elements styles.
4830       */
4831  	protected static function remove_insecure_element_styles( $elements, $responsive_media_queries = null ) {
4832          $sanitized           = array();
4833          $valid_element_names = array_keys( static::ELEMENTS );
4834  
4835          foreach ( $valid_element_names as $element_name ) {
4836              $element_input = $elements[ $element_name ] ?? null;
4837              if ( $element_input ) {
4838                  $element_output = static::remove_insecure_styles( $element_input );
4839  
4840                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
4841                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
4842                          if ( isset( $element_input[ $pseudo_selector ] ) ) {
4843                              $element_output[ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $pseudo_selector ] );
4844                          }
4845                      }
4846                  }
4847  
4848                  if ( null !== $responsive_media_queries ) {
4849                      // Re-add and process responsive breakpoint styles for elements.
4850                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4851                          if ( isset( $element_input[ $breakpoint ] ) ) {
4852                              $element_output[ $breakpoint ] = static::remove_insecure_styles( $element_input[ $breakpoint ] );
4853  
4854                              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
4855                                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
4856                                      if ( isset( $element_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4857                                          $element_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $breakpoint ][ $pseudo_selector ] );
4858                                      }
4859                                  }
4860                              }
4861                          }
4862                      }
4863                  }
4864  
4865                  $sanitized[ $element_name ] = $element_output;
4866              }
4867          }
4868          return $sanitized;
4869      }
4870  
4871      /**
4872       * Remove insecure styles from inner blocks and their elements.
4873       *
4874       * When responsive media queries are provided, nested responsive state styles
4875       * for those media-query keys are re-added after the base sanitization pass.
4876       *
4877       * @since 6.8.0
4878       * @since 7.1.0 Added the `$responsive_media_queries` parameter.
4879       *
4880       * @param array      $blocks                   The block styles to process.
4881       * @param array|null $responsive_media_queries Optional. Media queries whose keys define allowed
4882       *                                             viewport states. Default null.
4883       * @return array Sanitized block type styles.
4884       */
4885  	protected static function remove_insecure_inner_block_styles( $blocks, $responsive_media_queries = null ) {
4886          $sanitized = array();
4887          foreach ( $blocks as $block_type => $block_input ) {
4888              $block_output = static::remove_insecure_styles( $block_input );
4889  
4890              if ( isset( $block_input['elements'] ) ) {
4891                  $block_output['elements'] = static::remove_insecure_element_styles( $block_input['elements'], $responsive_media_queries );
4892              }
4893  
4894              if ( null !== $responsive_media_queries ) {
4895                  // Re-add and process responsive breakpoint styles for inner blocks.
4896                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4897                      if ( isset( $block_input[ $breakpoint ] ) ) {
4898                          $block_output[ $breakpoint ] = static::remove_insecure_styles( $block_input[ $breakpoint ] );
4899  
4900                          if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_type ] ) ) {
4901                              foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_type ] as $pseudo_selector ) {
4902                                  if ( isset( $block_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4903                                      $block_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $block_input[ $breakpoint ][ $pseudo_selector ] );
4904                                  }
4905                              }
4906                          }
4907                      }
4908                  }
4909              }
4910  
4911              $sanitized[ $block_type ] = $block_output;
4912          }
4913          return $sanitized;
4914      }
4915  
4916      /**
4917       * Preserves valid typed settings from input to output based on type markers in schema.
4918       *
4919       * Recursively iterates through the schema and validates/preserves settings
4920       * that have type markers (e.g., boolean) in VALID_SETTINGS.
4921       *
4922       * @since 7.0.0
4923       *
4924       * @param array             $input  Input settings to process.
4925       * @param array             $output Output settings array (passed by reference).
4926       * @param array             $schema Schema to validate against (typically VALID_SETTINGS).
4927       * @param array<string|int> $path   Current path in the schema (for recursive calls).
4928       */
4929  	private static function preserve_valid_typed_settings( $input, &$output, $schema, $path = array() ) {
4930          foreach ( $schema as $key => $schema_value ) {
4931              $current_path = array_merge( $path, array( $key ) );
4932  
4933              // Validate boolean type markers.
4934              if ( is_bool( $schema_value ) ) {
4935                  $value = _wp_array_get( $input, $current_path, null );
4936                  if ( is_bool( $value ) ) {
4937                      _wp_array_set( $output, $current_path, $value ); // Preserve boolean value.
4938                  }
4939              } elseif ( is_array( $schema_value ) ) {
4940                  self::preserve_valid_typed_settings( $input, $output, $schema_value, $current_path ); // Recurse into nested structure.
4941              }
4942          }
4943      }
4944  
4945      /**
4946       * Processes a setting node and returns the same node
4947       * without the insecure settings.
4948       *
4949       * @since 5.9.0
4950       * @since 7.1.0 Added the `$is_root` parameter.
4951       *
4952       * @param array $input   Node to process.
4953       * @param bool  $is_root Optional. Whether the node is the root settings node. Default false.
4954       * @return array
4955       */
4956  	protected static function remove_insecure_settings( $input, $is_root = false ) {
4957          $output = array();
4958          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
4959              foreach ( static::VALID_ORIGINS as $origin ) {
4960                  $path_with_origin   = $preset_metadata['path'];
4961                  $path_with_origin[] = $origin;
4962                  $presets            = _wp_array_get( $input, $path_with_origin, null );
4963                  if ( null === $presets ) {
4964                      continue;
4965                  }
4966  
4967                  $escaped_preset = array();
4968                  foreach ( $presets as $preset ) {
4969                      if (
4970                          esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] &&
4971                          sanitize_html_class( $preset['slug'] ) === $preset['slug']
4972                      ) {
4973                          $value = null;
4974                          if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
4975                              $value = $preset[ $preset_metadata['value_key'] ];
4976                          } elseif (
4977                              isset( $preset_metadata['value_func'] ) &&
4978                              is_callable( $preset_metadata['value_func'] )
4979                          ) {
4980                              $value = call_user_func( $preset_metadata['value_func'], $preset );
4981                          }
4982  
4983                          $preset_is_valid = true;
4984                          foreach ( $preset_metadata['properties'] as $property ) {
4985                              if ( ! static::is_safe_css_declaration( $property, $value ) ) {
4986                                  $preset_is_valid = false;
4987                                  break;
4988                              }
4989                          }
4990  
4991                          if ( $preset_is_valid ) {
4992                              $escaped_preset[] = $preset;
4993                          }
4994                      }
4995                  }
4996  
4997                  if ( ! empty( $escaped_preset ) ) {
4998                      _wp_array_set( $output, $path_with_origin, $escaped_preset );
4999                  }
5000              }
5001          }
5002  
5003          // Ensure indirect properties not included in any `PRESETS_METADATA` value are allowed.
5004          static::remove_indirect_properties( $input, $output );
5005  
5006          // Preserve all valid settings that have type markers in VALID_SETTINGS.
5007          self::preserve_valid_typed_settings( $input, $output, static::VALID_SETTINGS );
5008  
5009          if ( $is_root && array_key_exists( 'viewport', $input ) ) {
5010              $output['viewport'] = static::sanitize_viewport_settings( $input['viewport'] );
5011          }
5012  
5013          return $output;
5014      }
5015  
5016      /**
5017       * Processes a style node and returns the same node
5018       * without the insecure styles.
5019       *
5020       * @since 5.9.0
5021       *
5022       * @param array $input Node to process.
5023       * @return array
5024       */
5025  	protected static function remove_insecure_styles( $input ) {
5026          $output       = array();
5027          $declarations = static::compute_style_properties( $input );
5028  
5029          foreach ( $declarations as $declaration ) {
5030              if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) {
5031                  $path = static::PROPERTIES_METADATA[ $declaration['name'] ];
5032  
5033                  /*
5034                   * Check the value isn't an array before adding so as to not
5035                   * double up shorthand and longhand styles.
5036                   */
5037                  $value = _wp_array_get( $input, $path, array() );
5038                  if ( ! is_array( $value ) ) {
5039                      _wp_array_set( $output, $path, $value );
5040                  }
5041              }
5042          }
5043  
5044          // Ensure indirect properties not handled by `compute_style_properties` are allowed.
5045          static::remove_indirect_properties( $input, $output );
5046  
5047          return $output;
5048      }
5049  
5050      /**
5051       * Checks that a declaration provided by the user is safe.
5052       *
5053       * @since 5.9.0
5054       *
5055       * @param string $property_name  Property name in a CSS declaration, i.e. the `color` in `color: red`.
5056       * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`.
5057       * @return bool
5058       */
5059  	protected static function is_safe_css_declaration( $property_name, $property_value ) {
5060          $style_to_validate = $property_name . ': ' . $property_value;
5061          $filtered          = esc_html( safecss_filter_attr( $style_to_validate ) );
5062          return ! empty( trim( $filtered ) );
5063      }
5064  
5065      /**
5066       * Removes indirect properties from the given input node and
5067       * sets in the given output node.
5068       *
5069       * @since 6.2.0
5070       *
5071       * @param array $input  Node to process.
5072       * @param array $output The processed node. Passed by reference.
5073       */
5074  	private static function remove_indirect_properties( $input, &$output ) {
5075          foreach ( static::INDIRECT_PROPERTIES_METADATA as $property => $paths ) {
5076              foreach ( $paths as $path ) {
5077                  $value = _wp_array_get( $input, $path );
5078                  if (
5079                      is_string( $value ) &&
5080                      static::is_safe_css_declaration( $property, $value )
5081                  ) {
5082                      _wp_array_set( $output, $path, $value );
5083                  }
5084              }
5085          }
5086      }
5087  
5088      /**
5089       * Returns the raw data.
5090       *
5091       * @since 5.8.0
5092       *
5093       * @return array Raw data.
5094       */
5095  	public function get_raw_data() {
5096          return $this->theme_json;
5097      }
5098  
5099      /**
5100       * Transforms the given editor settings according the
5101       * add_theme_support format to the theme.json format.
5102       *
5103       * @since 5.8.0
5104       *
5105       * @param array $settings Existing editor settings.
5106       * @return array Config that adheres to the theme.json schema.
5107       */
5108  	public static function get_from_editor_settings( $settings ) {
5109          $theme_settings = array(
5110              'version'  => static::LATEST_SCHEMA,
5111              'settings' => array(),
5112          );
5113  
5114          // Deprecated theme supports.
5115          if ( isset( $settings['disableCustomColors'] ) ) {
5116              $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors'];
5117          }
5118  
5119          if ( isset( $settings['disableCustomGradients'] ) ) {
5120              $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients'];
5121          }
5122  
5123          if ( isset( $settings['disableCustomFontSizes'] ) ) {
5124              $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes'];
5125          }
5126  
5127          if ( isset( $settings['enableCustomLineHeight'] ) ) {
5128              $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight'];
5129          }
5130  
5131          if ( isset( $settings['enableCustomUnits'] ) ) {
5132              $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ?
5133                  array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) :
5134                  $settings['enableCustomUnits'];
5135          }
5136  
5137          if ( isset( $settings['colors'] ) ) {
5138              $theme_settings['settings']['color']['palette'] = $settings['colors'];
5139          }
5140  
5141          if ( isset( $settings['gradients'] ) ) {
5142              $theme_settings['settings']['color']['gradients'] = $settings['gradients'];
5143          }
5144  
5145          if ( isset( $settings['fontSizes'] ) ) {
5146              $font_sizes = $settings['fontSizes'];
5147              // Back-compatibility for presets without units.
5148              foreach ( $font_sizes as $key => $font_size ) {
5149                  if ( is_numeric( $font_size['size'] ) ) {
5150                      $font_sizes[ $key ]['size'] = $font_size['size'] . 'px';
5151                  }
5152              }
5153              $theme_settings['settings']['typography']['fontSizes'] = $font_sizes;
5154          }
5155  
5156          if ( isset( $settings['enableCustomSpacing'] ) ) {
5157              $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing'];
5158          }
5159  
5160          if ( isset( $settings['spacingSizes'] ) ) {
5161              $theme_settings['settings']['spacing']['spacingSizes'] = $settings['spacingSizes'];
5162          }
5163  
5164          return $theme_settings;
5165      }
5166  
5167      /**
5168       * Returns the current theme's wanted patterns(slugs) to be
5169       * registered from Pattern Directory.
5170       *
5171       * @since 6.0.0
5172       *
5173       * @return string[]
5174       */
5175  	public function get_patterns() {
5176          if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) {
5177              return $this->theme_json['patterns'];
5178          }
5179          return array();
5180      }
5181  
5182      /**
5183       * Returns a valid theme.json as provided by a theme.
5184       *
5185       * Unlike get_raw_data() this returns the presets flattened, as provided by a theme.
5186       * This also uses appearanceTools instead of their opt-ins if all of them are true.
5187       *
5188       * @since 6.0.0
5189       *
5190       * @return array
5191       */
5192  	public function get_data() {
5193          $output = $this->theme_json;
5194          $nodes  = static::get_setting_nodes( $output );
5195  
5196          /**
5197           * Flatten the theme & custom origins into a single one.
5198           *
5199           * For example, the following:
5200           *
5201           * {
5202           *   "settings": {
5203           *     "color": {
5204           *       "palette": {
5205           *         "theme": [ {} ],
5206           *         "custom": [ {} ]
5207           *       }
5208           *     }
5209           *   }
5210           * }
5211           *
5212           * will be converted to:
5213           *
5214           * {
5215           *   "settings": {
5216           *     "color": {
5217           *       "palette": [ {} ]
5218           *     }
5219           *   }
5220           * }
5221           */
5222          foreach ( $nodes as $node ) {
5223              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
5224                  $path = $node['path'];
5225                  foreach ( $preset_metadata['path'] as $preset_metadata_path ) {
5226                      $path[] = $preset_metadata_path;
5227                  }
5228                  $preset = _wp_array_get( $output, $path, null );
5229                  if ( null === $preset ) {
5230                      continue;
5231                  }
5232  
5233                  $items = array();
5234                  if ( isset( $preset['theme'] ) ) {
5235                      foreach ( $preset['theme'] as $item ) {
5236                          $slug = $item['slug'];
5237                          unset( $item['slug'] );
5238                          $items[ $slug ] = $item;
5239                      }
5240                  }
5241                  if ( isset( $preset['custom'] ) ) {
5242                      foreach ( $preset['custom'] as $item ) {
5243                          $slug = $item['slug'];
5244                          unset( $item['slug'] );
5245                          $items[ $slug ] = $item;
5246                      }
5247                  }
5248                  $flattened_preset = array();
5249                  foreach ( $items as $slug => $value ) {
5250                      $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value );
5251                  }
5252                  _wp_array_set( $output, $path, $flattened_preset );
5253              }
5254          }
5255  
5256          /*
5257           * If all of the static::APPEARANCE_TOOLS_OPT_INS are true,
5258           * this code unsets them and sets 'appearanceTools' instead.
5259           */
5260          foreach ( $nodes as $node ) {
5261              $all_opt_ins_are_set = true;
5262              foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
5263                  $full_path = $node['path'];
5264                  foreach ( $opt_in_path as $opt_in_path_item ) {
5265                      $full_path[] = $opt_in_path_item;
5266                  }
5267                  /*
5268                   * Use "unset prop" as a marker instead of "null" because
5269                   * "null" can be a valid value for some props (e.g. blockGap).
5270                   */
5271                  $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
5272                  if ( 'unset prop' === $opt_in_value ) {
5273                      $all_opt_ins_are_set = false;
5274                      break;
5275                  }
5276              }
5277  
5278              if ( $all_opt_ins_are_set ) {
5279                  $node_path_with_appearance_tools   = $node['path'];
5280                  $node_path_with_appearance_tools[] = 'appearanceTools';
5281                  _wp_array_set( $output, $node_path_with_appearance_tools, true );
5282                  foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
5283                      $full_path = $node['path'];
5284                      foreach ( $opt_in_path as $opt_in_path_item ) {
5285                          $full_path[] = $opt_in_path_item;
5286                      }
5287                      /*
5288                       * Use "unset prop" as a marker instead of "null" because
5289                       * "null" can be a valid value for some props (e.g. blockGap).
5290                       */
5291                      $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
5292                      if ( true !== $opt_in_value ) {
5293                          continue;
5294                      }
5295  
5296                      /*
5297                       * The following could be improved to be path independent.
5298                       * At the moment it relies on a couple of assumptions:
5299                       *
5300                       * - all opt-ins having a path of size 2.
5301                       * - there's two sources of settings: the top-level and the block-level.
5302                       */
5303                      if (
5304                          ( 1 === count( $node['path'] ) ) &&
5305                          ( 'settings' === $node['path'][0] )
5306                      ) {
5307                          // Top-level settings.
5308                          unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] );
5309                          if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) {
5310                              unset( $output['settings'][ $opt_in_path[0] ] );
5311                          }
5312                      } elseif (
5313                          ( 3 === count( $node['path'] ) ) &&
5314                          ( 'settings' === $node['path'][0] ) &&
5315                          ( 'blocks' === $node['path'][1] )
5316                      ) {
5317                          // Block-level settings.
5318                          $block_name = $node['path'][2];
5319                          unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] );
5320                          if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) {
5321                              unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] );
5322                          }
5323                      }
5324                  }
5325              }
5326          }
5327  
5328          wp_recursive_ksort( $output );
5329  
5330          return $output;
5331      }
5332  
5333      /**
5334       * Sets the spacingSizes array based on the spacingScale values from theme.json.
5335       *
5336       * @since 6.1.0
5337       * @deprecated 6.6.0 No longer used as the spacingSizes are automatically
5338       *                   generated in the constructor and merge methods instead
5339       *                   of manually after instantiation.
5340       *
5341       * @return void
5342       */
5343  	public function set_spacing_sizes() {
5344          _deprecated_function( __METHOD__, '6.6.0' );
5345  
5346          $spacing_scale = $this->theme_json['settings']['spacing']['spacingScale'] ?? array();
5347  
5348          if ( ! isset( $spacing_scale['steps'] )
5349              || ! is_numeric( $spacing_scale['steps'] )
5350              || ! isset( $spacing_scale['mediumStep'] )
5351              || ! isset( $spacing_scale['unit'] )
5352              || ! isset( $spacing_scale['operator'] )
5353              || ! isset( $spacing_scale['increment'] )
5354              || ! isset( $spacing_scale['steps'] )
5355              || ! is_numeric( $spacing_scale['increment'] )
5356              || ! is_numeric( $spacing_scale['mediumStep'] )
5357              || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) {
5358              if ( ! empty( $spacing_scale ) ) {
5359                  wp_trigger_error(
5360                      __METHOD__,
5361                      sprintf(
5362                          /* translators: 1: theme.json, 2: settings.spacing.spacingScale */
5363                          __( 'Some of the %1$s %2$s values are invalid' ),
5364                          'theme.json',
5365                          'settings.spacing.spacingScale'
5366                      ),
5367                      E_USER_NOTICE
5368                  );
5369              }
5370              return;
5371          }
5372  
5373          // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0.
5374          if ( 0 === $spacing_scale['steps'] ) {
5375              return;
5376          }
5377  
5378          $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
5379  
5380          // If there are 7 or fewer steps in the scale revert to numbers for labels instead of t-shirt sizes.
5381          if ( $spacing_scale['steps'] <= 7 ) {
5382              for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) {
5383                  $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 );
5384              }
5385          }
5386  
5387          _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes );
5388      }
5389  
5390      /**
5391       * Merges two sets of spacing size presets.
5392       *
5393       * @since 6.6.0
5394       *
5395       * @param array $base     The base set of spacing sizes.
5396       * @param array $incoming The set of spacing sizes to merge with the base. Duplicate slugs will override the base values.
5397       * @return array The merged set of spacing sizes.
5398       */
5399  	private static function merge_spacing_sizes( $base, $incoming ) {
5400          // Preserve the order if there are no base (spacingScale) values.
5401          if ( empty( $base ) ) {
5402              return $incoming;
5403          }
5404          $merged = array();
5405          foreach ( $base as $item ) {
5406              $merged[ $item['slug'] ] = $item;
5407          }
5408          foreach ( $incoming as $item ) {
5409              $merged[ $item['slug'] ] = $item;
5410          }
5411          ksort( $merged, SORT_NUMERIC );
5412          return array_values( $merged );
5413      }
5414  
5415      /**
5416       * Generates a set of spacing sizes by starting with a medium size and
5417       * applying an operator with an increment value to generate the rest of the
5418       * sizes outward from the medium size. The medium slug is '50' with the rest
5419       * of the slugs being 10 apart. The generated names use t-shirt sizing.
5420       *
5421       * Example:
5422       *
5423       *     $spacing_scale = array(
5424       *         'steps'      => 4,
5425       *         'mediumStep' => 16,
5426       *         'unit'       => 'px',
5427       *         'operator'   => '+',
5428       *         'increment'  => 2,
5429       *     );
5430       *     $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
5431       *     // -> array(
5432       *     //        array( 'name' => 'Small',   'slug' => '40', 'size' => '14px' ),
5433       *     //        array( 'name' => 'Medium',  'slug' => '50', 'size' => '16px' ),
5434       *     //        array( 'name' => 'Large',   'slug' => '60', 'size' => '18px' ),
5435       *     //        array( 'name' => 'X-Large', 'slug' => '70', 'size' => '20px' ),
5436       *     //    )
5437       *
5438       * @since 6.6.0
5439       *
5440       * @param array $spacing_scale {
5441       *      The spacing scale values. All are required.
5442       *
5443       *      @type int    $steps      The number of steps in the scale. (up to 10 steps are supported.)
5444       *      @type float  $mediumStep The middle value that gets the slug '50'. (For even number of steps, this becomes the first middle value.)
5445       *      @type string $unit       The CSS unit to use for the sizes.
5446       *      @type string $operator   The mathematical operator to apply to generate the other sizes. Either '+' or '*'.
5447       *      @type float  $increment  The value used with the operator to generate the other sizes.
5448       * }
5449       * @return array The spacing sizes presets or an empty array if some spacing scale values are missing or invalid.
5450       */
5451  	private static function compute_spacing_sizes( $spacing_scale ) {
5452          /*
5453           * This condition is intentionally missing some checks on ranges for the values in order to
5454           * keep backwards compatibility with the previous implementation.
5455           */
5456          if (
5457              ! isset( $spacing_scale['steps'] ) ||
5458              ! is_numeric( $spacing_scale['steps'] ) ||
5459              0 === $spacing_scale['steps'] ||
5460              ! isset( $spacing_scale['mediumStep'] ) ||
5461              ! is_numeric( $spacing_scale['mediumStep'] ) ||
5462              ! isset( $spacing_scale['unit'] ) ||
5463              ! isset( $spacing_scale['operator'] ) ||
5464              ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ||
5465              ! isset( $spacing_scale['increment'] ) ||
5466              ! is_numeric( $spacing_scale['increment'] )
5467          ) {
5468              return array();
5469          }
5470  
5471          $unit            = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] );
5472          $current_step    = $spacing_scale['mediumStep'];
5473          $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 );
5474          $x_small_count   = null;
5475          $below_sizes     = array();
5476          $slug            = 40;
5477          $remainder       = 0;
5478  
5479          for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) {
5480              if ( '+' === $spacing_scale['operator'] ) {
5481                  $current_step -= $spacing_scale['increment'];
5482              } elseif ( $spacing_scale['increment'] > 1 ) {
5483                  $current_step /= $spacing_scale['increment'];
5484              } else {
5485                  $current_step *= $spacing_scale['increment'];
5486              }
5487  
5488              if ( $current_step <= 0 ) {
5489                  $remainder = $below_midpoint_count;
5490                  break;
5491              }
5492  
5493              $below_sizes[] = array(
5494                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */
5495                  'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ),
5496                  'slug' => (string) $slug,
5497                  'size' => round( $current_step, 2 ) . $unit,
5498              );
5499  
5500              if ( $below_midpoint_count === $steps_mid_point - 2 ) {
5501                  $x_small_count = 2;
5502              }
5503  
5504              if ( $below_midpoint_count < $steps_mid_point - 2 ) {
5505                  ++$x_small_count;
5506              }
5507  
5508              $slug -= 10;
5509          }
5510  
5511          $below_sizes = array_reverse( $below_sizes );
5512  
5513          $below_sizes[] = array(
5514              'name' => __( 'Medium' ),
5515              'slug' => '50',
5516              'size' => $spacing_scale['mediumStep'] . $unit,
5517          );
5518  
5519          $current_step  = $spacing_scale['mediumStep'];
5520          $x_large_count = null;
5521          $above_sizes   = array();
5522          $slug          = 60;
5523          $steps_above   = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder;
5524  
5525          for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) {
5526              $current_step = '+' === $spacing_scale['operator']
5527                  ? $current_step + $spacing_scale['increment']
5528                  : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] );
5529  
5530              $above_sizes[] = array(
5531                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */
5532                  'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ),
5533                  'slug' => (string) $slug,
5534                  'size' => round( $current_step, 2 ) . $unit,
5535              );
5536  
5537              if ( 1 === $above_midpoint_count ) {
5538                  $x_large_count = 2;
5539              }
5540  
5541              if ( $above_midpoint_count > 1 ) {
5542                  ++$x_large_count;
5543              }
5544  
5545              $slug += 10;
5546          }
5547  
5548          $spacing_sizes = $below_sizes;
5549          foreach ( $above_sizes as $above_sizes_item ) {
5550              $spacing_sizes[] = $above_sizes_item;
5551          }
5552  
5553          return $spacing_sizes;
5554      }
5555  
5556      /**
5557       * This is used to convert the internal representation of variables to the CSS representation.
5558       * For example, `var:preset|color|vivid-green-cyan` becomes `var(--wp--preset--color--vivid-green-cyan)`.
5559       *
5560       * @since 6.3.0
5561       *
5562       * @param string $value The variable such as var:preset|color|vivid-green-cyan to convert.
5563       * @return string The converted variable.
5564       */
5565  	private static function convert_custom_properties( $value ) {
5566          $prefix     = 'var:';
5567          $prefix_len = strlen( $prefix );
5568          $token_in   = '|';
5569          $token_out  = '--';
5570          if ( str_starts_with( $value, $prefix ) ) {
5571              $unwrapped_name = str_replace(
5572                  $token_in,
5573                  $token_out,
5574                  substr( $value, $prefix_len )
5575              );
5576              $value          = "var(--wp--$unwrapped_name)";
5577          }
5578  
5579          return $value;
5580      }
5581  
5582      /**
5583       * Given a tree, converts the internal representation of variables to the CSS representation.
5584       * It is recursive and modifies the input in-place.
5585       *
5586       * @since 6.3.0
5587       *
5588       * @param array $tree Input to process.
5589       * @return array The modified $tree.
5590       */
5591  	private static function resolve_custom_css_format( $tree ) {
5592          $prefix = 'var:';
5593  
5594          foreach ( $tree as $key => $data ) {
5595              if ( is_string( $data ) && str_starts_with( $data, $prefix ) ) {
5596                  $tree[ $key ] = self::convert_custom_properties( $data );
5597              } elseif ( is_array( $data ) ) {
5598                  $tree[ $key ] = self::resolve_custom_css_format( $data );
5599              }
5600          }
5601  
5602          return $tree;
5603      }
5604  
5605      /**
5606       * Returns the selectors metadata for a block.
5607       *
5608       * @since 6.3.0
5609       *
5610       * @param object $block_type    The block type.
5611       * @param string $root_selector The block's root selector.
5612       * @return array The custom selectors set by the block.
5613       */
5614  	protected static function get_block_selectors( $block_type, $root_selector ) {
5615          if ( ! empty( $block_type->selectors ) ) {
5616              return $block_type->selectors;
5617          }
5618  
5619          $selectors = array( 'root' => $root_selector );
5620          foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) {
5621              $feature_selector = wp_get_block_css_selector( $block_type, $key );
5622              if ( null !== $feature_selector ) {
5623                  $selectors[ $feature ] = array( 'root' => $feature_selector );
5624              }
5625          }
5626  
5627          return $selectors;
5628      }
5629  
5630      /**
5631       * Generates all the element selectors for a block.
5632       *
5633       * @since 6.3.0
5634       *
5635       * @param string $root_selector The block's root CSS selector.
5636       * @return array The block's element selectors.
5637       */
5638  	protected static function get_block_element_selectors( $root_selector ) {
5639          /*
5640           * Assign defaults, then override those that the block sets by itself.
5641           * If the block selector is compounded, will append the element to each
5642           * individual block selector.
5643           */
5644          $block_selectors   = explode( ',', $root_selector );
5645          $element_selectors = array();
5646          foreach ( static::ELEMENTS as $el_name => $el_selector ) {
5647              $element_selector = array();
5648              foreach ( $block_selectors as $selector ) {
5649                  if ( $selector === $el_selector ) {
5650                      $element_selector = array( $el_selector );
5651                      break;
5652                  }
5653                  $element_selector[] = static::prepend_to_selector( $el_selector, $selector . ' ' );
5654              }
5655              $element_selectors[ $el_name ] = implode( ',', $element_selector );
5656          }
5657  
5658          return $element_selectors;
5659      }
5660  
5661      /**
5662       * Generates style declarations for a node's features e.g., color, border,
5663       * typography etc. that have custom selectors in their related block's
5664       * metadata.
5665       *
5666       * @since 6.3.0
5667       *
5668       * @param object $metadata The related block metadata containing selectors.
5669       * @param object $node     A merged theme.json node for block or variation.
5670       * @return array The style declarations for the node's features with custom
5671       *               selectors.
5672       */
5673  	protected function get_feature_declarations_for_node( $metadata, &$node ) {
5674          $declarations = array();
5675  
5676          if ( ! isset( $metadata['selectors'] ) ) {
5677              return $declarations;
5678          }
5679  
5680          $settings = $this->theme_json['settings'] ?? array();
5681  
5682          foreach ( $metadata['selectors'] as $feature => $feature_selectors ) {
5683              /*
5684               * Skip if this is the block's root selector, the custom CSS
5685               * selector, or the block doesn't have any styles for the feature.
5686               */
5687              if ( 'root' === $feature || 'css' === $feature || empty( $node[ $feature ] ) ) {
5688                  continue;
5689              }
5690  
5691              if ( is_array( $feature_selectors ) ) {
5692                  foreach ( $feature_selectors as $subfeature => $subfeature_selector ) {
5693                      if ( 'root' === $subfeature || empty( $node[ $feature ][ $subfeature ] ) ) {
5694                          continue;
5695                      }
5696  
5697                      /*
5698                       * Create temporary node containing only the subfeature data
5699                       * to leverage existing `compute_style_properties` function.
5700                       */
5701                      $subfeature_node = array(
5702                          $feature => array(
5703                              $subfeature => $node[ $feature ][ $subfeature ],
5704                          ),
5705                      );
5706  
5707                      // Generate style declarations.
5708                      $new_declarations = static::compute_style_properties( $subfeature_node, $settings, null, $this->theme_json );
5709  
5710                      // Merge subfeature declarations into feature declarations.
5711                      if ( isset( $declarations[ $subfeature_selector ] ) ) {
5712                          foreach ( $new_declarations as $new_declaration ) {
5713                              $declarations[ $subfeature_selector ][] = $new_declaration;
5714                          }
5715                      } else {
5716                          $declarations[ $subfeature_selector ] = $new_declarations;
5717                      }
5718  
5719                      /*
5720                       * Remove the subfeature from the block's node now its
5721                       * styles will be included under its own selector not the
5722                       * block's.
5723                       */
5724                      unset( $node[ $feature ][ $subfeature ] );
5725                  }
5726              }
5727  
5728              /*
5729               * Now subfeatures have been processed and removed we can process
5730               * feature root selector or simple string selector.
5731               */
5732              if (
5733                  is_string( $feature_selectors ) ||
5734                  ( isset( $feature_selectors['root'] ) && $feature_selectors['root'] )
5735              ) {
5736                  $feature_selector = is_string( $feature_selectors ) ? $feature_selectors : $feature_selectors['root'];
5737  
5738                  /*
5739                   * Create temporary node containing only the feature data
5740                   * to leverage existing `compute_style_properties` function.
5741                   */
5742                  $feature_node = array( $feature => $node[ $feature ] );
5743  
5744                  // Generate the style declarations.
5745                  $new_declarations = static::compute_style_properties( $feature_node, $settings, null, $this->theme_json );
5746  
5747                  /*
5748                   * Merge new declarations with any that already exist for
5749                   * the feature selector. This may occur when multiple block
5750                   * support features use the same custom selector.
5751                   */
5752                  if ( isset( $declarations[ $feature_selector ] ) ) {
5753                      foreach ( $new_declarations as $new_declaration ) {
5754                          $declarations[ $feature_selector ][] = $new_declaration;
5755                      }
5756                  } else {
5757                      $declarations[ $feature_selector ] = $new_declarations;
5758                  }
5759  
5760                  /*
5761                   * Remove the feature from the block's node now its styles
5762                   * will be included under its own selector not the block's.
5763                   */
5764                  unset( $node[ $feature ] );
5765              }
5766          }
5767  
5768          return $declarations;
5769      }
5770  
5771      /**
5772       * Replaces CSS variables with their values in place.
5773       *
5774       * @since 6.3.0
5775       * @since 6.5.0 Check for empty style before processing its value.
5776       *
5777       * @param array $styles CSS declarations to convert.
5778       * @param array $values key => value pairs to use for replacement.
5779       * @return array
5780       */
5781  	private static function convert_variables_to_value( $styles, $values ) {
5782          foreach ( $styles as $key => $style ) {
5783              if ( empty( $style ) ) {
5784                  continue;
5785              }
5786  
5787              if ( is_array( $style ) ) {
5788                  $styles[ $key ] = self::convert_variables_to_value( $style, $values );
5789                  continue;
5790              }
5791  
5792              if ( 0 <= strpos( $style, 'var(' ) ) {
5793                  // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group.
5794  
5795                  $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts );
5796  
5797                  if ( $has_matches ) {
5798                      $resolved_style = $styles[ $key ];
5799                      foreach ( $var_parts[1] as $index => $var_part ) {
5800                          $key_in_values   = 'var(' . $var_part . ')';
5801                          $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan).
5802                          $fallback        = $var_parts[2][ $index ]; // the fallback value.
5803                          $resolved_style  = str_replace(
5804                              array(
5805                                  $rule_to_replace,
5806                                  $fallback,
5807                              ),
5808                              array(
5809                                  $values[ $key_in_values ] ?? $rule_to_replace,
5810                                  $values[ $fallback ] ?? $fallback,
5811                              ),
5812                              $resolved_style
5813                          );
5814                      }
5815                      $styles[ $key ] = $resolved_style;
5816                  }
5817              }
5818          }
5819  
5820          return $styles;
5821      }
5822  
5823      /**
5824       * Resolves the values of CSS variables in the given styles.
5825       *
5826       * @since 6.3.0
5827       *
5828       * @param WP_Theme_JSON $theme_json The theme json resolver.
5829       * @return WP_Theme_JSON The $theme_json with resolved variables.
5830       */
5831  	public static function resolve_variables( $theme_json ) {
5832          $settings    = $theme_json->get_settings();
5833          $styles      = $theme_json->get_raw_data()['styles'];
5834          $preset_vars = static::compute_preset_vars( $settings, static::VALID_ORIGINS );
5835          $theme_vars  = static::compute_theme_vars( $settings );
5836          $vars        = array_reduce(
5837              array_merge( $preset_vars, $theme_vars ),
5838              function ( $carry, $item ) {
5839                  $name                    = $item['name'];
5840                  $carry[ "var({$name})" ] = $item['value'];
5841                  return $carry;
5842              },
5843              array()
5844          );
5845  
5846          $theme_json->theme_json['styles'] = self::convert_variables_to_value( $styles, $vars );
5847          return $theme_json;
5848      }
5849  
5850      /**
5851       * Generates a selector for a block style variation.
5852       *
5853       * @since 6.5.0
5854       *
5855       * @param string $variation_name Name of the block style variation.
5856       * @param string $block_selector CSS selector for the block.
5857       * @return string Block selector with block style variation selector added to it.
5858       */
5859  	protected static function get_block_style_variation_selector( $variation_name, $block_selector ) {
5860          $variation_class = ".is-style-$variation_name";
5861  
5862          if ( ! $block_selector ) {
5863              return $variation_class;
5864          }
5865  
5866          $limit          = 1;
5867          $selector_parts = static::split_selector_list( $block_selector );
5868          $result         = array();
5869  
5870          /*
5871           * Append the variation class to each selector's ancestor: the first
5872           * run of characters before any combinator (whitespace) or pseudo-class
5873           * (`:`). Only the first match is replaced.
5874           *
5875           * Examples ("custom" variation):
5876           * - `.wp-block`              => `.wp-block.is-style-custom`
5877           * - `.wp-block .inner`       => `.wp-block.is-style-custom .inner`
5878           * - `.wp-block:where(.a .b)` => `.wp-block.is-style-custom:where(.a .b)`
5879           * - `:where(.outer .inner)`  => `:where(.outer.is-style-custom .inner)`
5880           */
5881          foreach ( $selector_parts as $part ) {
5882              $result[] = preg_replace_callback(
5883                  '/[^\s:]+/',
5884                  function ( $matches ) use ( $variation_class ) {
5885                      return $matches[0] . $variation_class;
5886                  },
5887                  $part,
5888                  $limit
5889              );
5890          }
5891  
5892          return implode( ', ', $result );
5893      }
5894  
5895      /**
5896       * Applies a block style variation class to a feature selector.
5897       *
5898       * Feature selectors can target a different element than the block's root
5899       * selector. For example, the Button block's root selector targets the inner
5900       * link, while its dimensions width selector targets the outer wrapper. Apply
5901       * the variation class directly to the selector that will receive the
5902       * declarations instead of deriving it by subtracting the root selector from
5903       * the feature selector.
5904       *
5905       * @since 7.0.0
5906       *
5907       * @param array  $style_variation Style variation metadata.
5908       * @param string $feature_selector CSS selector for the feature.
5909       * @return string Feature selector with block style variation selector added.
5910       */
5911  	protected static function get_block_style_variation_feature_selector( $style_variation, $feature_selector ) {
5912          $variation_path = $style_variation['path'] ?? array();
5913          $variation_name = $style_variation['name'] ?? ( is_array( $variation_path ) ? end( $variation_path ) : null );
5914  
5915          if ( ! $variation_name ) {
5916              return $style_variation['selector'] ?? $feature_selector;
5917          }
5918  
5919          $variation_class = ".is-style-$variation_name";
5920          $selector_parts  = static::split_selector_list( $feature_selector );
5921          $selector_parts  = array_map(
5922              static function ( $selector ) use ( $variation_class ) {
5923                  $prefix = $variation_class . ' ';
5924  
5925                  if ( str_starts_with( $selector, $prefix ) ) {
5926                      return substr( $selector, strlen( $prefix ) );
5927                  }
5928  
5929                  return $selector;
5930              },
5931              $selector_parts
5932          );
5933  
5934          return static::get_block_style_variation_selector(
5935              $variation_name,
5936              implode( ', ', $selector_parts )
5937          );
5938      }
5939  
5940      /**
5941       * Collects valid block style variations keyed by block type.
5942       *
5943       * @since 6.6.0
5944       * @since 6.8.0 Added the `$blocks_metadata` parameter.
5945       *
5946       * @param array $blocks_metadata Optional. List of metadata per block. Default is the metadata for all blocks.
5947       * @return array Valid block style variations by block type.
5948       */
5949  	protected static function get_valid_block_style_variations( $blocks_metadata = array() ) {
5950          $valid_variations = array();
5951          $blocks_metadata  = empty( $blocks_metadata ) ? static::get_blocks_metadata() : $blocks_metadata;
5952          foreach ( $blocks_metadata as $block_name => $block_meta ) {
5953              if ( ! isset( $block_meta['styleVariations'] ) ) {
5954                  continue;
5955              }
5956              $valid_variations[ $block_name ] = array_keys( $block_meta['styleVariations'] );
5957          }
5958  
5959          return $valid_variations;
5960      }
5961  
5962      /**
5963       * Extracts the block name from the block metadata path.
5964       *
5965       * @since 7.1.0
5966       *
5967       * @param array $block_metadata Block metadata.
5968       * @return string|null The block name or null if not found.
5969       */
5970  	private static function get_block_name_from_metadata_path( $block_metadata ) {
5971          return $block_metadata['path'][2] ?? null;
5972      }
5973  }


Generated : Thu Jul 30 08:20:17 2026 Cross-referenced by PHPXref