[ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
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 * @var array 130 */ 131 const PRESETS_METADATA = array( 132 array( 133 'path' => array( 'dimensions', 'aspectRatios' ), 134 'prevent_override' => array( 'dimensions', 'defaultAspectRatios' ), 135 'use_default_names' => false, 136 'value_key' => 'ratio', 137 'css_vars' => '--wp--preset--aspect-ratio--$slug', 138 'classes' => array(), 139 'properties' => array( 'aspect-ratio' ), 140 ), 141 array( 142 'path' => array( 'color', 'palette' ), 143 'prevent_override' => array( 'color', 'defaultPalette' ), 144 'use_default_names' => false, 145 'value_key' => 'color', 146 'css_vars' => '--wp--preset--color--$slug', 147 'classes' => array( 148 '.has-$slug-color' => 'color', 149 '.has-$slug-background-color' => 'background-color', 150 '.has-$slug-border-color' => 'border-color', 151 ), 152 'properties' => array( 'color', 'background-color', 'border-color' ), 153 ), 154 array( 155 'path' => array( 'color', 'gradients' ), 156 'prevent_override' => array( 'color', 'defaultGradients' ), 157 'use_default_names' => false, 158 'value_key' => 'gradient', 159 'css_vars' => '--wp--preset--gradient--$slug', 160 'classes' => array( '.has-$slug-gradient-background' => 'background' ), 161 'properties' => array( 'background' ), 162 ), 163 array( 164 'path' => array( 'color', 'duotone' ), 165 'prevent_override' => array( 'color', 'defaultDuotone' ), 166 'use_default_names' => false, 167 'value_func' => null, // CSS Custom Properties for duotone are handled by block supports in class-wp-duotone.php. 168 'css_vars' => null, 169 'classes' => array(), 170 'properties' => array( 'filter' ), 171 ), 172 array( 173 'path' => array( 'typography', 'fontSizes' ), 174 'prevent_override' => array( 'typography', 'defaultFontSizes' ), 175 'use_default_names' => true, 176 'value_func' => 'wp_get_typography_font_size_value', 177 'css_vars' => '--wp--preset--font-size--$slug', 178 'classes' => array( '.has-$slug-font-size' => 'font-size' ), 179 'properties' => array( 'font-size' ), 180 ), 181 array( 182 'path' => array( 'typography', 'fontFamilies' ), 183 'prevent_override' => false, 184 'use_default_names' => false, 185 'value_key' => 'fontFamily', 186 'css_vars' => '--wp--preset--font-family--$slug', 187 'classes' => array( '.has-$slug-font-family' => 'font-family' ), 188 'properties' => array( 'font-family' ), 189 ), 190 array( 191 'path' => array( 'spacing', 'spacingSizes' ), 192 'prevent_override' => array( 'spacing', 'defaultSpacingSizes' ), 193 'use_default_names' => true, 194 'value_key' => 'size', 195 'css_vars' => '--wp--preset--spacing--$slug', 196 'classes' => array(), 197 'properties' => array( 'padding', 'margin' ), 198 ), 199 array( 200 'path' => array( 'shadow', 'presets' ), 201 'prevent_override' => array( 'shadow', 'defaultPresets' ), 202 'use_default_names' => false, 203 'value_key' => 'shadow', 204 'css_vars' => '--wp--preset--shadow--$slug', 205 'classes' => array(), 206 'properties' => array( 'box-shadow' ), 207 ), 208 ); 209 210 /** 211 * Metadata for style properties. 212 * 213 * Each element is a direct mapping from the CSS property name to the 214 * path to the value in theme.json & block attributes. 215 * 216 * @since 5.8.0 217 * @since 5.9.0 Added the `border-*`, `font-family`, `font-style`, `font-weight`, 218 * `letter-spacing`, `margin-*`, `padding-*`, `--wp--style--block-gap`, 219 * `text-decoration`, `text-transform`, and `filter` properties, 220 * simplified the metadata structure. 221 * @since 6.1.0 Added the `border-*-color`, `border-*-width`, `border-*-style`, 222 * `--wp--style--root--padding-*`, and `box-shadow` properties, 223 * removed the `--wp--style--block-gap` property. 224 * @since 6.2.0 Added `outline-*`, and `min-height` properties. 225 * @since 6.3.0 Added `column-count` property. 226 * @since 6.4.0 Added `writing-mode` property. 227 * @since 6.5.0 Added `aspect-ratio` property. 228 * @since 6.6.0 Added `background-[image|position|repeat|size]` properties. 229 * @since 6.7.0 Added `background-attachment` property. 230 * @var array 231 */ 232 const PROPERTIES_METADATA = array( 233 'aspect-ratio' => array( 'dimensions', 'aspectRatio' ), 234 'background' => array( 'color', 'gradient' ), 235 'background-color' => array( 'color', 'background' ), 236 'background-image' => array( 'background', 'backgroundImage' ), 237 'background-position' => array( 'background', 'backgroundPosition' ), 238 'background-repeat' => array( 'background', 'backgroundRepeat' ), 239 'background-size' => array( 'background', 'backgroundSize' ), 240 'background-attachment' => array( 'background', 'backgroundAttachment' ), 241 'border-radius' => array( 'border', 'radius' ), 242 'border-top-left-radius' => array( 'border', 'radius', 'topLeft' ), 243 'border-top-right-radius' => array( 'border', 'radius', 'topRight' ), 244 'border-bottom-left-radius' => array( 'border', 'radius', 'bottomLeft' ), 245 'border-bottom-right-radius' => array( 'border', 'radius', 'bottomRight' ), 246 'border-color' => array( 'border', 'color' ), 247 'border-width' => array( 'border', 'width' ), 248 'border-style' => array( 'border', 'style' ), 249 'border-top-color' => array( 'border', 'top', 'color' ), 250 'border-top-width' => array( 'border', 'top', 'width' ), 251 'border-top-style' => array( 'border', 'top', 'style' ), 252 'border-right-color' => array( 'border', 'right', 'color' ), 253 'border-right-width' => array( 'border', 'right', 'width' ), 254 'border-right-style' => array( 'border', 'right', 'style' ), 255 'border-bottom-color' => array( 'border', 'bottom', 'color' ), 256 'border-bottom-width' => array( 'border', 'bottom', 'width' ), 257 'border-bottom-style' => array( 'border', 'bottom', 'style' ), 258 'border-left-color' => array( 'border', 'left', 'color' ), 259 'border-left-width' => array( 'border', 'left', 'width' ), 260 'border-left-style' => array( 'border', 'left', 'style' ), 261 'color' => array( 'color', 'text' ), 262 'text-align' => array( 'typography', 'textAlign' ), 263 'column-count' => array( 'typography', 'textColumns' ), 264 'font-family' => array( 'typography', 'fontFamily' ), 265 'font-size' => array( 'typography', 'fontSize' ), 266 'font-style' => array( 'typography', 'fontStyle' ), 267 'font-weight' => array( 'typography', 'fontWeight' ), 268 'letter-spacing' => array( 'typography', 'letterSpacing' ), 269 'line-height' => array( 'typography', 'lineHeight' ), 270 'margin' => array( 'spacing', 'margin' ), 271 'margin-top' => array( 'spacing', 'margin', 'top' ), 272 'margin-right' => array( 'spacing', 'margin', 'right' ), 273 'margin-bottom' => array( 'spacing', 'margin', 'bottom' ), 274 'margin-left' => array( 'spacing', 'margin', 'left' ), 275 'min-height' => array( 'dimensions', 'minHeight' ), 276 'outline-color' => array( 'outline', 'color' ), 277 'outline-offset' => array( 'outline', 'offset' ), 278 'outline-style' => array( 'outline', 'style' ), 279 'outline-width' => array( 'outline', 'width' ), 280 'padding' => array( 'spacing', 'padding' ), 281 'padding-top' => array( 'spacing', 'padding', 'top' ), 282 'padding-right' => array( 'spacing', 'padding', 'right' ), 283 'padding-bottom' => array( 'spacing', 'padding', 'bottom' ), 284 'padding-left' => array( 'spacing', 'padding', 'left' ), 285 '--wp--style--root--padding' => array( 'spacing', 'padding' ), 286 '--wp--style--root--padding-top' => array( 'spacing', 'padding', 'top' ), 287 '--wp--style--root--padding-right' => array( 'spacing', 'padding', 'right' ), 288 '--wp--style--root--padding-bottom' => array( 'spacing', 'padding', 'bottom' ), 289 '--wp--style--root--padding-left' => array( 'spacing', 'padding', 'left' ), 290 'text-decoration' => array( 'typography', 'textDecoration' ), 291 'text-transform' => array( 'typography', 'textTransform' ), 292 'filter' => array( 'filter', 'duotone' ), 293 'box-shadow' => array( 'shadow' ), 294 'writing-mode' => array( 'typography', 'writingMode' ), 295 ); 296 297 /** 298 * Indirect metadata for style properties that are not directly output. 299 * 300 * Each element maps from a CSS property name to an array of 301 * paths to the value in theme.json & block attributes. 302 * 303 * Indirect properties are not output directly by `compute_style_properties`, 304 * but are used elsewhere in the processing of global styles. The indirect 305 * property is used to validate whether a style value is allowed. 306 * 307 * @since 6.2.0 308 * @since 6.6.0 Added background-image properties. 309 * @var array 310 */ 311 const INDIRECT_PROPERTIES_METADATA = array( 312 'gap' => array( 313 array( 'spacing', 'blockGap' ), 314 ), 315 'column-gap' => array( 316 array( 'spacing', 'blockGap', 'left' ), 317 ), 318 'row-gap' => array( 319 array( 'spacing', 'blockGap', 'top' ), 320 ), 321 'max-width' => array( 322 array( 'layout', 'contentSize' ), 323 array( 'layout', 'wideSize' ), 324 ), 325 'background-image' => array( 326 array( 'background', 'backgroundImage', 'url' ), 327 ), 328 ); 329 330 /** 331 * Protected style properties. 332 * 333 * These style properties are only rendered if a setting enables it 334 * via a value other than `null`. 335 * 336 * Each element maps the style property to the corresponding theme.json 337 * setting key. 338 * 339 * @since 5.9.0 340 * @var array 341 */ 342 const PROTECTED_PROPERTIES = array( 343 'spacing.blockGap' => array( 'spacing', 'blockGap' ), 344 ); 345 346 /** 347 * The top-level keys a theme.json can have. 348 * 349 * @since 5.8.0 As `ALLOWED_TOP_LEVEL_KEYS`. 350 * @since 5.9.0 Renamed from `ALLOWED_TOP_LEVEL_KEYS` to `VALID_TOP_LEVEL_KEYS`, 351 * added the `customTemplates` and `templateParts` values. 352 * @since 6.3.0 Added the `description` value. 353 * @since 6.6.0 Added `blockTypes` to support block style variation theme.json partials. 354 * @var string[] 355 */ 356 const VALID_TOP_LEVEL_KEYS = array( 357 'blockTypes', 358 'customTemplates', 359 'description', 360 'patterns', 361 'settings', 362 'slug', 363 'styles', 364 'templateParts', 365 'title', 366 'version', 367 ); 368 369 /** 370 * The valid properties under the settings key. 371 * 372 * @since 5.8.0 As `ALLOWED_SETTINGS`. 373 * @since 5.9.0 Renamed from `ALLOWED_SETTINGS` to `VALID_SETTINGS`, 374 * added new properties for `border`, `color`, `spacing`, 375 * and `typography`, and renamed others according to the new schema. 376 * @since 6.0.0 Added `color.defaultDuotone`. 377 * @since 6.1.0 Added `layout.definitions` and `useRootPaddingAwareAlignments`. 378 * @since 6.2.0 Added `dimensions.minHeight`, 'shadow.presets', 'shadow.defaultPresets', 379 * `position.fixed` and `position.sticky`. 380 * @since 6.3.0 Added support for `typography.textColumns`, removed `layout.definitions`. 381 * @since 6.4.0 Added support for `layout.allowEditing`, `background.backgroundImage`, 382 * `typography.writingMode`, `lightbox.enabled` and `lightbox.allowEditing`. 383 * @since 6.5.0 Added support for `layout.allowCustomContentAndWideSize`, 384 * `background.backgroundSize` and `dimensions.aspectRatio`. 385 * @since 6.6.0 Added support for 'dimensions.aspectRatios', 'dimensions.defaultAspectRatios', 386 * 'typography.defaultFontSizes', and 'spacing.defaultSpacingSizes'. 387 * @var array 388 */ 389 const VALID_SETTINGS = array( 390 'appearanceTools' => null, 391 'useRootPaddingAwareAlignments' => null, 392 'background' => array( 393 'backgroundImage' => null, 394 'backgroundSize' => null, 395 ), 396 'border' => array( 397 'color' => null, 398 'radius' => null, 399 'style' => null, 400 'width' => null, 401 ), 402 'color' => array( 403 'background' => null, 404 'custom' => null, 405 'customDuotone' => null, 406 'customGradient' => null, 407 'defaultDuotone' => null, 408 'defaultGradients' => null, 409 'defaultPalette' => null, 410 'duotone' => null, 411 'gradients' => null, 412 'link' => null, 413 'heading' => null, 414 'button' => null, 415 'caption' => null, 416 'palette' => null, 417 'text' => null, 418 ), 419 'custom' => null, 420 'dimensions' => array( 421 'aspectRatio' => null, 422 'aspectRatios' => null, 423 'defaultAspectRatios' => null, 424 'minHeight' => null, 425 ), 426 'layout' => array( 427 'contentSize' => null, 428 'wideSize' => null, 429 'allowEditing' => null, 430 'allowCustomContentAndWideSize' => null, 431 ), 432 'lightbox' => array( 433 'enabled' => null, 434 'allowEditing' => null, 435 ), 436 'position' => array( 437 'fixed' => null, 438 'sticky' => null, 439 ), 440 'spacing' => array( 441 'customSpacingSize' => null, 442 'defaultSpacingSizes' => null, 443 'spacingSizes' => null, 444 'spacingScale' => null, 445 'blockGap' => null, 446 'margin' => null, 447 'padding' => null, 448 'units' => null, 449 ), 450 'shadow' => array( 451 'presets' => null, 452 'defaultPresets' => null, 453 ), 454 'typography' => array( 455 'fluid' => null, 456 'customFontSize' => null, 457 'defaultFontSizes' => null, 458 'dropCap' => null, 459 'fontFamilies' => null, 460 'fontSizes' => null, 461 'fontStyle' => null, 462 'fontWeight' => null, 463 'letterSpacing' => null, 464 'lineHeight' => null, 465 'textAlign' => null, 466 'textColumns' => null, 467 'textDecoration' => null, 468 'textTransform' => null, 469 'writingMode' => null, 470 ), 471 ); 472 473 /** 474 * The valid properties for fontFamilies under settings key. 475 * 476 * @since 6.5.0 477 * @var array 478 */ 479 const FONT_FAMILY_SCHEMA = array( 480 array( 481 'fontFamily' => null, 482 'name' => null, 483 'slug' => null, 484 'fontFace' => array( 485 array( 486 'ascentOverride' => null, 487 'descentOverride' => null, 488 'fontDisplay' => null, 489 'fontFamily' => null, 490 'fontFeatureSettings' => null, 491 'fontStyle' => null, 492 'fontStretch' => null, 493 'fontVariationSettings' => null, 494 'fontWeight' => null, 495 'lineGapOverride' => null, 496 'sizeAdjust' => null, 497 'src' => null, 498 'unicodeRange' => null, 499 ), 500 ), 501 ), 502 ); 503 504 /** 505 * The valid properties under the styles key. 506 * 507 * @since 5.8.0 As `ALLOWED_STYLES`. 508 * @since 5.9.0 Renamed from `ALLOWED_STYLES` to `VALID_STYLES`, 509 * added new properties for `border`, `filter`, `spacing`, 510 * and `typography`. 511 * @since 6.1.0 Added new side properties for `border`, 512 * added new property `shadow`, 513 * updated `blockGap` to be allowed at any level. 514 * @since 6.2.0 Added `outline`, and `minHeight` properties. 515 * @since 6.3.0 Added support for `typography.textColumns`. 516 * @since 6.5.0 Added support for `dimensions.aspectRatio`. 517 * @since 6.6.0 Added `background` sub properties to top-level only. 518 * @var array 519 */ 520 const VALID_STYLES = array( 521 'background' => array( 522 'backgroundImage' => null, 523 'backgroundPosition' => null, 524 'backgroundRepeat' => null, 525 'backgroundSize' => null, 526 'backgroundAttachment' => null, 527 ), 528 'border' => array( 529 'color' => null, 530 'radius' => null, 531 'style' => null, 532 'width' => null, 533 'top' => null, 534 'right' => null, 535 'bottom' => null, 536 'left' => null, 537 ), 538 'color' => array( 539 'background' => null, 540 'gradient' => null, 541 'text' => null, 542 ), 543 'dimensions' => array( 544 'aspectRatio' => null, 545 'minHeight' => null, 546 ), 547 'filter' => array( 548 'duotone' => null, 549 ), 550 'outline' => array( 551 'color' => null, 552 'offset' => null, 553 'style' => null, 554 'width' => null, 555 ), 556 'shadow' => null, 557 'spacing' => array( 558 'margin' => null, 559 'padding' => null, 560 'blockGap' => null, 561 ), 562 'typography' => array( 563 'fontFamily' => null, 564 'fontSize' => null, 565 'fontStyle' => null, 566 'fontWeight' => null, 567 'letterSpacing' => null, 568 'lineHeight' => null, 569 'textAlign' => null, 570 'textColumns' => null, 571 'textDecoration' => null, 572 'textTransform' => null, 573 'writingMode' => null, 574 ), 575 'css' => null, 576 ); 577 578 /** 579 * Defines which pseudo selectors are enabled for which elements. 580 * 581 * The order of the selectors should be: link, any-link, visited, hover, focus, active. 582 * This is to ensure the user action (hover, focus and active) styles have a higher 583 * specificity than the visited styles, which in turn have a higher specificity than 584 * the unvisited styles. 585 * 586 * See https://core.trac.wordpress.org/ticket/56928. 587 * Note: this will affect both top-level and block-level elements. 588 * 589 * @since 6.1.0 590 * @since 6.2.0 Added support for ':link' and ':any-link'. 591 * @var array 592 */ 593 const VALID_ELEMENT_PSEUDO_SELECTORS = array( 594 'link' => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':active' ), 595 'button' => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':active' ), 596 ); 597 598 /** 599 * The valid elements that can be found under styles. 600 * 601 * @since 5.8.0 602 * @since 6.1.0 Added `heading`, `button`, and `caption` elements. 603 * @var string[] 604 */ 605 const ELEMENTS = array( 606 'link' => 'a:where(:not(.wp-element-button))', // The `where` is needed to lower the specificity. 607 'heading' => 'h1, h2, h3, h4, h5, h6', 608 'h1' => 'h1', 609 'h2' => 'h2', 610 'h3' => 'h3', 611 'h4' => 'h4', 612 'h5' => 'h5', 613 'h6' => 'h6', 614 // We have the .wp-block-button__link class so that this will target older buttons that have been serialized. 615 'button' => '.wp-element-button, .wp-block-button__link', 616 // The block classes are necessary to target older content that won't use the new class names. 617 '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', 618 'cite' => 'cite', 619 ); 620 621 const __EXPERIMENTAL_ELEMENT_CLASS_NAMES = array( 622 'button' => 'wp-element-button', 623 'caption' => 'wp-element-caption', 624 ); 625 626 /** 627 * List of block support features that can have their related styles 628 * generated under their own feature level selector rather than the block's. 629 * 630 * @since 6.1.0 631 * @var string[] 632 */ 633 const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = array( 634 '__experimentalBorder' => 'border', 635 'color' => 'color', 636 'spacing' => 'spacing', 637 'typography' => 'typography', 638 ); 639 640 /** 641 * Return the input schema at the root and per origin. 642 * 643 * @since 6.5.0 644 * 645 * @param array $schema The base schema. 646 * @return array The schema at the root and per origin. 647 * 648 * Example: 649 * schema_in_root_and_per_origin( 650 * array( 651 * 'fontFamily' => null, 652 * 'slug' => null, 653 * ) 654 * ) 655 * 656 * Returns: 657 * array( 658 * 'fontFamily' => null, 659 * 'slug' => null, 660 * 'default' => array( 661 * 'fontFamily' => null, 662 * 'slug' => null, 663 * ), 664 * 'blocks' => array( 665 * 'fontFamily' => null, 666 * 'slug' => null, 667 * ), 668 * 'theme' => array( 669 * 'fontFamily' => null, 670 * 'slug' => null, 671 * ), 672 * 'custom' => array( 673 * 'fontFamily' => null, 674 * 'slug' => null, 675 * ), 676 * ) 677 */ 678 protected static function schema_in_root_and_per_origin( $schema ) { 679 $schema_in_root_and_per_origin = $schema; 680 foreach ( static::VALID_ORIGINS as $origin ) { 681 $schema_in_root_and_per_origin[ $origin ] = $schema; 682 } 683 return $schema_in_root_and_per_origin; 684 } 685 686 /** 687 * Returns a class name by an element name. 688 * 689 * @since 6.1.0 690 * 691 * @param string $element The name of the element. 692 * @return string The name of the class. 693 */ 694 public static function get_element_class_name( $element ) { 695 $class_name = ''; 696 697 if ( isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ] ) ) { 698 $class_name = static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ]; 699 } 700 701 return $class_name; 702 } 703 704 /** 705 * Options that settings.appearanceTools enables. 706 * 707 * @since 6.0.0 708 * @since 6.2.0 Added `dimensions.minHeight` and `position.sticky`. 709 * @since 6.4.0 Added `background.backgroundImage`. 710 * @since 6.5.0 Added `background.backgroundSize` and `dimensions.aspectRatio`. 711 * @var array 712 */ 713 const APPEARANCE_TOOLS_OPT_INS = array( 714 array( 'background', 'backgroundImage' ), 715 array( 'background', 'backgroundSize' ), 716 array( 'border', 'color' ), 717 array( 'border', 'radius' ), 718 array( 'border', 'style' ), 719 array( 'border', 'width' ), 720 array( 'color', 'link' ), 721 array( 'color', 'heading' ), 722 array( 'color', 'button' ), 723 array( 'color', 'caption' ), 724 array( 'dimensions', 'aspectRatio' ), 725 array( 'dimensions', 'minHeight' ), 726 array( 'position', 'sticky' ), 727 array( 'spacing', 'blockGap' ), 728 array( 'spacing', 'margin' ), 729 array( 'spacing', 'padding' ), 730 array( 'typography', 'lineHeight' ), 731 ); 732 733 /** 734 * The latest version of the schema in use. 735 * 736 * @since 5.8.0 737 * @since 5.9.0 Changed value from 1 to 2. 738 * @since 6.6.0 Changed value from 2 to 3. 739 * @var int 740 */ 741 const LATEST_SCHEMA = 3; 742 743 /** 744 * Constructor. 745 * 746 * @since 5.8.0 747 * @since 6.6.0 Key spacingScale by origin, and Pre-generate the spacingSizes from spacingScale. 748 * Added unwrapping of shared block style variations into block type variations if registered. 749 * 750 * @param array $theme_json A structure that follows the theme.json schema. 751 * @param string $origin Optional. What source of data this object represents. 752 * One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'. 753 */ 754 public function __construct( $theme_json = array( 'version' => self::LATEST_SCHEMA ), $origin = 'theme' ) { 755 if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) { 756 $origin = 'theme'; 757 } 758 759 $this->theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin ); 760 $blocks_metadata = static::get_blocks_metadata(); 761 $valid_block_names = array_keys( $blocks_metadata ); 762 $valid_element_names = array_keys( static::ELEMENTS ); 763 $valid_variations = static::get_valid_block_style_variations( $blocks_metadata ); 764 $this->theme_json = static::unwrap_shared_block_style_variations( $this->theme_json, $valid_variations ); 765 $this->theme_json = static::sanitize( $this->theme_json, $valid_block_names, $valid_element_names, $valid_variations ); 766 $this->theme_json = static::maybe_opt_in_into_settings( $this->theme_json ); 767 768 // Internally, presets are keyed by origin. 769 $nodes = static::get_setting_nodes( $this->theme_json ); 770 foreach ( $nodes as $node ) { 771 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 772 $path = $node['path']; 773 foreach ( $preset_metadata['path'] as $subpath ) { 774 $path[] = $subpath; 775 } 776 $preset = _wp_array_get( $this->theme_json, $path, null ); 777 if ( null !== $preset ) { 778 // If the preset is not already keyed by origin. 779 if ( isset( $preset[0] ) || empty( $preset ) ) { 780 _wp_array_set( $this->theme_json, $path, array( $origin => $preset ) ); 781 } 782 } 783 } 784 } 785 786 // In addition to presets, spacingScale (which generates presets) is also keyed by origin. 787 $scale_path = array( 'settings', 'spacing', 'spacingScale' ); 788 $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null ); 789 if ( null !== $spacing_scale ) { 790 // If the spacingScale is not already keyed by origin. 791 if ( empty( array_intersect( array_keys( $spacing_scale ), static::VALID_ORIGINS ) ) ) { 792 _wp_array_set( $this->theme_json, $scale_path, array( $origin => $spacing_scale ) ); 793 } 794 } 795 796 // Pre-generate the spacingSizes from spacingScale. 797 $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin ); 798 $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null ); 799 if ( isset( $spacing_scale ) ) { 800 $sizes_path = array( 'settings', 'spacing', 'spacingSizes', $origin ); 801 $spacing_sizes = _wp_array_get( $this->theme_json, $sizes_path, array() ); 802 $spacing_scale_sizes = static::compute_spacing_sizes( $spacing_scale ); 803 $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes ); 804 _wp_array_set( $this->theme_json, $sizes_path, $merged_spacing_sizes ); 805 } 806 } 807 808 /** 809 * Unwraps shared block style variations. 810 * 811 * It takes the shared variations (styles.variations.variationName) and 812 * applies them to all the blocks that have the given variation registered 813 * (styles.blocks.blockType.variations.variationName). 814 * 815 * For example, given the `core/paragraph` and `core/group` blocks have 816 * registered the `section-a` style variation, and given the following input: 817 * 818 * { 819 * "styles": { 820 * "variations": { 821 * "section-a": { "color": { "background": "backgroundColor" } } 822 * } 823 * } 824 * } 825 * 826 * It returns the following output: 827 * 828 * { 829 * "styles": { 830 * "blocks": { 831 * "core/paragraph": { 832 * "variations": { 833 * "section-a": { "color": { "background": "backgroundColor" } } 834 * }, 835 * }, 836 * "core/group": { 837 * "variations": { 838 * "section-a": { "color": { "background": "backgroundColor" } } 839 * } 840 * } 841 * } 842 * } 843 * } 844 * 845 * @since 6.6.0 846 * 847 * @param array $theme_json A structure that follows the theme.json schema. 848 * @param array $valid_variations Valid block style variations. 849 * @return array Theme json data with shared variation definitions unwrapped under appropriate block types. 850 */ 851 private static function unwrap_shared_block_style_variations( $theme_json, $valid_variations ) { 852 if ( empty( $theme_json['styles']['variations'] ) || empty( $valid_variations ) ) { 853 return $theme_json; 854 } 855 856 $new_theme_json = $theme_json; 857 $variations = $new_theme_json['styles']['variations']; 858 859 foreach ( $valid_variations as $block_type => $registered_variations ) { 860 foreach ( $registered_variations as $variation_name ) { 861 $block_level_data = $new_theme_json['styles']['blocks'][ $block_type ]['variations'][ $variation_name ] ?? array(); 862 $top_level_data = $variations[ $variation_name ] ?? array(); 863 $merged_data = array_replace_recursive( $top_level_data, $block_level_data ); 864 if ( ! empty( $merged_data ) ) { 865 _wp_array_set( $new_theme_json, array( 'styles', 'blocks', $block_type, 'variations', $variation_name ), $merged_data ); 866 } 867 } 868 } 869 870 unset( $new_theme_json['styles']['variations'] ); 871 872 return $new_theme_json; 873 } 874 875 /** 876 * Enables some opt-in settings if theme declared support. 877 * 878 * @since 5.9.0 879 * 880 * @param array $theme_json A theme.json structure to modify. 881 * @return array The modified theme.json structure. 882 */ 883 protected static function maybe_opt_in_into_settings( $theme_json ) { 884 $new_theme_json = $theme_json; 885 886 if ( 887 isset( $new_theme_json['settings']['appearanceTools'] ) && 888 true === $new_theme_json['settings']['appearanceTools'] 889 ) { 890 static::do_opt_in_into_settings( $new_theme_json['settings'] ); 891 } 892 893 if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) { 894 foreach ( $new_theme_json['settings']['blocks'] as &$block ) { 895 if ( isset( $block['appearanceTools'] ) && ( true === $block['appearanceTools'] ) ) { 896 static::do_opt_in_into_settings( $block ); 897 } 898 } 899 } 900 901 return $new_theme_json; 902 } 903 904 /** 905 * Enables some settings. 906 * 907 * @since 5.9.0 908 * 909 * @param array $context The context to which the settings belong. 910 */ 911 protected static function do_opt_in_into_settings( &$context ) { 912 foreach ( static::APPEARANCE_TOOLS_OPT_INS as $path ) { 913 /* 914 * Use "unset prop" as a marker instead of "null" because 915 * "null" can be a valid value for some props (e.g. blockGap). 916 */ 917 if ( 'unset prop' === _wp_array_get( $context, $path, 'unset prop' ) ) { 918 _wp_array_set( $context, $path, true ); 919 } 920 } 921 922 unset( $context['appearanceTools'] ); 923 } 924 925 /** 926 * Sanitizes the input according to the schemas. 927 * 928 * @since 5.8.0 929 * @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters. 930 * @since 6.3.0 Added the `$valid_variations` parameter. 931 * @since 6.6.0 Updated schema to allow extended block style variations. 932 * 933 * @param array $input Structure to sanitize. 934 * @param array $valid_block_names List of valid block names. 935 * @param array $valid_element_names List of valid element names. 936 * @param array $valid_variations List of valid variations per block. 937 * @return array The sanitized output. 938 */ 939 protected static function sanitize( $input, $valid_block_names, $valid_element_names, $valid_variations ) { 940 $output = array(); 941 942 if ( ! is_array( $input ) ) { 943 return $output; 944 } 945 946 // Preserve only the top most level keys. 947 $output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) ); 948 949 /* 950 * Remove any rules that are annotated as "top" in VALID_STYLES constant. 951 * Some styles are only meant to be available at the top-level (e.g.: blockGap), 952 * hence, the schema for blocks & elements should not have them. 953 */ 954 $styles_non_top_level = static::VALID_STYLES; 955 foreach ( array_keys( $styles_non_top_level ) as $section ) { 956 // array_key_exists() needs to be used instead of isset() because the value can be null. 957 if ( array_key_exists( $section, $styles_non_top_level ) && is_array( $styles_non_top_level[ $section ] ) ) { 958 foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) { 959 if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) { 960 unset( $styles_non_top_level[ $section ][ $prop ] ); 961 } 962 } 963 } 964 } 965 966 // Build the schema based on valid block & element names. 967 $schema = array(); 968 $schema_styles_elements = array(); 969 970 /* 971 * Set allowed element pseudo selectors based on per element allow list. 972 * Target data structure in schema: 973 * e.g. 974 * - top level elements: `$schema['styles']['elements']['link'][':hover']`. 975 * - block level elements: `$schema['styles']['blocks']['core/button']['elements']['link'][':hover']`. 976 */ 977 foreach ( $valid_element_names as $element ) { 978 $schema_styles_elements[ $element ] = $styles_non_top_level; 979 980 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) { 981 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) { 982 $schema_styles_elements[ $element ][ $pseudo_selector ] = $styles_non_top_level; 983 } 984 } 985 } 986 987 $schema_styles_blocks = array(); 988 $schema_settings_blocks = array(); 989 990 /* 991 * Generate a schema for blocks. 992 * - Block styles can contain `elements` & `variations` definitions. 993 * - Variations definitions cannot be nested. 994 * - Variations can contain styles for inner `blocks`. 995 * - Variation inner `blocks` styles can contain `elements`. 996 * 997 * As each variation needs a `blocks` schema but further nested 998 * inner `blocks`, the overall schema will be generated in multiple passes. 999 */ 1000 foreach ( $valid_block_names as $block ) { 1001 $schema_settings_blocks[ $block ] = static::VALID_SETTINGS; 1002 $schema_styles_blocks[ $block ] = $styles_non_top_level; 1003 $schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements; 1004 } 1005 1006 $block_style_variation_styles = static::VALID_STYLES; 1007 $block_style_variation_styles['blocks'] = $schema_styles_blocks; 1008 $block_style_variation_styles['elements'] = $schema_styles_elements; 1009 1010 foreach ( $valid_block_names as $block ) { 1011 // Build the schema for each block style variation. 1012 $style_variation_names = array(); 1013 if ( 1014 ! empty( $input['styles']['blocks'][ $block ]['variations'] ) && 1015 is_array( $input['styles']['blocks'][ $block ]['variations'] ) && 1016 isset( $valid_variations[ $block ] ) 1017 ) { 1018 $style_variation_names = array_intersect( 1019 array_keys( $input['styles']['blocks'][ $block ]['variations'] ), 1020 $valid_variations[ $block ] 1021 ); 1022 } 1023 1024 $schema_styles_variations = array(); 1025 if ( ! empty( $style_variation_names ) ) { 1026 $schema_styles_variations = array_fill_keys( $style_variation_names, $block_style_variation_styles ); 1027 } 1028 1029 $schema_styles_blocks[ $block ]['variations'] = $schema_styles_variations; 1030 } 1031 1032 $schema['styles'] = static::VALID_STYLES; 1033 $schema['styles']['blocks'] = $schema_styles_blocks; 1034 $schema['styles']['elements'] = $schema_styles_elements; 1035 $schema['settings'] = static::VALID_SETTINGS; 1036 $schema['settings']['blocks'] = $schema_settings_blocks; 1037 $schema['settings']['typography']['fontFamilies'] = static::schema_in_root_and_per_origin( static::FONT_FAMILY_SCHEMA ); 1038 1039 // Remove anything that's not present in the schema. 1040 foreach ( array( 'styles', 'settings' ) as $subtree ) { 1041 if ( ! isset( $input[ $subtree ] ) ) { 1042 continue; 1043 } 1044 1045 if ( ! is_array( $input[ $subtree ] ) ) { 1046 unset( $output[ $subtree ] ); 1047 continue; 1048 } 1049 1050 $result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] ); 1051 1052 if ( empty( $result ) ) { 1053 unset( $output[ $subtree ] ); 1054 } else { 1055 $output[ $subtree ] = static::resolve_custom_css_format( $result ); 1056 } 1057 } 1058 1059 return $output; 1060 } 1061 1062 /** 1063 * Appends a sub-selector to an existing one. 1064 * 1065 * Given the compounded $selector "h1, h2, h3" 1066 * and the $to_append selector ".some-class" the result will be 1067 * "h1.some-class, h2.some-class, h3.some-class". 1068 * 1069 * @since 5.8.0 1070 * @since 6.1.0 Added append position. 1071 * @since 6.3.0 Removed append position parameter. 1072 * 1073 * @param string $selector Original selector. 1074 * @param string $to_append Selector to append. 1075 * @return string The new selector. 1076 */ 1077 protected static function append_to_selector( $selector, $to_append ) { 1078 if ( ! str_contains( $selector, ',' ) ) { 1079 return $selector . $to_append; 1080 } 1081 $new_selectors = array(); 1082 $selectors = explode( ',', $selector ); 1083 foreach ( $selectors as $sel ) { 1084 $new_selectors[] = $sel . $to_append; 1085 } 1086 return implode( ',', $new_selectors ); 1087 } 1088 1089 /** 1090 * Prepends a sub-selector to an existing one. 1091 * 1092 * Given the compounded $selector "h1, h2, h3" 1093 * and the $to_prepend selector ".some-class " the result will be 1094 * ".some-class h1, .some-class h2, .some-class h3". 1095 * 1096 * @since 6.3.0 1097 * 1098 * @param string $selector Original selector. 1099 * @param string $to_prepend Selector to prepend. 1100 * @return string The new selector. 1101 */ 1102 protected static function prepend_to_selector( $selector, $to_prepend ) { 1103 if ( ! str_contains( $selector, ',' ) ) { 1104 return $to_prepend . $selector; 1105 } 1106 $new_selectors = array(); 1107 $selectors = explode( ',', $selector ); 1108 foreach ( $selectors as $sel ) { 1109 $new_selectors[] = $to_prepend . $sel; 1110 } 1111 return implode( ',', $new_selectors ); 1112 } 1113 1114 /** 1115 * Returns the metadata for each block. 1116 * 1117 * Example: 1118 * 1119 * { 1120 * 'core/paragraph': { 1121 * 'selector': 'p', 1122 * 'elements': { 1123 * 'link' => 'link selector', 1124 * 'etc' => 'element selector' 1125 * } 1126 * }, 1127 * 'core/heading': { 1128 * 'selector': 'h1', 1129 * 'elements': {} 1130 * }, 1131 * 'core/image': { 1132 * 'selector': '.wp-block-image', 1133 * 'duotone': 'img', 1134 * 'elements': {} 1135 * } 1136 * } 1137 * 1138 * @since 5.8.0 1139 * @since 5.9.0 Added `duotone` key with CSS selector. 1140 * @since 6.1.0 Added `features` key with block support feature level selectors. 1141 * @since 6.3.0 Refactored and stabilized selectors API. 1142 * @since 6.6.0 Updated to include block style variations from the block styles registry. 1143 * 1144 * @return array Block metadata. 1145 */ 1146 protected static function get_blocks_metadata() { 1147 $registry = WP_Block_Type_Registry::get_instance(); 1148 $blocks = $registry->get_all_registered(); 1149 $style_registry = WP_Block_Styles_Registry::get_instance(); 1150 1151 // Is there metadata for all currently registered blocks? 1152 $blocks = array_diff_key( $blocks, static::$blocks_metadata ); 1153 if ( empty( $blocks ) ) { 1154 /* 1155 * New block styles may have been registered within WP_Block_Styles_Registry. 1156 * Update block metadata for any new block style variations. 1157 */ 1158 $registered_styles = $style_registry->get_all_registered(); 1159 foreach ( static::$blocks_metadata as $block_name => $block_metadata ) { 1160 if ( ! empty( $registered_styles[ $block_name ] ) ) { 1161 $style_selectors = $block_metadata['styleVariations'] ?? array(); 1162 1163 foreach ( $registered_styles[ $block_name ] as $block_style ) { 1164 if ( ! isset( $style_selectors[ $block_style['name'] ] ) ) { 1165 $style_selectors[ $block_style['name'] ] = static::get_block_style_variation_selector( $block_style['name'], $block_metadata['selector'] ); 1166 } 1167 } 1168 1169 static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors; 1170 } 1171 } 1172 return static::$blocks_metadata; 1173 } 1174 1175 foreach ( $blocks as $block_name => $block_type ) { 1176 $root_selector = wp_get_block_css_selector( $block_type ); 1177 1178 static::$blocks_metadata[ $block_name ]['selector'] = $root_selector; 1179 static::$blocks_metadata[ $block_name ]['selectors'] = static::get_block_selectors( $block_type, $root_selector ); 1180 1181 $elements = static::get_block_element_selectors( $root_selector ); 1182 if ( ! empty( $elements ) ) { 1183 static::$blocks_metadata[ $block_name ]['elements'] = $elements; 1184 } 1185 1186 // The block may or may not have a duotone selector. 1187 $duotone_selector = wp_get_block_css_selector( $block_type, 'filter.duotone' ); 1188 1189 // Keep backwards compatibility for support.color.__experimentalDuotone. 1190 if ( null === $duotone_selector ) { 1191 $duotone_support = isset( $block_type->supports['color']['__experimentalDuotone'] ) 1192 ? $block_type->supports['color']['__experimentalDuotone'] 1193 : null; 1194 1195 if ( $duotone_support ) { 1196 $root_selector = wp_get_block_css_selector( $block_type ); 1197 $duotone_selector = static::scope_selector( $root_selector, $duotone_support ); 1198 } 1199 } 1200 1201 if ( null !== $duotone_selector ) { 1202 static::$blocks_metadata[ $block_name ]['duotone'] = $duotone_selector; 1203 } 1204 1205 // If the block has style variations, append their selectors to the block metadata. 1206 $style_selectors = array(); 1207 if ( ! empty( $block_type->styles ) ) { 1208 foreach ( $block_type->styles as $style ) { 1209 $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] ); 1210 } 1211 } 1212 1213 // Block style variations can be registered through the WP_Block_Styles_Registry as well as block.json. 1214 $registered_styles = $style_registry->get_registered_styles_for_block( $block_name ); 1215 foreach ( $registered_styles as $style ) { 1216 $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] ); 1217 } 1218 1219 if ( ! empty( $style_selectors ) ) { 1220 static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors; 1221 } 1222 } 1223 1224 return static::$blocks_metadata; 1225 } 1226 1227 /** 1228 * Given a tree, removes the keys that are not present in the schema. 1229 * 1230 * It is recursive and modifies the input in-place. 1231 * 1232 * @since 5.8.0 1233 * 1234 * @param array $tree Input to process. 1235 * @param array $schema Schema to adhere to. 1236 * @return array The modified $tree. 1237 */ 1238 protected static function remove_keys_not_in_schema( $tree, $schema ) { 1239 if ( ! is_array( $tree ) ) { 1240 return $tree; 1241 } 1242 1243 foreach ( $tree as $key => $value ) { 1244 // Remove keys not in the schema or with null/empty values. 1245 if ( ! array_key_exists( $key, $schema ) ) { 1246 unset( $tree[ $key ] ); 1247 continue; 1248 } 1249 1250 if ( is_array( $schema[ $key ] ) ) { 1251 if ( ! is_array( $value ) ) { 1252 unset( $tree[ $key ] ); 1253 } elseif ( wp_is_numeric_array( $value ) ) { 1254 // If indexed, process each item in the array. 1255 foreach ( $value as $item_key => $item_value ) { 1256 if ( isset( $schema[ $key ][0] ) && is_array( $schema[ $key ][0] ) ) { 1257 $tree[ $key ][ $item_key ] = self::remove_keys_not_in_schema( $item_value, $schema[ $key ][0] ); 1258 } else { 1259 // If the schema does not define a further structure, keep the value as is. 1260 $tree[ $key ][ $item_key ] = $item_value; 1261 } 1262 } 1263 } else { 1264 // If associative, process as a single object. 1265 $tree[ $key ] = self::remove_keys_not_in_schema( $value, $schema[ $key ] ); 1266 1267 if ( empty( $tree[ $key ] ) ) { 1268 unset( $tree[ $key ] ); 1269 } 1270 } 1271 } 1272 } 1273 return $tree; 1274 } 1275 1276 /** 1277 * Returns the existing settings for each block. 1278 * 1279 * Example: 1280 * 1281 * { 1282 * 'root': { 1283 * 'color': { 1284 * 'custom': true 1285 * } 1286 * }, 1287 * 'core/paragraph': { 1288 * 'spacing': { 1289 * 'customPadding': true 1290 * } 1291 * } 1292 * } 1293 * 1294 * @since 5.8.0 1295 * 1296 * @return array Settings per block. 1297 */ 1298 public function get_settings() { 1299 if ( ! isset( $this->theme_json['settings'] ) ) { 1300 return array(); 1301 } else { 1302 return $this->theme_json['settings']; 1303 } 1304 } 1305 1306 /** 1307 * Returns the stylesheet that results of processing 1308 * the theme.json structure this object represents. 1309 * 1310 * @since 5.8.0 1311 * @since 5.9.0 Removed the `$type` parameter, added the `$types` and `$origins` parameters. 1312 * @since 6.3.0 Add fallback layout styles for Post Template when block gap support isn't available. 1313 * @since 6.6.0 Added boolean `skip_root_layout_styles` and `include_block_style_variations` options 1314 * to control styles output as desired. 1315 * 1316 * @param string[] $types Types of styles to load. Will load all by default. It accepts: 1317 * - `variables`: only the CSS Custom Properties for presets & custom ones. 1318 * - `styles`: only the styles section in theme.json. 1319 * - `presets`: only the classes for the presets. 1320 * - `base-layout-styles`: only the base layout styles. 1321 * - `custom-css`: only the custom CSS. 1322 * @param string[] $origins A list of origins to include. By default it includes VALID_ORIGINS. 1323 * @param array $options { 1324 * Optional. An array of options for now used for internal purposes only (may change without notice). 1325 * 1326 * @type string $scope Makes sure all style are scoped to a given selector 1327 * @type string $root_selector Overwrites and forces a given selector to be used on the root node 1328 * @type bool $skip_root_layout_styles Omits root layout styles from the generated stylesheet. Default false. 1329 * @type bool $include_block_style_variations Includes styles for block style variations in the generated stylesheet. Default false. 1330 * } 1331 * @return string The resulting stylesheet. 1332 */ 1333 public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null, $options = array() ) { 1334 if ( null === $origins ) { 1335 $origins = static::VALID_ORIGINS; 1336 } 1337 1338 if ( is_string( $types ) ) { 1339 // Dispatch error and map old arguments to new ones. 1340 _deprecated_argument( __FUNCTION__, '5.9.0' ); 1341 if ( 'block_styles' === $types ) { 1342 $types = array( 'styles', 'presets' ); 1343 } elseif ( 'css_variables' === $types ) { 1344 $types = array( 'variables' ); 1345 } else { 1346 $types = array( 'variables', 'styles', 'presets' ); 1347 } 1348 } 1349 1350 $blocks_metadata = static::get_blocks_metadata(); 1351 $style_nodes = static::get_style_nodes( $this->theme_json, $blocks_metadata, $options ); 1352 $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata ); 1353 1354 $root_style_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $style_nodes, 'selector' ), true ); 1355 $root_settings_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $setting_nodes, 'selector' ), true ); 1356 1357 if ( ! empty( $options['scope'] ) ) { 1358 foreach ( $setting_nodes as &$node ) { 1359 $node['selector'] = static::scope_selector( $options['scope'], $node['selector'] ); 1360 } 1361 foreach ( $style_nodes as &$node ) { 1362 $node = static::scope_style_node_selectors( $options['scope'], $node ); 1363 } 1364 unset( $node ); 1365 } 1366 1367 if ( ! empty( $options['root_selector'] ) ) { 1368 if ( false !== $root_settings_key ) { 1369 $setting_nodes[ $root_settings_key ]['selector'] = $options['root_selector']; 1370 } 1371 if ( false !== $root_style_key ) { 1372 $style_nodes[ $root_style_key ]['selector'] = $options['root_selector']; 1373 } 1374 } 1375 1376 $stylesheet = ''; 1377 1378 if ( in_array( 'variables', $types, true ) ) { 1379 $stylesheet .= $this->get_css_variables( $setting_nodes, $origins ); 1380 } 1381 1382 if ( in_array( 'styles', $types, true ) ) { 1383 if ( false !== $root_style_key && empty( $options['skip_root_layout_styles'] ) ) { 1384 $stylesheet .= $this->get_root_layout_rules( $style_nodes[ $root_style_key ]['selector'], $style_nodes[ $root_style_key ] ); 1385 } 1386 $stylesheet .= $this->get_block_classes( $style_nodes ); 1387 } elseif ( in_array( 'base-layout-styles', $types, true ) ) { 1388 $root_selector = static::ROOT_BLOCK_SELECTOR; 1389 $columns_selector = '.wp-block-columns'; 1390 $post_template_selector = '.wp-block-post-template'; 1391 if ( ! empty( $options['scope'] ) ) { 1392 $root_selector = static::scope_selector( $options['scope'], $root_selector ); 1393 $columns_selector = static::scope_selector( $options['scope'], $columns_selector ); 1394 $post_template_selector = static::scope_selector( $options['scope'], $post_template_selector ); 1395 } 1396 if ( ! empty( $options['root_selector'] ) ) { 1397 $root_selector = $options['root_selector']; 1398 } 1399 /* 1400 * Base layout styles are provided as part of `styles`, so only output separately if explicitly requested. 1401 * For backwards compatibility, the Columns block is explicitly included, to support a different default gap value. 1402 */ 1403 $base_styles_nodes = array( 1404 array( 1405 'path' => array( 'styles' ), 1406 'selector' => $root_selector, 1407 ), 1408 array( 1409 'path' => array( 'styles', 'blocks', 'core/columns' ), 1410 'selector' => $columns_selector, 1411 'name' => 'core/columns', 1412 ), 1413 array( 1414 'path' => array( 'styles', 'blocks', 'core/post-template' ), 1415 'selector' => $post_template_selector, 1416 'name' => 'core/post-template', 1417 ), 1418 ); 1419 1420 foreach ( $base_styles_nodes as $base_style_node ) { 1421 $stylesheet .= $this->get_layout_styles( $base_style_node, $types ); 1422 } 1423 } 1424 1425 if ( in_array( 'presets', $types, true ) ) { 1426 $stylesheet .= $this->get_preset_classes( $setting_nodes, $origins ); 1427 } 1428 1429 // Load the custom CSS last so it has the highest specificity. 1430 if ( in_array( 'custom-css', $types, true ) ) { 1431 // Add the global styles root CSS. 1432 $stylesheet .= _wp_array_get( $this->theme_json, array( 'styles', 'css' ) ); 1433 } 1434 1435 return $stylesheet; 1436 } 1437 1438 /** 1439 * Processes the CSS, to apply nesting. 1440 * 1441 * @since 6.2.0 1442 * @since 6.6.0 Enforced 0-1-0 specificity for block custom CSS selectors. 1443 * 1444 * @param string $css The CSS to process. 1445 * @param string $selector The selector to nest. 1446 * @return string The processed CSS. 1447 */ 1448 protected function process_blocks_custom_css( $css, $selector ) { 1449 $processed_css = ''; 1450 1451 if ( empty( $css ) ) { 1452 return $processed_css; 1453 } 1454 1455 // Split CSS nested rules. 1456 $parts = explode( '&', $css ); 1457 foreach ( $parts as $part ) { 1458 if ( empty( $part ) ) { 1459 continue; 1460 } 1461 $is_root_css = ( ! str_contains( $part, '{' ) ); 1462 if ( $is_root_css ) { 1463 // If the part doesn't contain braces, it applies to the root level. 1464 $processed_css .= ':root :where(' . trim( $selector ) . '){' . trim( $part ) . '}'; 1465 } else { 1466 // If the part contains braces, it's a nested CSS rule. 1467 $part = explode( '{', str_replace( '}', '', $part ) ); 1468 if ( count( $part ) !== 2 ) { 1469 continue; 1470 } 1471 $nested_selector = $part[0]; 1472 $css_value = $part[1]; 1473 1474 /* 1475 * Handle pseudo elements such as ::before, ::after etc. Regex will also 1476 * capture any leading combinator such as >, +, or ~, as well as spaces. 1477 * This allows pseudo elements as descendants e.g. `.parent ::before`. 1478 */ 1479 $matches = array(); 1480 $has_pseudo_element = preg_match( '/([>+~\s]*::[a-zA-Z-]+)/', $nested_selector, $matches ); 1481 $pseudo_part = $has_pseudo_element ? $matches[1] : ''; 1482 $nested_selector = $has_pseudo_element ? str_replace( $pseudo_part, '', $nested_selector ) : $nested_selector; 1483 1484 // Finalize selector and re-append pseudo element if required. 1485 $part_selector = str_starts_with( $nested_selector, ' ' ) 1486 ? static::scope_selector( $selector, $nested_selector ) 1487 : static::append_to_selector( $selector, $nested_selector ); 1488 $final_selector = ":root :where($part_selector)$pseudo_part"; 1489 1490 $processed_css .= $final_selector . '{' . trim( $css_value ) . '}'; 1491 } 1492 } 1493 return $processed_css; 1494 } 1495 1496 /** 1497 * Returns the global styles custom CSS. 1498 * 1499 * @since 6.2.0 1500 * @deprecated 6.7.0 Use {@see 'get_stylesheet'} instead. 1501 * 1502 * @return string The global styles custom CSS. 1503 */ 1504 public function get_custom_css() { 1505 _deprecated_function( __METHOD__, '6.7.0', 'get_stylesheet' ); 1506 // Add the global styles root CSS. 1507 $stylesheet = isset( $this->theme_json['styles']['css'] ) ? $this->theme_json['styles']['css'] : ''; 1508 1509 // Add the global styles block CSS. 1510 if ( isset( $this->theme_json['styles']['blocks'] ) ) { 1511 foreach ( $this->theme_json['styles']['blocks'] as $name => $node ) { 1512 $custom_block_css = isset( $this->theme_json['styles']['blocks'][ $name ]['css'] ) 1513 ? $this->theme_json['styles']['blocks'][ $name ]['css'] 1514 : null; 1515 if ( $custom_block_css ) { 1516 $selector = static::$blocks_metadata[ $name ]['selector']; 1517 $stylesheet .= $this->process_blocks_custom_css( $custom_block_css, $selector ); 1518 } 1519 } 1520 } 1521 1522 return $stylesheet; 1523 } 1524 1525 /** 1526 * Returns the page templates of the active theme. 1527 * 1528 * @since 5.9.0 1529 * 1530 * @return array 1531 */ 1532 public function get_custom_templates() { 1533 $custom_templates = array(); 1534 if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) { 1535 return $custom_templates; 1536 } 1537 1538 foreach ( $this->theme_json['customTemplates'] as $item ) { 1539 if ( isset( $item['name'] ) ) { 1540 $custom_templates[ $item['name'] ] = array( 1541 'title' => isset( $item['title'] ) ? $item['title'] : '', 1542 'postTypes' => isset( $item['postTypes'] ) ? $item['postTypes'] : array( 'page' ), 1543 ); 1544 } 1545 } 1546 return $custom_templates; 1547 } 1548 1549 /** 1550 * Returns the template part data of active theme. 1551 * 1552 * @since 5.9.0 1553 * 1554 * @return array 1555 */ 1556 public function get_template_parts() { 1557 $template_parts = array(); 1558 if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) { 1559 return $template_parts; 1560 } 1561 1562 foreach ( $this->theme_json['templateParts'] as $item ) { 1563 if ( isset( $item['name'] ) ) { 1564 $template_parts[ $item['name'] ] = array( 1565 'title' => isset( $item['title'] ) ? $item['title'] : '', 1566 'area' => isset( $item['area'] ) ? $item['area'] : '', 1567 ); 1568 } 1569 } 1570 return $template_parts; 1571 } 1572 1573 /** 1574 * Converts each style section into a list of rulesets 1575 * containing the block styles to be appended to the stylesheet. 1576 * 1577 * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax 1578 * 1579 * For each section this creates a new ruleset such as: 1580 * 1581 * block-selector { 1582 * style-property-one: value; 1583 * } 1584 * 1585 * @since 5.8.0 As `get_block_styles()`. 1586 * @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()` 1587 * and no longer returns preset classes. 1588 * Removed the `$setting_nodes` parameter. 1589 * @since 6.1.0 Moved most internal logic to `get_styles_for_block()`. 1590 * 1591 * @param array $style_nodes Nodes with styles. 1592 * @return string The new stylesheet. 1593 */ 1594 protected function get_block_classes( $style_nodes ) { 1595 $block_rules = ''; 1596 1597 foreach ( $style_nodes as $metadata ) { 1598 if ( null === $metadata['selector'] ) { 1599 continue; 1600 } 1601 $block_rules .= static::get_styles_for_block( $metadata ); 1602 } 1603 1604 return $block_rules; 1605 } 1606 1607 /** 1608 * Gets the CSS layout rules for a particular block from theme.json layout definitions. 1609 * 1610 * @since 6.1.0 1611 * @since 6.3.0 Reduced specificity for layout margin rules. 1612 * @since 6.5.1 Only output rules referencing content and wide sizes when values exist. 1613 * @since 6.5.3 Add types parameter to check if only base layout styles are needed. 1614 * @since 6.6.0 Updated layout style specificity to be compatible with overall 0-1-0 specificity in global styles. 1615 * 1616 * @param array $block_metadata Metadata about the block to get styles for. 1617 * @param array $types Optional. Types of styles to output. If empty, all styles will be output. 1618 * @return string Layout styles for the block. 1619 */ 1620 protected function get_layout_styles( $block_metadata, $types = array() ) { 1621 $block_rules = ''; 1622 $block_type = null; 1623 1624 // Skip outputting layout styles if explicitly disabled. 1625 if ( current_theme_supports( 'disable-layout-styles' ) ) { 1626 return $block_rules; 1627 } 1628 1629 if ( isset( $block_metadata['name'] ) ) { 1630 $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] ); 1631 if ( ! block_has_support( $block_type, 'layout', false ) && ! block_has_support( $block_type, '__experimentalLayout', false ) ) { 1632 return $block_rules; 1633 } 1634 } 1635 1636 $selector = isset( $block_metadata['selector'] ) ? $block_metadata['selector'] : ''; 1637 $has_block_gap_support = isset( $this->theme_json['settings']['spacing']['blockGap'] ); 1638 $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. 1639 $node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() ); 1640 $layout_definitions = wp_get_layout_definitions(); 1641 $layout_selector_pattern = '/^[a-zA-Z0-9\-\.\,\ *+>:\(\)]*$/'; // Allow alphanumeric classnames, spaces, wildcard, sibling, child combinator and pseudo class selectors. 1642 1643 /* 1644 * Gap styles will only be output if the theme has block gap support, or supports a fallback gap. 1645 * Default layout gap styles will be skipped for themes that do not explicitly opt-in to blockGap with a `true` or `false` value. 1646 */ 1647 if ( $has_block_gap_support || $has_fallback_gap_support ) { 1648 $block_gap_value = null; 1649 // Use a fallback gap value if block gap support is not available. 1650 if ( ! $has_block_gap_support ) { 1651 $block_gap_value = static::ROOT_BLOCK_SELECTOR === $selector ? '0.5em' : null; 1652 if ( ! empty( $block_type ) ) { 1653 $block_gap_value = isset( $block_type->supports['spacing']['blockGap']['__experimentalDefault'] ) 1654 ? $block_type->supports['spacing']['blockGap']['__experimentalDefault'] 1655 : null; 1656 } 1657 } else { 1658 $block_gap_value = static::get_property_value( $node, array( 'spacing', 'blockGap' ) ); 1659 } 1660 1661 // Support split row / column values and concatenate to a shorthand value. 1662 if ( is_array( $block_gap_value ) ) { 1663 if ( isset( $block_gap_value['top'] ) && isset( $block_gap_value['left'] ) ) { 1664 $gap_row = static::get_property_value( $node, array( 'spacing', 'blockGap', 'top' ) ); 1665 $gap_column = static::get_property_value( $node, array( 'spacing', 'blockGap', 'left' ) ); 1666 $block_gap_value = $gap_row === $gap_column ? $gap_row : $gap_row . ' ' . $gap_column; 1667 } else { 1668 // Skip outputting gap value if not all sides are provided. 1669 $block_gap_value = null; 1670 } 1671 } 1672 1673 // If the block should have custom gap, add the gap styles. 1674 if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) { 1675 foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) { 1676 // Allow outputting fallback gap styles for flex and grid layout types when block gap support isn't available. 1677 if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key && 'grid' !== $layout_definition_key ) { 1678 continue; 1679 } 1680 1681 $class_name = isset( $layout_definition['className'] ) ? $layout_definition['className'] : false; 1682 $spacing_rules = isset( $layout_definition['spacingStyles'] ) ? $layout_definition['spacingStyles'] : array(); 1683 1684 if ( 1685 ! empty( $class_name ) && 1686 ! empty( $spacing_rules ) 1687 ) { 1688 foreach ( $spacing_rules as $spacing_rule ) { 1689 $declarations = array(); 1690 if ( 1691 isset( $spacing_rule['selector'] ) && 1692 preg_match( $layout_selector_pattern, $spacing_rule['selector'] ) && 1693 ! empty( $spacing_rule['rules'] ) 1694 ) { 1695 // Iterate over each of the styling rules and substitute non-string values such as `null` with the real `blockGap` value. 1696 foreach ( $spacing_rule['rules'] as $css_property => $css_value ) { 1697 $current_css_value = is_string( $css_value ) ? $css_value : $block_gap_value; 1698 if ( static::is_safe_css_declaration( $css_property, $current_css_value ) ) { 1699 $declarations[] = array( 1700 'name' => $css_property, 1701 'value' => $current_css_value, 1702 ); 1703 } 1704 } 1705 1706 if ( ! $has_block_gap_support ) { 1707 // For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles. 1708 $format = static::ROOT_BLOCK_SELECTOR === $selector ? ':where(.%2$s%3$s)' : ':where(%1$s.%2$s%3$s)'; 1709 $layout_selector = sprintf( 1710 $format, 1711 $selector, 1712 $class_name, 1713 $spacing_rule['selector'] 1714 ); 1715 } else { 1716 $format = static::ROOT_BLOCK_SELECTOR === $selector ? ':root :where(.%2$s)%3$s' : ':root :where(%1$s-%2$s)%3$s'; 1717 $layout_selector = sprintf( 1718 $format, 1719 $selector, 1720 $class_name, 1721 $spacing_rule['selector'] 1722 ); 1723 } 1724 $block_rules .= static::to_ruleset( $layout_selector, $declarations ); 1725 } 1726 } 1727 } 1728 } 1729 } 1730 } 1731 1732 // Output base styles. 1733 if ( 1734 static::ROOT_BLOCK_SELECTOR === $selector 1735 ) { 1736 $valid_display_modes = array( 'block', 'flex', 'grid' ); 1737 foreach ( $layout_definitions as $layout_definition ) { 1738 $class_name = isset( $layout_definition['className'] ) ? $layout_definition['className'] : false; 1739 $base_style_rules = isset( $layout_definition['baseStyles'] ) ? $layout_definition['baseStyles'] : array(); 1740 1741 if ( 1742 ! empty( $class_name ) && 1743 is_array( $base_style_rules ) 1744 ) { 1745 // Output display mode. This requires special handling as `display` is not exposed in `safe_style_css_filter`. 1746 if ( 1747 ! empty( $layout_definition['displayMode'] ) && 1748 is_string( $layout_definition['displayMode'] ) && 1749 in_array( $layout_definition['displayMode'], $valid_display_modes, true ) 1750 ) { 1751 $layout_selector = sprintf( 1752 '%s .%s', 1753 $selector, 1754 $class_name 1755 ); 1756 $block_rules .= static::to_ruleset( 1757 $layout_selector, 1758 array( 1759 array( 1760 'name' => 'display', 1761 'value' => $layout_definition['displayMode'], 1762 ), 1763 ) 1764 ); 1765 } 1766 1767 foreach ( $base_style_rules as $base_style_rule ) { 1768 $declarations = array(); 1769 1770 // Skip outputting base styles for flow and constrained layout types if theme doesn't support theme.json. The 'base-layout-styles' type flags this. 1771 if ( in_array( 'base-layout-styles', $types, true ) && ( 'default' === $layout_definition['name'] || 'constrained' === $layout_definition['name'] ) ) { 1772 continue; 1773 } 1774 1775 if ( 1776 isset( $base_style_rule['selector'] ) && 1777 preg_match( $layout_selector_pattern, $base_style_rule['selector'] ) && 1778 ! empty( $base_style_rule['rules'] ) 1779 ) { 1780 foreach ( $base_style_rule['rules'] as $css_property => $css_value ) { 1781 // Skip rules that reference content size or wide size if they are not defined in the theme.json. 1782 if ( 1783 is_string( $css_value ) && 1784 ( str_contains( $css_value, '--global--content-size' ) || str_contains( $css_value, '--global--wide-size' ) ) && 1785 ! isset( $this->theme_json['settings']['layout']['contentSize'] ) && 1786 ! isset( $this->theme_json['settings']['layout']['wideSize'] ) 1787 ) { 1788 continue; 1789 } 1790 1791 if ( static::is_safe_css_declaration( $css_property, $css_value ) ) { 1792 $declarations[] = array( 1793 'name' => $css_property, 1794 'value' => $css_value, 1795 ); 1796 } 1797 } 1798 1799 $layout_selector = sprintf( 1800 '.%s%s', 1801 $class_name, 1802 $base_style_rule['selector'] 1803 ); 1804 $block_rules .= static::to_ruleset( $layout_selector, $declarations ); 1805 } 1806 } 1807 } 1808 } 1809 } 1810 return $block_rules; 1811 } 1812 1813 /** 1814 * Creates new rulesets as classes for each preset value such as: 1815 * 1816 * .has-value-color { 1817 * color: value; 1818 * } 1819 * 1820 * .has-value-background-color { 1821 * background-color: value; 1822 * } 1823 * 1824 * .has-value-font-size { 1825 * font-size: value; 1826 * } 1827 * 1828 * .has-value-gradient-background { 1829 * background: value; 1830 * } 1831 * 1832 * p.has-value-gradient-background { 1833 * background: value; 1834 * } 1835 * 1836 * @since 5.9.0 1837 * 1838 * @param array $setting_nodes Nodes with settings. 1839 * @param string[] $origins List of origins to process presets from. 1840 * @return string The new stylesheet. 1841 */ 1842 protected function get_preset_classes( $setting_nodes, $origins ) { 1843 $preset_rules = ''; 1844 1845 foreach ( $setting_nodes as $metadata ) { 1846 if ( null === $metadata['selector'] ) { 1847 continue; 1848 } 1849 1850 $selector = $metadata['selector']; 1851 $node = _wp_array_get( $this->theme_json, $metadata['path'], array() ); 1852 $preset_rules .= static::compute_preset_classes( $node, $selector, $origins ); 1853 } 1854 1855 return $preset_rules; 1856 } 1857 1858 /** 1859 * Converts each styles section into a list of rulesets 1860 * to be appended to the stylesheet. 1861 * These rulesets contain all the css variables (custom variables and preset variables). 1862 * 1863 * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax 1864 * 1865 * For each section this creates a new ruleset such as: 1866 * 1867 * block-selector { 1868 * --wp--preset--category--slug: value; 1869 * --wp--custom--variable: value; 1870 * } 1871 * 1872 * @since 5.8.0 1873 * @since 5.9.0 Added the `$origins` parameter. 1874 * 1875 * @param array $nodes Nodes with settings. 1876 * @param string[] $origins List of origins to process. 1877 * @return string The new stylesheet. 1878 */ 1879 protected function get_css_variables( $nodes, $origins ) { 1880 $stylesheet = ''; 1881 foreach ( $nodes as $metadata ) { 1882 if ( null === $metadata['selector'] ) { 1883 continue; 1884 } 1885 1886 $selector = $metadata['selector']; 1887 1888 $node = _wp_array_get( $this->theme_json, $metadata['path'], array() ); 1889 $declarations = static::compute_preset_vars( $node, $origins ); 1890 $theme_vars_declarations = static::compute_theme_vars( $node ); 1891 foreach ( $theme_vars_declarations as $theme_vars_declaration ) { 1892 $declarations[] = $theme_vars_declaration; 1893 } 1894 1895 $stylesheet .= static::to_ruleset( $selector, $declarations ); 1896 } 1897 1898 return $stylesheet; 1899 } 1900 1901 /** 1902 * Given a selector and a declaration list, 1903 * creates the corresponding ruleset. 1904 * 1905 * @since 5.8.0 1906 * 1907 * @param string $selector CSS selector. 1908 * @param array $declarations List of declarations. 1909 * @return string The resulting CSS ruleset. 1910 */ 1911 protected static function to_ruleset( $selector, $declarations ) { 1912 if ( empty( $declarations ) ) { 1913 return ''; 1914 } 1915 1916 $declaration_block = array_reduce( 1917 $declarations, 1918 static function ( $carry, $element ) { 1919 return $carry .= $element['name'] . ': ' . $element['value'] . ';'; }, 1920 '' 1921 ); 1922 1923 return $selector . '{' . $declaration_block . '}'; 1924 } 1925 1926 /** 1927 * Given a settings array, returns the generated rulesets 1928 * for the preset classes. 1929 * 1930 * @since 5.8.0 1931 * @since 5.9.0 Added the `$origins` parameter. 1932 * @since 6.6.0 Added check for root CSS properties selector. 1933 * 1934 * @param array $settings Settings to process. 1935 * @param string $selector Selector wrapping the classes. 1936 * @param string[] $origins List of origins to process. 1937 * @return string The result of processing the presets. 1938 */ 1939 protected static function compute_preset_classes( $settings, $selector, $origins ) { 1940 if ( static::ROOT_BLOCK_SELECTOR === $selector || static::ROOT_CSS_PROPERTIES_SELECTOR === $selector ) { 1941 /* 1942 * Classes at the global level do not need any CSS prefixed, 1943 * and we don't want to increase its specificity. 1944 */ 1945 $selector = ''; 1946 } 1947 1948 $stylesheet = ''; 1949 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 1950 if ( empty( $preset_metadata['classes'] ) ) { 1951 continue; 1952 } 1953 $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins ); 1954 foreach ( $preset_metadata['classes'] as $class => $property ) { 1955 foreach ( $slugs as $slug ) { 1956 $css_var = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ); 1957 $class_name = static::replace_slug_in_string( $class, $slug ); 1958 1959 // $selector is often empty, so we can save ourselves the `append_to_selector()` call then. 1960 $new_selector = '' === $selector ? $class_name : static::append_to_selector( $selector, $class_name ); 1961 $stylesheet .= static::to_ruleset( 1962 $new_selector, 1963 array( 1964 array( 1965 'name' => $property, 1966 'value' => 'var(' . $css_var . ') !important', 1967 ), 1968 ) 1969 ); 1970 } 1971 } 1972 } 1973 1974 return $stylesheet; 1975 } 1976 1977 /** 1978 * Function that scopes a selector with another one. This works a bit like 1979 * SCSS nesting except the `&` operator isn't supported. 1980 * 1981 * <code> 1982 * $scope = '.a, .b .c'; 1983 * $selector = '> .x, .y'; 1984 * $merged = scope_selector( $scope, $selector ); 1985 * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y' 1986 * </code> 1987 * 1988 * @since 5.9.0 1989 * @since 6.6.0 Added early return if missing scope or selector. 1990 * 1991 * @param string $scope Selector to scope to. 1992 * @param string $selector Original selector. 1993 * @return string Scoped selector. 1994 */ 1995 public static function scope_selector( $scope, $selector ) { 1996 if ( ! $scope || ! $selector ) { 1997 return $selector; 1998 } 1999 2000 $scopes = explode( ',', $scope ); 2001 $selectors = explode( ',', $selector ); 2002 2003 $selectors_scoped = array(); 2004 foreach ( $scopes as $outer ) { 2005 foreach ( $selectors as $inner ) { 2006 $outer = trim( $outer ); 2007 $inner = trim( $inner ); 2008 if ( ! empty( $outer ) && ! empty( $inner ) ) { 2009 $selectors_scoped[] = $outer . ' ' . $inner; 2010 } elseif ( empty( $outer ) ) { 2011 $selectors_scoped[] = $inner; 2012 } elseif ( empty( $inner ) ) { 2013 $selectors_scoped[] = $outer; 2014 } 2015 } 2016 } 2017 2018 $result = implode( ', ', $selectors_scoped ); 2019 return $result; 2020 } 2021 2022 /** 2023 * Scopes the selectors for a given style node. 2024 * 2025 * This includes the primary selector, i.e. `$node['selector']`, as well as any custom 2026 * selectors for features and subfeatures, e.g. `$node['selectors']['border']` etc. 2027 * 2028 * @since 6.6.0 2029 * 2030 * @param string $scope Selector to scope to. 2031 * @param array $node Style node with selectors to scope. 2032 * @return array Node with updated selectors. 2033 */ 2034 protected static function scope_style_node_selectors( $scope, $node ) { 2035 $node['selector'] = static::scope_selector( $scope, $node['selector'] ); 2036 2037 if ( empty( $node['selectors'] ) ) { 2038 return $node; 2039 } 2040 2041 foreach ( $node['selectors'] as $feature => $selector ) { 2042 if ( is_string( $selector ) ) { 2043 $node['selectors'][ $feature ] = static::scope_selector( $scope, $selector ); 2044 } 2045 if ( is_array( $selector ) ) { 2046 foreach ( $selector as $subfeature => $subfeature_selector ) { 2047 $node['selectors'][ $feature ][ $subfeature ] = static::scope_selector( $scope, $subfeature_selector ); 2048 } 2049 } 2050 } 2051 2052 return $node; 2053 } 2054 2055 /** 2056 * Gets preset values keyed by slugs based on settings and metadata. 2057 * 2058 * <code> 2059 * $settings = array( 2060 * 'typography' => array( 2061 * 'fontFamilies' => array( 2062 * array( 2063 * 'slug' => 'sansSerif', 2064 * 'fontFamily' => '"Helvetica Neue", sans-serif', 2065 * ), 2066 * array( 2067 * 'slug' => 'serif', 2068 * 'colors' => 'Georgia, serif', 2069 * ) 2070 * ), 2071 * ), 2072 * ); 2073 * $meta = array( 2074 * 'path' => array( 'typography', 'fontFamilies' ), 2075 * 'value_key' => 'fontFamily', 2076 * ); 2077 * $values_by_slug = get_settings_values_by_slug(); 2078 * // $values_by_slug === array( 2079 * // 'sans-serif' => '"Helvetica Neue", sans-serif', 2080 * // 'serif' => 'Georgia, serif', 2081 * // ); 2082 * </code> 2083 * 2084 * @since 5.9.0 2085 * @since 6.6.0 Passing $settings to the callbacks defined in static::PRESETS_METADATA. 2086 * 2087 * @param array $settings Settings to process. 2088 * @param array $preset_metadata One of the PRESETS_METADATA values. 2089 * @param string[] $origins List of origins to process. 2090 * @return array Array of presets where each key is a slug and each value is the preset value. 2091 */ 2092 protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) { 2093 $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() ); 2094 2095 $result = array(); 2096 foreach ( $origins as $origin ) { 2097 if ( ! isset( $preset_per_origin[ $origin ] ) ) { 2098 continue; 2099 } 2100 foreach ( $preset_per_origin[ $origin ] as $preset ) { 2101 $slug = _wp_to_kebab_case( $preset['slug'] ); 2102 2103 $value = ''; 2104 if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) { 2105 $value_key = $preset_metadata['value_key']; 2106 $value = $preset[ $value_key ]; 2107 } elseif ( 2108 isset( $preset_metadata['value_func'] ) && 2109 is_callable( $preset_metadata['value_func'] ) 2110 ) { 2111 $value_func = $preset_metadata['value_func']; 2112 $value = call_user_func( $value_func, $preset, $settings ); 2113 } else { 2114 // If we don't have a value, then don't add it to the result. 2115 continue; 2116 } 2117 2118 $result[ $slug ] = $value; 2119 } 2120 } 2121 return $result; 2122 } 2123 2124 /** 2125 * Similar to get_settings_values_by_slug, but doesn't compute the value. 2126 * 2127 * @since 5.9.0 2128 * 2129 * @param array $settings Settings to process. 2130 * @param array $preset_metadata One of the PRESETS_METADATA values. 2131 * @param string[] $origins List of origins to process. 2132 * @return array Array of presets where the key and value are both the slug. 2133 */ 2134 protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) { 2135 if ( null === $origins ) { 2136 $origins = static::VALID_ORIGINS; 2137 } 2138 2139 $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() ); 2140 2141 $result = array(); 2142 foreach ( $origins as $origin ) { 2143 if ( ! isset( $preset_per_origin[ $origin ] ) ) { 2144 continue; 2145 } 2146 foreach ( $preset_per_origin[ $origin ] as $preset ) { 2147 $slug = _wp_to_kebab_case( $preset['slug'] ); 2148 2149 // Use the array as a set so we don't get duplicates. 2150 $result[ $slug ] = $slug; 2151 } 2152 } 2153 return $result; 2154 } 2155 2156 /** 2157 * Transforms a slug into a CSS Custom Property. 2158 * 2159 * @since 5.9.0 2160 * 2161 * @param string $input String to replace. 2162 * @param string $slug The slug value to use to generate the custom property. 2163 * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`. 2164 */ 2165 protected static function replace_slug_in_string( $input, $slug ) { 2166 return strtr( $input, array( '$slug' => $slug ) ); 2167 } 2168 2169 /** 2170 * Given the block settings, extracts the CSS Custom Properties 2171 * for the presets and adds them to the $declarations array 2172 * following the format: 2173 * 2174 * array( 2175 * 'name' => 'property_name', 2176 * 'value' => 'property_value, 2177 * ) 2178 * 2179 * @since 5.8.0 2180 * @since 5.9.0 Added the `$origins` parameter. 2181 * 2182 * @param array $settings Settings to process. 2183 * @param string[] $origins List of origins to process. 2184 * @return array The modified $declarations. 2185 */ 2186 protected static function compute_preset_vars( $settings, $origins ) { 2187 $declarations = array(); 2188 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 2189 if ( empty( $preset_metadata['css_vars'] ) ) { 2190 continue; 2191 } 2192 $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins ); 2193 foreach ( $values_by_slug as $slug => $value ) { 2194 $declarations[] = array( 2195 'name' => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ), 2196 'value' => $value, 2197 ); 2198 } 2199 } 2200 2201 return $declarations; 2202 } 2203 2204 /** 2205 * Given an array of settings, extracts the CSS Custom Properties 2206 * for the custom values and adds them to the $declarations 2207 * array following the format: 2208 * 2209 * array( 2210 * 'name' => 'property_name', 2211 * 'value' => 'property_value, 2212 * ) 2213 * 2214 * @since 5.8.0 2215 * 2216 * @param array $settings Settings to process. 2217 * @return array The modified $declarations. 2218 */ 2219 protected static function compute_theme_vars( $settings ) { 2220 $declarations = array(); 2221 $custom_values = isset( $settings['custom'] ) ? $settings['custom'] : array(); 2222 $css_vars = static::flatten_tree( $custom_values ); 2223 foreach ( $css_vars as $key => $value ) { 2224 $declarations[] = array( 2225 'name' => '--wp--custom--' . $key, 2226 'value' => $value, 2227 ); 2228 } 2229 2230 return $declarations; 2231 } 2232 2233 /** 2234 * Given a tree, it creates a flattened one 2235 * by merging the keys and binding the leaf values 2236 * to the new keys. 2237 * 2238 * It also transforms camelCase names into kebab-case 2239 * and substitutes '/' by '-'. 2240 * 2241 * This is thought to be useful to generate 2242 * CSS Custom Properties from a tree, 2243 * although there's nothing in the implementation 2244 * of this function that requires that format. 2245 * 2246 * For example, assuming the given prefix is '--wp' 2247 * and the token is '--', for this input tree: 2248 * 2249 * { 2250 * 'some/property': 'value', 2251 * 'nestedProperty': { 2252 * 'sub-property': 'value' 2253 * } 2254 * } 2255 * 2256 * it'll return this output: 2257 * 2258 * { 2259 * '--wp--some-property': 'value', 2260 * '--wp--nested-property--sub-property': 'value' 2261 * } 2262 * 2263 * @since 5.8.0 2264 * 2265 * @param array $tree Input tree to process. 2266 * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string. 2267 * @param string $token Optional. Token to use between levels. Default '--'. 2268 * @return array The flattened tree. 2269 */ 2270 protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) { 2271 $result = array(); 2272 foreach ( $tree as $property => $value ) { 2273 $new_key = $prefix . str_replace( 2274 '/', 2275 '-', 2276 strtolower( _wp_to_kebab_case( $property ) ) 2277 ); 2278 2279 if ( is_array( $value ) ) { 2280 $new_prefix = $new_key . $token; 2281 $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token ); 2282 foreach ( $flattened_subtree as $subtree_key => $subtree_value ) { 2283 $result[ $subtree_key ] = $subtree_value; 2284 } 2285 } else { 2286 $result[ $new_key ] = $value; 2287 } 2288 } 2289 return $result; 2290 } 2291 2292 /** 2293 * Given a styles array, it extracts the style properties 2294 * and adds them to the $declarations array following the format: 2295 * 2296 * array( 2297 * 'name' => 'property_name', 2298 * 'value' => 'property_value', 2299 * ) 2300 * 2301 * @since 5.8.0 2302 * @since 5.9.0 Added the `$settings` and `$properties` parameters. 2303 * @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters. 2304 * @since 6.5.0 Output a `min-height: unset` rule when `aspect-ratio` is set. 2305 * @since 6.6.0 Pass current theme JSON settings to wp_get_typography_font_size_value(), and process background properties. 2306 * @since 6.7.0 `ref` resolution of background properties, and assigning custom default values. 2307 * 2308 * @param array $styles Styles to process. 2309 * @param array $settings Theme settings. 2310 * @param array $properties Properties metadata. 2311 * @param array $theme_json Theme JSON array. 2312 * @param string $selector The style block selector. 2313 * @param boolean $use_root_padding Whether to add custom properties at root level. 2314 * @return array Returns the modified $declarations. 2315 */ 2316 protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) { 2317 if ( empty( $styles ) ) { 2318 return array(); 2319 } 2320 2321 if ( null === $properties ) { 2322 $properties = static::PROPERTIES_METADATA; 2323 } 2324 $declarations = array(); 2325 $root_variable_duplicates = array(); 2326 $root_style_length = strlen( '--wp--style--root--' ); 2327 2328 foreach ( $properties as $css_property => $value_path ) { 2329 if ( ! is_array( $value_path ) ) { 2330 continue; 2331 } 2332 2333 $is_root_style = str_starts_with( $css_property, '--wp--style--root--' ); 2334 if ( $is_root_style && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) { 2335 continue; 2336 } 2337 2338 $value = static::get_property_value( $styles, $value_path, $theme_json ); 2339 2340 /* 2341 * Root-level padding styles don't currently support strings with CSS shorthand values. 2342 * This may change: https://github.com/WordPress/gutenberg/issues/40132. 2343 */ 2344 if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) { 2345 continue; 2346 } 2347 2348 if ( $is_root_style && $use_root_padding ) { 2349 $root_variable_duplicates[] = substr( $css_property, $root_style_length ); 2350 } 2351 2352 /* 2353 * Processes background image styles. 2354 * If the value is a URL, it will be converted to a CSS `url()` value. 2355 * For uploaded image (images with a database ID), apply size and position defaults, 2356 * equal to those applied in block supports in lib/background.php. 2357 */ 2358 if ( 'background-image' === $css_property && ! empty( $value ) ) { 2359 $background_styles = wp_style_engine_get_styles( 2360 array( 'background' => array( 'backgroundImage' => $value ) ) 2361 ); 2362 $value = $background_styles['declarations'][ $css_property ]; 2363 } 2364 if ( empty( $value ) && static::ROOT_BLOCK_SELECTOR !== $selector && ! empty( $styles['background']['backgroundImage']['id'] ) ) { 2365 if ( 'background-size' === $css_property ) { 2366 $value = 'cover'; 2367 } 2368 // If the background size is set to `contain` and no position is set, set the position to `center`. 2369 if ( 'background-position' === $css_property ) { 2370 $background_size = $styles['background']['backgroundSize'] ?? null; 2371 $value = 'contain' === $background_size ? '50% 50%' : null; 2372 } 2373 } 2374 2375 // Skip if empty and not "0" or value represents array of longhand values. 2376 $has_missing_value = empty( $value ) && ! is_numeric( $value ); 2377 if ( $has_missing_value || is_array( $value ) ) { 2378 continue; 2379 } 2380 2381 /* 2382 * Look up protected properties, keyed by value path. 2383 * Skip protected properties that are explicitly set to `null`. 2384 */ 2385 $path_string = implode( '.', $value_path ); 2386 if ( 2387 isset( static::PROTECTED_PROPERTIES[ $path_string ] ) && 2388 _wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null 2389 ) { 2390 continue; 2391 } 2392 2393 // Calculates fluid typography rules where available. 2394 if ( 'font-size' === $css_property ) { 2395 /* 2396 * wp_get_typography_font_size_value() will check 2397 * if fluid typography has been activated and also 2398 * whether the incoming value can be converted to a fluid value. 2399 * Values that already have a clamp() function will not pass the test, 2400 * and therefore the original $value will be returned. 2401 * Pass the current theme_json settings to override any global settings. 2402 */ 2403 $value = wp_get_typography_font_size_value( array( 'size' => $value ), $settings ); 2404 } 2405 2406 if ( 'aspect-ratio' === $css_property ) { 2407 // For aspect ratio to work, other dimensions rules must be unset. 2408 // This ensures that a fixed height does not override the aspect ratio. 2409 $declarations[] = array( 2410 'name' => 'min-height', 2411 'value' => 'unset', 2412 ); 2413 } 2414 2415 $declarations[] = array( 2416 'name' => $css_property, 2417 'value' => $value, 2418 ); 2419 } 2420 2421 // If a variable value is added to the root, the corresponding property should be removed. 2422 foreach ( $root_variable_duplicates as $duplicate ) { 2423 $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true ); 2424 if ( is_numeric( $discard ) ) { 2425 array_splice( $declarations, $discard, 1 ); 2426 } 2427 } 2428 2429 return $declarations; 2430 } 2431 2432 /** 2433 * Returns the style property for the given path. 2434 * 2435 * It also converts references to a path to the value 2436 * stored at that location, e.g. 2437 * { "ref": "style.color.background" } => "#fff". 2438 * 2439 * @since 5.8.0 2440 * @since 5.9.0 Added support for values of array type, which are returned as is. 2441 * @since 6.1.0 Added the `$theme_json` parameter. 2442 * @since 6.3.0 It no longer converts the internal format "var:preset|color|secondary" 2443 * to the standard form "--wp--preset--color--secondary". 2444 * This is already done by the sanitize method, 2445 * so every property will be in the standard form. 2446 * @since 6.7.0 Added support for background image refs. 2447 * 2448 * @param array $styles Styles subtree. 2449 * @param array $path Which property to process. 2450 * @param array $theme_json Theme JSON array. 2451 * @return string|array Style property value. 2452 */ 2453 protected static function get_property_value( $styles, $path, $theme_json = null ) { 2454 $value = _wp_array_get( $styles, $path, '' ); 2455 2456 if ( '' === $value || null === $value ) { 2457 // No need to process the value further. 2458 return ''; 2459 } 2460 2461 /* 2462 * This converts references to a path to the value at that path 2463 * where the value is an array with a "ref" key, pointing to a path. 2464 * For example: { "ref": "style.color.background" } => "#fff". 2465 * In the case of backgroundImage, if both a ref and a URL are present in the value, 2466 * the URL takes precedence and the ref is ignored. 2467 */ 2468 if ( is_array( $value ) && isset( $value['ref'] ) ) { 2469 $value_path = explode( '.', $value['ref'] ); 2470 $ref_value = _wp_array_get( $theme_json, $value_path ); 2471 // Background Image refs can refer to a string or an array containing a URL string. 2472 $ref_value_url = $ref_value['url'] ?? null; 2473 // Only use the ref value if we find anything. 2474 if ( ! empty( $ref_value ) && ( is_string( $ref_value ) || is_string( $ref_value_url ) ) ) { 2475 $value = $ref_value; 2476 } 2477 2478 if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) { 2479 $path_string = json_encode( $path ); 2480 $ref_value_string = json_encode( $ref_value ); 2481 _doing_it_wrong( 2482 'get_property_value', 2483 sprintf( 2484 /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */ 2485 __( '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.' ), 2486 'theme.json', 2487 $ref_value_string, 2488 $path_string, 2489 $ref_value['ref'] 2490 ), 2491 '6.1.0' 2492 ); 2493 } 2494 } 2495 2496 if ( is_array( $value ) ) { 2497 return $value; 2498 } 2499 2500 return $value; 2501 } 2502 2503 /** 2504 * Builds metadata for the setting nodes, which returns in the form of: 2505 * 2506 * [ 2507 * [ 2508 * 'path' => ['path', 'to', 'some', 'node' ], 2509 * 'selector' => 'CSS selector for some node' 2510 * ], 2511 * [ 2512 * 'path' => [ 'path', 'to', 'other', 'node' ], 2513 * 'selector' => 'CSS selector for other node' 2514 * ], 2515 * ] 2516 * 2517 * @since 5.8.0 2518 * 2519 * @param array $theme_json The tree to extract setting nodes from. 2520 * @param array $selectors List of selectors per block. 2521 * @return array An array of setting nodes metadata. 2522 */ 2523 protected static function get_setting_nodes( $theme_json, $selectors = array() ) { 2524 $nodes = array(); 2525 if ( ! isset( $theme_json['settings'] ) ) { 2526 return $nodes; 2527 } 2528 2529 // Top-level. 2530 $nodes[] = array( 2531 'path' => array( 'settings' ), 2532 'selector' => static::ROOT_CSS_PROPERTIES_SELECTOR, 2533 ); 2534 2535 // Calculate paths for blocks. 2536 if ( ! isset( $theme_json['settings']['blocks'] ) ) { 2537 return $nodes; 2538 } 2539 2540 foreach ( $theme_json['settings']['blocks'] as $name => $node ) { 2541 $selector = null; 2542 if ( isset( $selectors[ $name ]['selector'] ) ) { 2543 $selector = $selectors[ $name ]['selector']; 2544 } 2545 2546 $nodes[] = array( 2547 'path' => array( 'settings', 'blocks', $name ), 2548 'selector' => $selector, 2549 ); 2550 } 2551 2552 return $nodes; 2553 } 2554 2555 /** 2556 * Builds metadata for the style nodes, which returns in the form of: 2557 * 2558 * [ 2559 * [ 2560 * 'path' => [ 'path', 'to', 'some', 'node' ], 2561 * 'selector' => 'CSS selector for some node', 2562 * 'duotone' => 'CSS selector for duotone for some node' 2563 * ], 2564 * [ 2565 * 'path' => ['path', 'to', 'other', 'node' ], 2566 * 'selector' => 'CSS selector for other node', 2567 * 'duotone' => null 2568 * ], 2569 * ] 2570 * 2571 * @since 5.8.0 2572 * @since 6.6.0 Added options array for modifying generated nodes. 2573 * 2574 * @param array $theme_json The tree to extract style nodes from. 2575 * @param array $selectors List of selectors per block. 2576 * @param array $options { 2577 * Optional. An array of options for now used for internal purposes only (may change without notice). 2578 * 2579 * @type bool $include_block_style_variations Includes style nodes for block style variations. Default false. 2580 * } 2581 * @return array An array of style nodes metadata. 2582 */ 2583 protected static function get_style_nodes( $theme_json, $selectors = array(), $options = array() ) { 2584 $nodes = array(); 2585 if ( ! isset( $theme_json['styles'] ) ) { 2586 return $nodes; 2587 } 2588 2589 // Top-level. 2590 $nodes[] = array( 2591 'path' => array( 'styles' ), 2592 'selector' => static::ROOT_BLOCK_SELECTOR, 2593 ); 2594 2595 if ( isset( $theme_json['styles']['elements'] ) ) { 2596 foreach ( self::ELEMENTS as $element => $selector ) { 2597 if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) { 2598 continue; 2599 } 2600 $nodes[] = array( 2601 'path' => array( 'styles', 'elements', $element ), 2602 'selector' => static::ELEMENTS[ $element ], 2603 ); 2604 2605 // Handle any pseudo selectors for the element. 2606 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) { 2607 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) { 2608 2609 if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) { 2610 $nodes[] = array( 2611 'path' => array( 'styles', 'elements', $element ), 2612 'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ), 2613 ); 2614 } 2615 } 2616 } 2617 } 2618 } 2619 2620 // Blocks. 2621 if ( ! isset( $theme_json['styles']['blocks'] ) ) { 2622 return $nodes; 2623 } 2624 2625 $block_nodes = static::get_block_nodes( $theme_json, $selectors, $options ); 2626 foreach ( $block_nodes as $block_node ) { 2627 $nodes[] = $block_node; 2628 } 2629 2630 /** 2631 * Filters the list of style nodes with metadata. 2632 * 2633 * This allows for things like loading block CSS independently. 2634 * 2635 * @since 6.1.0 2636 * 2637 * @param array $nodes Style nodes with metadata. 2638 */ 2639 return apply_filters( 'wp_theme_json_get_style_nodes', $nodes ); 2640 } 2641 2642 /** 2643 * A public helper to get the block nodes from a theme.json file. 2644 * 2645 * @since 6.1.0 2646 * 2647 * @return array The block nodes in theme.json. 2648 */ 2649 public function get_styles_block_nodes() { 2650 return static::get_block_nodes( $this->theme_json ); 2651 } 2652 2653 /** 2654 * Returns a filtered declarations array if there is a separator block with only a background 2655 * style defined in theme.json by adding a color attribute to reflect the changes in the front. 2656 * 2657 * @since 6.1.1 2658 * 2659 * @param array $declarations List of declarations. 2660 * @return array $declarations List of declarations filtered. 2661 */ 2662 private static function update_separator_declarations( $declarations ) { 2663 $background_color = ''; 2664 $border_color_matches = false; 2665 $text_color_matches = false; 2666 2667 foreach ( $declarations as $declaration ) { 2668 if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) { 2669 $background_color = $declaration['value']; 2670 } elseif ( 'border-color' === $declaration['name'] ) { 2671 $border_color_matches = true; 2672 } elseif ( 'color' === $declaration['name'] ) { 2673 $text_color_matches = true; 2674 } 2675 2676 if ( $background_color && $border_color_matches && $text_color_matches ) { 2677 break; 2678 } 2679 } 2680 2681 if ( $background_color && ! $border_color_matches && ! $text_color_matches ) { 2682 $declarations[] = array( 2683 'name' => 'color', 2684 'value' => $background_color, 2685 ); 2686 } 2687 2688 return $declarations; 2689 } 2690 2691 /** 2692 * An internal method to get the block nodes from a theme.json file. 2693 * 2694 * @since 6.1.0 2695 * @since 6.3.0 Refactored and stabilized selectors API. 2696 * @since 6.6.0 Added optional selectors and options for generating block nodes. 2697 * @since 6.7.0 Added $include_node_paths_only option. 2698 * 2699 * @param array $theme_json The theme.json converted to an array. 2700 * @param array $selectors Optional list of selectors per block. 2701 * @param array $options { 2702 * Optional. An array of options for now used for internal purposes only (may change without notice). 2703 * 2704 * @type bool $include_block_style_variations Include nodes for block style variations. Default false. 2705 * @type bool $include_node_paths_only Return only block nodes node paths. Default false. 2706 * } 2707 * @return array The block nodes in theme.json. 2708 */ 2709 private static function get_block_nodes( $theme_json, $selectors = array(), $options = array() ) { 2710 $nodes = array(); 2711 2712 if ( ! isset( $theme_json['styles']['blocks'] ) ) { 2713 return $nodes; 2714 } 2715 2716 $include_variations = $options['include_block_style_variations'] ?? false; 2717 $include_node_paths_only = $options['include_node_paths_only'] ?? false; 2718 2719 // If only node paths are to be returned, skip selector assignment. 2720 if ( ! $include_node_paths_only ) { 2721 $selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors; 2722 } 2723 2724 foreach ( $theme_json['styles']['blocks'] as $name => $node ) { 2725 $node_path = array( 'styles', 'blocks', $name ); 2726 if ( $include_node_paths_only ) { 2727 $variation_paths = array(); 2728 if ( $include_variations && isset( $node['variations'] ) ) { 2729 foreach ( $node['variations'] as $variation => $variation_node ) { 2730 $variation_paths[] = array( 2731 'path' => array( 'styles', 'blocks', $name, 'variations', $variation ), 2732 ); 2733 } 2734 } 2735 $node = array( 2736 'path' => $node_path, 2737 ); 2738 if ( ! empty( $variation_paths ) ) { 2739 $node['variations'] = $variation_paths; 2740 } 2741 $nodes[] = $node; 2742 } else { 2743 $selector = null; 2744 if ( isset( $selectors[ $name ]['selector'] ) ) { 2745 $selector = $selectors[ $name ]['selector']; 2746 } 2747 2748 $duotone_selector = null; 2749 if ( isset( $selectors[ $name ]['duotone'] ) ) { 2750 $duotone_selector = $selectors[ $name ]['duotone']; 2751 } 2752 2753 $feature_selectors = null; 2754 if ( isset( $selectors[ $name ]['selectors'] ) ) { 2755 $feature_selectors = $selectors[ $name ]['selectors']; 2756 } 2757 2758 $variation_selectors = array(); 2759 if ( $include_variations && isset( $node['variations'] ) ) { 2760 foreach ( $node['variations'] as $variation => $node ) { 2761 $variation_selectors[] = array( 2762 'path' => array( 'styles', 'blocks', $name, 'variations', $variation ), 2763 'selector' => $selectors[ $name ]['styleVariations'][ $variation ], 2764 ); 2765 } 2766 } 2767 2768 $nodes[] = array( 2769 'name' => $name, 2770 'path' => $node_path, 2771 'selector' => $selector, 2772 'selectors' => $feature_selectors, 2773 'duotone' => $duotone_selector, 2774 'features' => $feature_selectors, 2775 'variations' => $variation_selectors, 2776 'css' => $selector, 2777 ); 2778 } 2779 2780 if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) { 2781 foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) { 2782 $node_path = array( 'styles', 'blocks', $name, 'elements', $element ); 2783 if ( $include_node_paths_only ) { 2784 $nodes[] = array( 2785 'path' => $node_path, 2786 ); 2787 continue; 2788 } 2789 2790 $nodes[] = array( 2791 'path' => $node_path, 2792 'selector' => $selectors[ $name ]['elements'][ $element ], 2793 ); 2794 2795 // Handle any pseudo selectors for the element. 2796 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) { 2797 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) { 2798 if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) { 2799 $node_path = array( 'styles', 'blocks', $name, 'elements', $element ); 2800 if ( $include_node_paths_only ) { 2801 $nodes[] = array( 2802 'path' => $node_path, 2803 ); 2804 continue; 2805 } 2806 2807 $nodes[] = array( 2808 'path' => $node_path, 2809 'selector' => static::append_to_selector( $selectors[ $name ]['elements'][ $element ], $pseudo_selector ), 2810 ); 2811 } 2812 } 2813 } 2814 } 2815 } 2816 } 2817 2818 return $nodes; 2819 } 2820 2821 /** 2822 * Gets the CSS rules for a particular block from theme.json. 2823 * 2824 * @since 6.1.0 2825 * @since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image. 2826 * Updated general global styles specificity to 0-1-0. 2827 * Fixed custom CSS output in block style variations. 2828 * 2829 * @param array $block_metadata Metadata about the block to get styles for. 2830 * @return string Styles for the block. 2831 */ 2832 public function get_styles_for_block( $block_metadata ) { 2833 $node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() ); 2834 $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments']; 2835 $selector = $block_metadata['selector']; 2836 $settings = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array(); 2837 $feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $node ); 2838 $is_root_selector = static::ROOT_BLOCK_SELECTOR === $selector; 2839 2840 // If there are style variations, generate the declarations for them, including any feature selectors the block may have. 2841 $style_variation_declarations = array(); 2842 $style_variation_custom_css = array(); 2843 if ( ! empty( $block_metadata['variations'] ) ) { 2844 foreach ( $block_metadata['variations'] as $style_variation ) { 2845 $style_variation_node = _wp_array_get( $this->theme_json, $style_variation['path'], array() ); 2846 $clean_style_variation_selector = trim( $style_variation['selector'] ); 2847 2848 // Generate any feature/subfeature style declarations for the current style variation. 2849 $variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node ); 2850 2851 // Combine selectors with style variation's selector and add to overall style variation declarations. 2852 foreach ( $variation_declarations as $current_selector => $new_declarations ) { 2853 // If current selector includes block classname, remove it but leave the whitespace in. 2854 $shortened_selector = str_replace( $block_metadata['selector'] . ' ', ' ', $current_selector ); 2855 2856 // Prepend the variation selector to the current selector. 2857 $split_selectors = explode( ',', $shortened_selector ); 2858 $updated_selectors = array_map( 2859 static function ( $split_selector ) use ( $clean_style_variation_selector ) { 2860 return $clean_style_variation_selector . $split_selector; 2861 }, 2862 $split_selectors 2863 ); 2864 $combined_selectors = implode( ',', $updated_selectors ); 2865 2866 // Add the new declarations to the overall results under the modified selector. 2867 $style_variation_declarations[ $combined_selectors ] = $new_declarations; 2868 } 2869 2870 // Compute declarations for remaining styles not covered by feature level selectors. 2871 $style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json ); 2872 // Store custom CSS for the style variation. 2873 if ( isset( $style_variation_node['css'] ) ) { 2874 $style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] ); 2875 } 2876 } 2877 } 2878 /* 2879 * Get a reference to element name from path. 2880 * $block_metadata['path'] = array( 'styles','elements','link' ); 2881 * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ]. 2882 * Skip non-element paths like just ['styles']. 2883 */ 2884 $is_processing_element = in_array( 'elements', $block_metadata['path'], true ); 2885 2886 $current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null; 2887 2888 $element_pseudo_allowed = array(); 2889 2890 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) { 2891 $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ]; 2892 } 2893 2894 /* 2895 * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover"). 2896 * This also resets the array keys. 2897 */ 2898 $pseudo_matches = array_values( 2899 array_filter( 2900 $element_pseudo_allowed, 2901 static function ( $pseudo_selector ) use ( $selector ) { 2902 return str_contains( $selector, $pseudo_selector ); 2903 } 2904 ) 2905 ); 2906 2907 $pseudo_selector = isset( $pseudo_matches[0] ) ? $pseudo_matches[0] : null; 2908 2909 /* 2910 * If the current selector is a pseudo selector that's defined in the allow list for the current 2911 * element then compute the style properties for it. 2912 * Otherwise just compute the styles for the default selector as normal. 2913 */ 2914 if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) && 2915 isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) 2916 && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true ) 2917 ) { 2918 $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding ); 2919 } else { 2920 $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding ); 2921 } 2922 2923 $block_rules = ''; 2924 2925 /* 2926 * 1. Bespoke declaration modifiers: 2927 * - 'filter': Separate the declarations that use the general selector 2928 * from the ones using the duotone selector. 2929 * - 'background|background-image': set the html min-height to 100% 2930 * to ensure the background covers the entire viewport. 2931 */ 2932 $declarations_duotone = array(); 2933 $should_set_root_min_height = false; 2934 2935 foreach ( $declarations as $index => $declaration ) { 2936 if ( 'filter' === $declaration['name'] ) { 2937 /* 2938 * 'unset' filters happen when a filter is unset 2939 * in the site-editor UI. Because the 'unset' value 2940 * in the user origin overrides the value in the 2941 * theme origin, we can skip rendering anything 2942 * here as no filter needs to be applied anymore. 2943 * So only add declarations to with values other 2944 * than 'unset'. 2945 */ 2946 if ( 'unset' !== $declaration['value'] ) { 2947 $declarations_duotone[] = $declaration; 2948 } 2949 unset( $declarations[ $index ] ); 2950 } 2951 2952 if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) { 2953 $should_set_root_min_height = true; 2954 } 2955 } 2956 2957 /* 2958 * If root styles has a background-image or a background (gradient) set, 2959 * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view. 2960 * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly, 2961 * and matches the behavior of the site editor. 2962 */ 2963 if ( $should_set_root_min_height ) { 2964 $block_rules .= static::to_ruleset( 2965 'html', 2966 array( 2967 array( 2968 'name' => 'min-height', 2969 'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))', 2970 ), 2971 ) 2972 ); 2973 } 2974 2975 // Update declarations if there are separators with only background color defined. 2976 if ( '.wp-block-separator' === $selector ) { 2977 $declarations = static::update_separator_declarations( $declarations ); 2978 } 2979 2980 /* 2981 * Root selector (body) styles should not be wrapped in `:root where()` to keep 2982 * specificity at (0,0,1) and maintain backwards compatibility. 2983 * 2984 * Top-level element styles using element-only specificity selectors should 2985 * not get wrapped in `:root :where()` to maintain backwards compatibility. 2986 * 2987 * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so 2988 * still need to be wrapped in `:root :where` to cap specificity for nested 2989 * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly. 2990 */ 2991 $element_only_selector = $is_root_selector || ( 2992 $current_element && 2993 isset( static::ELEMENTS[ $current_element ] ) && 2994 // buttons, captions etc. still need `:root :where()` as they are class based selectors. 2995 ! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) && 2996 static::ELEMENTS[ $current_element ] === $selector 2997 ); 2998 2999 // 2. Generate and append the rules that use the general selector. 3000 $general_selector = $element_only_selector ? $selector : ":root :where($selector)"; 3001 $block_rules .= static::to_ruleset( $general_selector, $declarations ); 3002 3003 // 3. Generate and append the rules that use the duotone selector. 3004 if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) { 3005 $block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone ); 3006 } 3007 3008 // 4. Generate Layout block gap styles. 3009 if ( 3010 ! $is_root_selector && 3011 ! empty( $block_metadata['name'] ) 3012 ) { 3013 $block_rules .= $this->get_layout_styles( $block_metadata ); 3014 } 3015 3016 // 5. Generate and append the feature level rulesets. 3017 foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) { 3018 $block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations ); 3019 } 3020 3021 // 6. Generate and append the style variation rulesets. 3022 foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) { 3023 $block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations ); 3024 if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) { 3025 $block_rules .= $style_variation_custom_css[ $style_variation_selector ]; 3026 } 3027 } 3028 3029 // 7. Generate and append any custom CSS rules. 3030 if ( isset( $node['css'] ) && ! $is_root_selector ) { 3031 $block_rules .= $this->process_blocks_custom_css( $node['css'], $selector ); 3032 } 3033 3034 return $block_rules; 3035 } 3036 3037 /** 3038 * Outputs the CSS for layout rules on the root. 3039 * 3040 * @since 6.1.0 3041 * @since 6.6.0 Use `ROOT_CSS_PROPERTIES_SELECTOR` for CSS custom properties and improved consistency of root padding rules. 3042 * Updated specificity of body margin reset and first/last child selectors. 3043 * 3044 * @param string $selector The root node selector. 3045 * @param array $block_metadata The metadata for the root block. 3046 * @return string The additional root rules CSS. 3047 */ 3048 public function get_root_layout_rules( $selector, $block_metadata ) { 3049 $css = ''; 3050 $settings = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array(); 3051 $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments']; 3052 3053 /* 3054 * If there are content and wide widths in theme.json, output them 3055 * as custom properties on the body element so all blocks can use them. 3056 */ 3057 if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) { 3058 $content_size = isset( $settings['layout']['contentSize'] ) ? $settings['layout']['contentSize'] : $settings['layout']['wideSize']; 3059 $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial'; 3060 $wide_size = isset( $settings['layout']['wideSize'] ) ? $settings['layout']['wideSize'] : $settings['layout']['contentSize']; 3061 $wide_size = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial'; 3062 $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . ' { --wp--style--global--content-size: ' . $content_size . ';'; 3063 $css .= '--wp--style--global--wide-size: ' . $wide_size . '; }'; 3064 } 3065 3066 /* 3067 * Reset default browser margin on the body element. 3068 * This is set on the body selector **before** generating the ruleset 3069 * from the `theme.json`. This is to ensure that if the `theme.json` declares 3070 * `margin` in its `spacing` declaration for the `body` element then these 3071 * user-generated values take precedence in the CSS cascade. 3072 * @link https://github.com/WordPress/gutenberg/issues/36147. 3073 */ 3074 $css .= ':where(body) { margin: 0; }'; 3075 3076 if ( $use_root_padding ) { 3077 // Top and bottom padding are applied to the outer block container. 3078 $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }'; 3079 // Right and left padding are applied to the first container with `.has-global-padding` class. 3080 $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }'; 3081 // Alignfull children of the container with left and right padding have negative margins so they can still be full width. 3082 $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); }'; 3083 // 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. 3084 $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }'; 3085 // Alignfull direct children of the containers that are targeted by the rule above do not need negative margins. 3086 $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; }'; 3087 } 3088 3089 $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }'; 3090 $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }'; 3091 $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }'; 3092 3093 // Block gap styles will be output unless explicitly set to `null`. See static::PROTECTED_PROPERTIES. 3094 if ( isset( $this->theme_json['settings']['spacing']['blockGap'] ) ) { 3095 $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) ); 3096 $css .= ":where(.wp-site-blocks) > * { margin-block-start: $block_gap_value; margin-block-end: 0; }"; 3097 $css .= ':where(.wp-site-blocks) > :first-child { margin-block-start: 0; }'; 3098 $css .= ':where(.wp-site-blocks) > :last-child { margin-block-end: 0; }'; 3099 3100 // For backwards compatibility, ensure the legacy block gap CSS variable is still available. 3101 $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . " { --wp--style--block-gap: $block_gap_value; }"; 3102 } 3103 $css .= $this->get_layout_styles( $block_metadata ); 3104 3105 return $css; 3106 } 3107 3108 /** 3109 * For metadata values that can either be booleans or paths to booleans, gets the value. 3110 * 3111 * $data = array( 3112 * 'color' => array( 3113 * 'defaultPalette' => true 3114 * ) 3115 * ); 3116 * 3117 * static::get_metadata_boolean( $data, false ); 3118 * // => false 3119 * 3120 * static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) ); 3121 * // => true 3122 * 3123 * @since 6.0.0 3124 * 3125 * @param array $data The data to inspect. 3126 * @param bool|array $path Boolean or path to a boolean. 3127 * @param bool $default_value Default value if the referenced path is missing. 3128 * Default false. 3129 * @return bool Value of boolean metadata. 3130 */ 3131 protected static function get_metadata_boolean( $data, $path, $default_value = false ) { 3132 if ( is_bool( $path ) ) { 3133 return $path; 3134 } 3135 3136 if ( is_array( $path ) ) { 3137 $value = _wp_array_get( $data, $path ); 3138 if ( null !== $value ) { 3139 return $value; 3140 } 3141 } 3142 3143 return $default_value; 3144 } 3145 3146 /** 3147 * Merges new incoming data. 3148 * 3149 * @since 5.8.0 3150 * @since 5.9.0 Duotone preset also has origins. 3151 * @since 6.7.0 Replace background image objects during merge. 3152 * 3153 * @param WP_Theme_JSON $incoming Data to merge. 3154 */ 3155 public function merge( $incoming ) { 3156 $incoming_data = $incoming->get_raw_data(); 3157 $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data ); 3158 3159 /* 3160 * Recompute all the spacing sizes based on the new hierarchy of data. In the constructor 3161 * spacingScale and spacingSizes are both keyed by origin and VALID_ORIGINS is ordered, so 3162 * we can allow partial spacingScale data to inherit missing data from earlier layers when 3163 * computing the spacing sizes. 3164 * 3165 * This happens before the presets are merged to ensure that default spacing sizes can be 3166 * removed from the theme origin if $prevent_override is true. 3167 */ 3168 $flattened_spacing_scale = array(); 3169 foreach ( static::VALID_ORIGINS as $origin ) { 3170 $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin ); 3171 3172 // Apply the base spacing scale to the current layer. 3173 $base_spacing_scale = _wp_array_get( $this->theme_json, $scale_path, array() ); 3174 $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $base_spacing_scale ); 3175 3176 $spacing_scale = _wp_array_get( $incoming_data, $scale_path, null ); 3177 if ( ! isset( $spacing_scale ) ) { 3178 continue; 3179 } 3180 3181 // Allow partial scale settings by merging with lower layers. 3182 $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $spacing_scale ); 3183 3184 // Generate and merge the scales for this layer. 3185 $sizes_path = array( 'settings', 'spacing', 'spacingSizes', $origin ); 3186 $spacing_sizes = _wp_array_get( $incoming_data, $sizes_path, array() ); 3187 $spacing_scale_sizes = static::compute_spacing_sizes( $flattened_spacing_scale ); 3188 $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes ); 3189 3190 _wp_array_set( $incoming_data, $sizes_path, $merged_spacing_sizes ); 3191 } 3192 3193 /* 3194 * The array_replace_recursive algorithm merges at the leaf level, 3195 * but we don't want leaf arrays to be merged, so we overwrite it. 3196 * 3197 * For leaf values that are sequential arrays it will use the numeric indexes for replacement. 3198 * We rather replace the existing with the incoming value, if it exists. 3199 * This is the case of spacing.units. 3200 * 3201 * For leaf values that are associative arrays it will merge them as expected. 3202 * This is also not the behavior we want for the current associative arrays (presets). 3203 * We rather replace the existing with the incoming value, if it exists. 3204 * This happens, for example, when we merge data from theme.json upon existing 3205 * theme supports or when we merge anything coming from the same source twice. 3206 * This is the case of color.palette, color.gradients, color.duotone, 3207 * typography.fontSizes, or typography.fontFamilies. 3208 * 3209 * Additionally, for some preset types, we also want to make sure the 3210 * values they introduce don't conflict with default values. We do so 3211 * by checking the incoming slugs for theme presets and compare them 3212 * with the equivalent default presets: if a slug is present as a default 3213 * we remove it from the theme presets. 3214 */ 3215 $nodes = static::get_setting_nodes( $incoming_data ); 3216 $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) ); 3217 foreach ( $nodes as $node ) { 3218 // Replace the spacing.units. 3219 $path = $node['path']; 3220 $path[] = 'spacing'; 3221 $path[] = 'units'; 3222 3223 $content = _wp_array_get( $incoming_data, $path, null ); 3224 if ( isset( $content ) ) { 3225 _wp_array_set( $this->theme_json, $path, $content ); 3226 } 3227 3228 // Replace the presets. 3229 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 3230 $prevent_override = $preset_metadata['prevent_override']; 3231 if ( is_array( $prevent_override ) ) { 3232 $prevent_override = _wp_array_get( $this->theme_json['settings'], $preset_metadata['prevent_override'] ); 3233 } 3234 3235 foreach ( static::VALID_ORIGINS as $origin ) { 3236 $base_path = $node['path']; 3237 foreach ( $preset_metadata['path'] as $leaf ) { 3238 $base_path[] = $leaf; 3239 } 3240 3241 $path = $base_path; 3242 $path[] = $origin; 3243 3244 $content = _wp_array_get( $incoming_data, $path, null ); 3245 if ( ! isset( $content ) ) { 3246 continue; 3247 } 3248 3249 // Set names for theme presets based on the slug if they are not set and can use default names. 3250 if ( 'theme' === $origin && $preset_metadata['use_default_names'] ) { 3251 foreach ( $content as $key => $item ) { 3252 if ( ! isset( $item['name'] ) ) { 3253 $name = static::get_name_from_defaults( $item['slug'], $base_path ); 3254 if ( null !== $name ) { 3255 $content[ $key ]['name'] = $name; 3256 } 3257 } 3258 } 3259 } 3260 3261 // Filter out default slugs from theme presets when defaults should not be overridden. 3262 if ( 'theme' === $origin && $prevent_override ) { 3263 $slugs_node = static::get_default_slugs( $this->theme_json, $node['path'] ); 3264 $preset_global = _wp_array_get( $slugs_global, $preset_metadata['path'], array() ); 3265 $preset_node = _wp_array_get( $slugs_node, $preset_metadata['path'], array() ); 3266 $preset_slugs = array_merge_recursive( $preset_global, $preset_node ); 3267 3268 $content = static::filter_slugs( $content, $preset_slugs ); 3269 } 3270 3271 _wp_array_set( $this->theme_json, $path, $content ); 3272 } 3273 } 3274 } 3275 3276 /* 3277 * Style values are merged at the leaf level, however 3278 * some values provide exceptions, namely style values that are 3279 * objects and represent unique definitions for the style. 3280 */ 3281 $style_nodes = static::get_block_nodes( 3282 $this->theme_json, 3283 array(), 3284 array( 'include_node_paths_only' => true ) 3285 ); 3286 3287 // Add top-level styles. 3288 $style_nodes[] = array( 'path' => array( 'styles' ) ); 3289 3290 foreach ( $style_nodes as $style_node ) { 3291 $path = $style_node['path']; 3292 /* 3293 * Background image styles should be replaced, not merged, 3294 * as they themselves are specific object definitions for the style. 3295 */ 3296 $background_image_path = array_merge( $path, static::PROPERTIES_METADATA['background-image'] ); 3297 $content = _wp_array_get( $incoming_data, $background_image_path, null ); 3298 if ( isset( $content ) ) { 3299 _wp_array_set( $this->theme_json, $background_image_path, $content ); 3300 } 3301 } 3302 } 3303 3304 /** 3305 * Converts all filter (duotone) presets into SVGs. 3306 * 3307 * @since 5.9.1 3308 * 3309 * @param array $origins List of origins to process. 3310 * @return string SVG filters. 3311 */ 3312 public function get_svg_filters( $origins ) { 3313 $blocks_metadata = static::get_blocks_metadata(); 3314 $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata ); 3315 3316 $filters = ''; 3317 foreach ( $setting_nodes as $metadata ) { 3318 $node = _wp_array_get( $this->theme_json, $metadata['path'], array() ); 3319 if ( empty( $node['color']['duotone'] ) ) { 3320 continue; 3321 } 3322 3323 $duotone_presets = $node['color']['duotone']; 3324 3325 foreach ( $origins as $origin ) { 3326 if ( ! isset( $duotone_presets[ $origin ] ) ) { 3327 continue; 3328 } 3329 foreach ( $duotone_presets[ $origin ] as $duotone_preset ) { 3330 $filters .= WP_Duotone::get_filter_svg_from_preset( $duotone_preset ); 3331 } 3332 } 3333 } 3334 3335 return $filters; 3336 } 3337 3338 /** 3339 * Determines whether a presets should be overridden or not. 3340 * 3341 * @since 5.9.0 3342 * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead. 3343 * 3344 * @param array $theme_json The theme.json like structure to inspect. 3345 * @param array $path Path to inspect. 3346 * @param bool|array $override Data to compute whether to override the preset. 3347 * @return bool 3348 */ 3349 protected static function should_override_preset( $theme_json, $path, $override ) { 3350 _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' ); 3351 3352 if ( is_bool( $override ) ) { 3353 return $override; 3354 } 3355 3356 /* 3357 * The relationship between whether to override the defaults 3358 * and whether the defaults are enabled is inverse: 3359 * 3360 * - If defaults are enabled => theme presets should not be overridden 3361 * - If defaults are disabled => theme presets should be overridden 3362 * 3363 * For example, a theme sets defaultPalette to false, 3364 * making the default palette hidden from the user. 3365 * In that case, we want all the theme presets to be present, 3366 * so they should override the defaults. 3367 */ 3368 if ( is_array( $override ) ) { 3369 $value = _wp_array_get( $theme_json, array_merge( $path, $override ) ); 3370 if ( isset( $value ) ) { 3371 return ! $value; 3372 } 3373 3374 // Search the top-level key if none was found for this node. 3375 $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) ); 3376 if ( isset( $value ) ) { 3377 return ! $value; 3378 } 3379 3380 return true; 3381 } 3382 } 3383 3384 /** 3385 * Returns the default slugs for all the presets in an associative array 3386 * whose keys are the preset paths and the leaves is the list of slugs. 3387 * 3388 * For example: 3389 * 3390 * array( 3391 * 'color' => array( 3392 * 'palette' => array( 'slug-1', 'slug-2' ), 3393 * 'gradients' => array( 'slug-3', 'slug-4' ), 3394 * ), 3395 * ) 3396 * 3397 * @since 5.9.0 3398 * 3399 * @param array $data A theme.json like structure. 3400 * @param array $node_path The path to inspect. It's 'settings' by default. 3401 * @return array 3402 */ 3403 protected static function get_default_slugs( $data, $node_path ) { 3404 $slugs = array(); 3405 3406 foreach ( static::PRESETS_METADATA as $metadata ) { 3407 $path = $node_path; 3408 foreach ( $metadata['path'] as $leaf ) { 3409 $path[] = $leaf; 3410 } 3411 $path[] = 'default'; 3412 3413 $preset = _wp_array_get( $data, $path, null ); 3414 if ( ! isset( $preset ) ) { 3415 continue; 3416 } 3417 3418 $slugs_for_preset = array(); 3419 foreach ( $preset as $item ) { 3420 if ( isset( $item['slug'] ) ) { 3421 $slugs_for_preset[] = $item['slug']; 3422 } 3423 } 3424 3425 _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset ); 3426 } 3427 3428 return $slugs; 3429 } 3430 3431 /** 3432 * Gets a `default`'s preset name by a provided slug. 3433 * 3434 * @since 5.9.0 3435 * 3436 * @param string $slug The slug we want to find a match from default presets. 3437 * @param array $base_path The path to inspect. It's 'settings' by default. 3438 * @return string|null 3439 */ 3440 protected function get_name_from_defaults( $slug, $base_path ) { 3441 $path = $base_path; 3442 $path[] = 'default'; 3443 $default_content = _wp_array_get( $this->theme_json, $path, null ); 3444 if ( ! $default_content ) { 3445 return null; 3446 } 3447 foreach ( $default_content as $item ) { 3448 if ( $slug === $item['slug'] ) { 3449 return $item['name']; 3450 } 3451 } 3452 return null; 3453 } 3454 3455 /** 3456 * Removes the preset values whose slug is equal to any of given slugs. 3457 * 3458 * @since 5.9.0 3459 * 3460 * @param array $node The node with the presets to validate. 3461 * @param array $slugs The slugs that should not be overridden. 3462 * @return array The new node. 3463 */ 3464 protected static function filter_slugs( $node, $slugs ) { 3465 if ( empty( $slugs ) ) { 3466 return $node; 3467 } 3468 3469 $new_node = array(); 3470 foreach ( $node as $value ) { 3471 if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) { 3472 $new_node[] = $value; 3473 } 3474 } 3475 3476 return $new_node; 3477 } 3478 3479 /** 3480 * Removes insecure data from theme.json. 3481 * 3482 * @since 5.9.0 3483 * @since 6.3.2 Preserves global styles block variations when securing styles. 3484 * @since 6.6.0 Updated to allow variation element styles and $origin parameter. 3485 * 3486 * @param array $theme_json Structure to sanitize. 3487 * @param string $origin Optional. What source of data this object represents. 3488 * One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'. 3489 * @return array Sanitized structure. 3490 */ 3491 public static function remove_insecure_properties( $theme_json, $origin = 'theme' ) { 3492 if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) { 3493 $origin = 'theme'; 3494 } 3495 3496 $sanitized = array(); 3497 3498 $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin ); 3499 3500 $blocks_metadata = static::get_blocks_metadata(); 3501 $valid_block_names = array_keys( $blocks_metadata ); 3502 $valid_element_names = array_keys( static::ELEMENTS ); 3503 $valid_variations = static::get_valid_block_style_variations( $blocks_metadata ); 3504 3505 $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names, $valid_variations ); 3506 3507 $blocks_metadata = static::get_blocks_metadata(); 3508 $style_options = array( 'include_block_style_variations' => true ); // Allow variations data. 3509 $style_nodes = static::get_style_nodes( $theme_json, $blocks_metadata, $style_options ); 3510 3511 foreach ( $style_nodes as $metadata ) { 3512 $input = _wp_array_get( $theme_json, $metadata['path'], array() ); 3513 if ( empty( $input ) ) { 3514 continue; 3515 } 3516 3517 // The global styles custom CSS is not sanitized, but can only be edited by users with 'edit_css' capability. 3518 if ( isset( $input['css'] ) && current_user_can( 'edit_css' ) ) { 3519 $output = $input; 3520 } else { 3521 $output = static::remove_insecure_styles( $input ); 3522 } 3523 3524 /* 3525 * Get a reference to element name from path. 3526 * $metadata['path'] = array( 'styles', 'elements', 'link' ); 3527 */ 3528 $current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ]; 3529 3530 /* 3531 * $output is stripped of pseudo selectors. Re-add and process them 3532 * or insecure styles here. 3533 */ 3534 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) { 3535 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) { 3536 if ( isset( $input[ $pseudo_selector ] ) ) { 3537 $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] ); 3538 } 3539 } 3540 } 3541 3542 if ( ! empty( $output ) ) { 3543 _wp_array_set( $sanitized, $metadata['path'], $output ); 3544 } 3545 3546 if ( isset( $metadata['variations'] ) ) { 3547 foreach ( $metadata['variations'] as $variation ) { 3548 $variation_input = _wp_array_get( $theme_json, $variation['path'], array() ); 3549 if ( empty( $variation_input ) ) { 3550 continue; 3551 } 3552 3553 $variation_output = static::remove_insecure_styles( $variation_input ); 3554 3555 // Process a variation's elements and element pseudo selector styles. 3556 if ( isset( $variation_input['elements'] ) ) { 3557 foreach ( $valid_element_names as $element_name ) { 3558 $element_input = $variation_input['elements'][ $element_name ] ?? null; 3559 if ( $element_input ) { 3560 $element_output = static::remove_insecure_styles( $element_input ); 3561 3562 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) { 3563 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) { 3564 if ( isset( $element_input[ $pseudo_selector ] ) ) { 3565 $element_output[ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $pseudo_selector ] ); 3566 } 3567 } 3568 } 3569 3570 if ( ! empty( $element_output ) ) { 3571 _wp_array_set( $variation_output, array( 'elements', $element_name ), $element_output ); 3572 } 3573 } 3574 } 3575 } 3576 3577 if ( ! empty( $variation_output ) ) { 3578 _wp_array_set( $sanitized, $variation['path'], $variation_output ); 3579 } 3580 } 3581 } 3582 } 3583 3584 $setting_nodes = static::get_setting_nodes( $theme_json ); 3585 foreach ( $setting_nodes as $metadata ) { 3586 $input = _wp_array_get( $theme_json, $metadata['path'], array() ); 3587 if ( empty( $input ) ) { 3588 continue; 3589 } 3590 3591 $output = static::remove_insecure_settings( $input ); 3592 if ( ! empty( $output ) ) { 3593 _wp_array_set( $sanitized, $metadata['path'], $output ); 3594 } 3595 } 3596 3597 if ( empty( $sanitized['styles'] ) ) { 3598 unset( $theme_json['styles'] ); 3599 } else { 3600 $theme_json['styles'] = $sanitized['styles']; 3601 } 3602 3603 if ( empty( $sanitized['settings'] ) ) { 3604 unset( $theme_json['settings'] ); 3605 } else { 3606 $theme_json['settings'] = $sanitized['settings']; 3607 } 3608 3609 return $theme_json; 3610 } 3611 3612 /** 3613 * Processes a setting node and returns the same node 3614 * without the insecure settings. 3615 * 3616 * @since 5.9.0 3617 * 3618 * @param array $input Node to process. 3619 * @return array 3620 */ 3621 protected static function remove_insecure_settings( $input ) { 3622 $output = array(); 3623 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 3624 foreach ( static::VALID_ORIGINS as $origin ) { 3625 $path_with_origin = $preset_metadata['path']; 3626 $path_with_origin[] = $origin; 3627 $presets = _wp_array_get( $input, $path_with_origin, null ); 3628 if ( null === $presets ) { 3629 continue; 3630 } 3631 3632 $escaped_preset = array(); 3633 foreach ( $presets as $preset ) { 3634 if ( 3635 esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] && 3636 sanitize_html_class( $preset['slug'] ) === $preset['slug'] 3637 ) { 3638 $value = null; 3639 if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) { 3640 $value = $preset[ $preset_metadata['value_key'] ]; 3641 } elseif ( 3642 isset( $preset_metadata['value_func'] ) && 3643 is_callable( $preset_metadata['value_func'] ) 3644 ) { 3645 $value = call_user_func( $preset_metadata['value_func'], $preset ); 3646 } 3647 3648 $preset_is_valid = true; 3649 foreach ( $preset_metadata['properties'] as $property ) { 3650 if ( ! static::is_safe_css_declaration( $property, $value ) ) { 3651 $preset_is_valid = false; 3652 break; 3653 } 3654 } 3655 3656 if ( $preset_is_valid ) { 3657 $escaped_preset[] = $preset; 3658 } 3659 } 3660 } 3661 3662 if ( ! empty( $escaped_preset ) ) { 3663 _wp_array_set( $output, $path_with_origin, $escaped_preset ); 3664 } 3665 } 3666 } 3667 3668 // Ensure indirect properties not included in any `PRESETS_METADATA` value are allowed. 3669 static::remove_indirect_properties( $input, $output ); 3670 3671 return $output; 3672 } 3673 3674 /** 3675 * Processes a style node and returns the same node 3676 * without the insecure styles. 3677 * 3678 * @since 5.9.0 3679 * 3680 * @param array $input Node to process. 3681 * @return array 3682 */ 3683 protected static function remove_insecure_styles( $input ) { 3684 $output = array(); 3685 $declarations = static::compute_style_properties( $input ); 3686 3687 foreach ( $declarations as $declaration ) { 3688 if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) { 3689 $path = static::PROPERTIES_METADATA[ $declaration['name'] ]; 3690 3691 /* 3692 * Check the value isn't an array before adding so as to not 3693 * double up shorthand and longhand styles. 3694 */ 3695 $value = _wp_array_get( $input, $path, array() ); 3696 if ( ! is_array( $value ) ) { 3697 _wp_array_set( $output, $path, $value ); 3698 } 3699 } 3700 } 3701 3702 // Ensure indirect properties not handled by `compute_style_properties` are allowed. 3703 static::remove_indirect_properties( $input, $output ); 3704 3705 return $output; 3706 } 3707 3708 /** 3709 * Checks that a declaration provided by the user is safe. 3710 * 3711 * @since 5.9.0 3712 * 3713 * @param string $property_name Property name in a CSS declaration, i.e. the `color` in `color: red`. 3714 * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`. 3715 * @return bool 3716 */ 3717 protected static function is_safe_css_declaration( $property_name, $property_value ) { 3718 $style_to_validate = $property_name . ': ' . $property_value; 3719 $filtered = esc_html( safecss_filter_attr( $style_to_validate ) ); 3720 return ! empty( trim( $filtered ) ); 3721 } 3722 3723 /** 3724 * Removes indirect properties from the given input node and 3725 * sets in the given output node. 3726 * 3727 * @since 6.2.0 3728 * 3729 * @param array $input Node to process. 3730 * @param array $output The processed node. Passed by reference. 3731 */ 3732 private static function remove_indirect_properties( $input, &$output ) { 3733 foreach ( static::INDIRECT_PROPERTIES_METADATA as $property => $paths ) { 3734 foreach ( $paths as $path ) { 3735 $value = _wp_array_get( $input, $path ); 3736 if ( 3737 is_string( $value ) && 3738 static::is_safe_css_declaration( $property, $value ) 3739 ) { 3740 _wp_array_set( $output, $path, $value ); 3741 } 3742 } 3743 } 3744 } 3745 3746 /** 3747 * Returns the raw data. 3748 * 3749 * @since 5.8.0 3750 * 3751 * @return array Raw data. 3752 */ 3753 public function get_raw_data() { 3754 return $this->theme_json; 3755 } 3756 3757 /** 3758 * Transforms the given editor settings according the 3759 * add_theme_support format to the theme.json format. 3760 * 3761 * @since 5.8.0 3762 * 3763 * @param array $settings Existing editor settings. 3764 * @return array Config that adheres to the theme.json schema. 3765 */ 3766 public static function get_from_editor_settings( $settings ) { 3767 $theme_settings = array( 3768 'version' => static::LATEST_SCHEMA, 3769 'settings' => array(), 3770 ); 3771 3772 // Deprecated theme supports. 3773 if ( isset( $settings['disableCustomColors'] ) ) { 3774 $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors']; 3775 } 3776 3777 if ( isset( $settings['disableCustomGradients'] ) ) { 3778 $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients']; 3779 } 3780 3781 if ( isset( $settings['disableCustomFontSizes'] ) ) { 3782 $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes']; 3783 } 3784 3785 if ( isset( $settings['enableCustomLineHeight'] ) ) { 3786 $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight']; 3787 } 3788 3789 if ( isset( $settings['enableCustomUnits'] ) ) { 3790 $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ? 3791 array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) : 3792 $settings['enableCustomUnits']; 3793 } 3794 3795 if ( isset( $settings['colors'] ) ) { 3796 $theme_settings['settings']['color']['palette'] = $settings['colors']; 3797 } 3798 3799 if ( isset( $settings['gradients'] ) ) { 3800 $theme_settings['settings']['color']['gradients'] = $settings['gradients']; 3801 } 3802 3803 if ( isset( $settings['fontSizes'] ) ) { 3804 $font_sizes = $settings['fontSizes']; 3805 // Back-compatibility for presets without units. 3806 foreach ( $font_sizes as $key => $font_size ) { 3807 if ( is_numeric( $font_size['size'] ) ) { 3808 $font_sizes[ $key ]['size'] = $font_size['size'] . 'px'; 3809 } 3810 } 3811 $theme_settings['settings']['typography']['fontSizes'] = $font_sizes; 3812 } 3813 3814 if ( isset( $settings['enableCustomSpacing'] ) ) { 3815 $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing']; 3816 } 3817 3818 if ( isset( $settings['spacingSizes'] ) ) { 3819 $theme_settings['settings']['spacing']['spacingSizes'] = $settings['spacingSizes']; 3820 } 3821 3822 return $theme_settings; 3823 } 3824 3825 /** 3826 * Returns the current theme's wanted patterns(slugs) to be 3827 * registered from Pattern Directory. 3828 * 3829 * @since 6.0.0 3830 * 3831 * @return string[] 3832 */ 3833 public function get_patterns() { 3834 if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) { 3835 return $this->theme_json['patterns']; 3836 } 3837 return array(); 3838 } 3839 3840 /** 3841 * Returns a valid theme.json as provided by a theme. 3842 * 3843 * Unlike get_raw_data() this returns the presets flattened, as provided by a theme. 3844 * This also uses appearanceTools instead of their opt-ins if all of them are true. 3845 * 3846 * @since 6.0.0 3847 * 3848 * @return array 3849 */ 3850 public function get_data() { 3851 $output = $this->theme_json; 3852 $nodes = static::get_setting_nodes( $output ); 3853 3854 /** 3855 * Flatten the theme & custom origins into a single one. 3856 * 3857 * For example, the following: 3858 * 3859 * { 3860 * "settings": { 3861 * "color": { 3862 * "palette": { 3863 * "theme": [ {} ], 3864 * "custom": [ {} ] 3865 * } 3866 * } 3867 * } 3868 * } 3869 * 3870 * will be converted to: 3871 * 3872 * { 3873 * "settings": { 3874 * "color": { 3875 * "palette": [ {} ] 3876 * } 3877 * } 3878 * } 3879 */ 3880 foreach ( $nodes as $node ) { 3881 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 3882 $path = $node['path']; 3883 foreach ( $preset_metadata['path'] as $preset_metadata_path ) { 3884 $path[] = $preset_metadata_path; 3885 } 3886 $preset = _wp_array_get( $output, $path, null ); 3887 if ( null === $preset ) { 3888 continue; 3889 } 3890 3891 $items = array(); 3892 if ( isset( $preset['theme'] ) ) { 3893 foreach ( $preset['theme'] as $item ) { 3894 $slug = $item['slug']; 3895 unset( $item['slug'] ); 3896 $items[ $slug ] = $item; 3897 } 3898 } 3899 if ( isset( $preset['custom'] ) ) { 3900 foreach ( $preset['custom'] as $item ) { 3901 $slug = $item['slug']; 3902 unset( $item['slug'] ); 3903 $items[ $slug ] = $item; 3904 } 3905 } 3906 $flattened_preset = array(); 3907 foreach ( $items as $slug => $value ) { 3908 $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value ); 3909 } 3910 _wp_array_set( $output, $path, $flattened_preset ); 3911 } 3912 } 3913 3914 /* 3915 * If all of the static::APPEARANCE_TOOLS_OPT_INS are true, 3916 * this code unsets them and sets 'appearanceTools' instead. 3917 */ 3918 foreach ( $nodes as $node ) { 3919 $all_opt_ins_are_set = true; 3920 foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) { 3921 $full_path = $node['path']; 3922 foreach ( $opt_in_path as $opt_in_path_item ) { 3923 $full_path[] = $opt_in_path_item; 3924 } 3925 /* 3926 * Use "unset prop" as a marker instead of "null" because 3927 * "null" can be a valid value for some props (e.g. blockGap). 3928 */ 3929 $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' ); 3930 if ( 'unset prop' === $opt_in_value ) { 3931 $all_opt_ins_are_set = false; 3932 break; 3933 } 3934 } 3935 3936 if ( $all_opt_ins_are_set ) { 3937 $node_path_with_appearance_tools = $node['path']; 3938 $node_path_with_appearance_tools[] = 'appearanceTools'; 3939 _wp_array_set( $output, $node_path_with_appearance_tools, true ); 3940 foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) { 3941 $full_path = $node['path']; 3942 foreach ( $opt_in_path as $opt_in_path_item ) { 3943 $full_path[] = $opt_in_path_item; 3944 } 3945 /* 3946 * Use "unset prop" as a marker instead of "null" because 3947 * "null" can be a valid value for some props (e.g. blockGap). 3948 */ 3949 $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' ); 3950 if ( true !== $opt_in_value ) { 3951 continue; 3952 } 3953 3954 /* 3955 * The following could be improved to be path independent. 3956 * At the moment it relies on a couple of assumptions: 3957 * 3958 * - all opt-ins having a path of size 2. 3959 * - there's two sources of settings: the top-level and the block-level. 3960 */ 3961 if ( 3962 ( 1 === count( $node['path'] ) ) && 3963 ( 'settings' === $node['path'][0] ) 3964 ) { 3965 // Top-level settings. 3966 unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] ); 3967 if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) { 3968 unset( $output['settings'][ $opt_in_path[0] ] ); 3969 } 3970 } elseif ( 3971 ( 3 === count( $node['path'] ) ) && 3972 ( 'settings' === $node['path'][0] ) && 3973 ( 'blocks' === $node['path'][1] ) 3974 ) { 3975 // Block-level settings. 3976 $block_name = $node['path'][2]; 3977 unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] ); 3978 if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) { 3979 unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ); 3980 } 3981 } 3982 } 3983 } 3984 } 3985 3986 wp_recursive_ksort( $output ); 3987 3988 return $output; 3989 } 3990 3991 /** 3992 * Sets the spacingSizes array based on the spacingScale values from theme.json. 3993 * 3994 * @since 6.1.0 3995 * @deprecated 6.6.0 No longer used as the spacingSizes are automatically 3996 * generated in the constructor and merge methods instead 3997 * of manually after instantiation. 3998 * 3999 * @return null|void 4000 */ 4001 public function set_spacing_sizes() { 4002 _deprecated_function( __METHOD__, '6.6.0' ); 4003 4004 $spacing_scale = isset( $this->theme_json['settings']['spacing']['spacingScale'] ) 4005 ? $this->theme_json['settings']['spacing']['spacingScale'] 4006 : array(); 4007 4008 if ( ! isset( $spacing_scale['steps'] ) 4009 || ! is_numeric( $spacing_scale['steps'] ) 4010 || ! isset( $spacing_scale['mediumStep'] ) 4011 || ! isset( $spacing_scale['unit'] ) 4012 || ! isset( $spacing_scale['operator'] ) 4013 || ! isset( $spacing_scale['increment'] ) 4014 || ! isset( $spacing_scale['steps'] ) 4015 || ! is_numeric( $spacing_scale['increment'] ) 4016 || ! is_numeric( $spacing_scale['mediumStep'] ) 4017 || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) { 4018 if ( ! empty( $spacing_scale ) ) { 4019 wp_trigger_error( 4020 __METHOD__, 4021 sprintf( 4022 /* translators: 1: theme.json, 2: settings.spacing.spacingScale */ 4023 __( 'Some of the %1$s %2$s values are invalid' ), 4024 'theme.json', 4025 'settings.spacing.spacingScale' 4026 ), 4027 E_USER_NOTICE 4028 ); 4029 } 4030 return null; 4031 } 4032 4033 // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0. 4034 if ( 0 === $spacing_scale['steps'] ) { 4035 return null; 4036 } 4037 4038 $spacing_sizes = static::compute_spacing_sizes( $spacing_scale ); 4039 4040 // If there are 7 or fewer steps in the scale revert to numbers for labels instead of t-shirt sizes. 4041 if ( $spacing_scale['steps'] <= 7 ) { 4042 for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) { 4043 $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 ); 4044 } 4045 } 4046 4047 _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes ); 4048 } 4049 4050 /** 4051 * Merges two sets of spacing size presets. 4052 * 4053 * @since 6.6.0 4054 * 4055 * @param array $base The base set of spacing sizes. 4056 * @param array $incoming The set of spacing sizes to merge with the base. Duplicate slugs will override the base values. 4057 * @return array The merged set of spacing sizes. 4058 */ 4059 private static function merge_spacing_sizes( $base, $incoming ) { 4060 // Preserve the order if there are no base (spacingScale) values. 4061 if ( empty( $base ) ) { 4062 return $incoming; 4063 } 4064 $merged = array(); 4065 foreach ( $base as $item ) { 4066 $merged[ $item['slug'] ] = $item; 4067 } 4068 foreach ( $incoming as $item ) { 4069 $merged[ $item['slug'] ] = $item; 4070 } 4071 ksort( $merged, SORT_NUMERIC ); 4072 return array_values( $merged ); 4073 } 4074 4075 /** 4076 * Generates a set of spacing sizes by starting with a medium size and 4077 * applying an operator with an increment value to generate the rest of the 4078 * sizes outward from the medium size. The medium slug is '50' with the rest 4079 * of the slugs being 10 apart. The generated names use t-shirt sizing. 4080 * 4081 * Example: 4082 * 4083 * $spacing_scale = array( 4084 * 'steps' => 4, 4085 * 'mediumStep' => 16, 4086 * 'unit' => 'px', 4087 * 'operator' => '+', 4088 * 'increment' => 2, 4089 * ); 4090 * $spacing_sizes = static::compute_spacing_sizes( $spacing_scale ); 4091 * // -> array( 4092 * // array( 'name' => 'Small', 'slug' => '40', 'size' => '14px' ), 4093 * // array( 'name' => 'Medium', 'slug' => '50', 'size' => '16px' ), 4094 * // array( 'name' => 'Large', 'slug' => '60', 'size' => '18px' ), 4095 * // array( 'name' => 'X-Large', 'slug' => '70', 'size' => '20px' ), 4096 * // ) 4097 * 4098 * @since 6.6.0 4099 * 4100 * @param array $spacing_scale { 4101 * The spacing scale values. All are required. 4102 * 4103 * @type int $steps The number of steps in the scale. (up to 10 steps are supported.) 4104 * @type float $mediumStep The middle value that gets the slug '50'. (For even number of steps, this becomes the first middle value.) 4105 * @type string $unit The CSS unit to use for the sizes. 4106 * @type string $operator The mathematical operator to apply to generate the other sizes. Either '+' or '*'. 4107 * @type float $increment The value used with the operator to generate the other sizes. 4108 * } 4109 * @return array The spacing sizes presets or an empty array if some spacing scale values are missing or invalid. 4110 */ 4111 private static function compute_spacing_sizes( $spacing_scale ) { 4112 /* 4113 * This condition is intentionally missing some checks on ranges for the values in order to 4114 * keep backwards compatibility with the previous implementation. 4115 */ 4116 if ( 4117 ! isset( $spacing_scale['steps'] ) || 4118 ! is_numeric( $spacing_scale['steps'] ) || 4119 0 === $spacing_scale['steps'] || 4120 ! isset( $spacing_scale['mediumStep'] ) || 4121 ! is_numeric( $spacing_scale['mediumStep'] ) || 4122 ! isset( $spacing_scale['unit'] ) || 4123 ! isset( $spacing_scale['operator'] ) || 4124 ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) || 4125 ! isset( $spacing_scale['increment'] ) || 4126 ! is_numeric( $spacing_scale['increment'] ) 4127 ) { 4128 return array(); 4129 } 4130 4131 $unit = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] ); 4132 $current_step = $spacing_scale['mediumStep']; 4133 $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 ); 4134 $x_small_count = null; 4135 $below_sizes = array(); 4136 $slug = 40; 4137 $remainder = 0; 4138 4139 for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) { 4140 if ( '+' === $spacing_scale['operator'] ) { 4141 $current_step -= $spacing_scale['increment']; 4142 } elseif ( $spacing_scale['increment'] > 1 ) { 4143 $current_step /= $spacing_scale['increment']; 4144 } else { 4145 $current_step *= $spacing_scale['increment']; 4146 } 4147 4148 if ( $current_step <= 0 ) { 4149 $remainder = $below_midpoint_count; 4150 break; 4151 } 4152 4153 $below_sizes[] = array( 4154 /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */ 4155 'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ), 4156 'slug' => (string) $slug, 4157 'size' => round( $current_step, 2 ) . $unit, 4158 ); 4159 4160 if ( $below_midpoint_count === $steps_mid_point - 2 ) { 4161 $x_small_count = 2; 4162 } 4163 4164 if ( $below_midpoint_count < $steps_mid_point - 2 ) { 4165 ++$x_small_count; 4166 } 4167 4168 $slug -= 10; 4169 } 4170 4171 $below_sizes = array_reverse( $below_sizes ); 4172 4173 $below_sizes[] = array( 4174 'name' => __( 'Medium' ), 4175 'slug' => '50', 4176 'size' => $spacing_scale['mediumStep'] . $unit, 4177 ); 4178 4179 $current_step = $spacing_scale['mediumStep']; 4180 $x_large_count = null; 4181 $above_sizes = array(); 4182 $slug = 60; 4183 $steps_above = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder; 4184 4185 for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) { 4186 $current_step = '+' === $spacing_scale['operator'] 4187 ? $current_step + $spacing_scale['increment'] 4188 : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] ); 4189 4190 $above_sizes[] = array( 4191 /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */ 4192 'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ), 4193 'slug' => (string) $slug, 4194 'size' => round( $current_step, 2 ) . $unit, 4195 ); 4196 4197 if ( 1 === $above_midpoint_count ) { 4198 $x_large_count = 2; 4199 } 4200 4201 if ( $above_midpoint_count > 1 ) { 4202 ++$x_large_count; 4203 } 4204 4205 $slug += 10; 4206 } 4207 4208 $spacing_sizes = $below_sizes; 4209 foreach ( $above_sizes as $above_sizes_item ) { 4210 $spacing_sizes[] = $above_sizes_item; 4211 } 4212 4213 return $spacing_sizes; 4214 } 4215 4216 /** 4217 * This is used to convert the internal representation of variables to the CSS representation. 4218 * For example, `var:preset|color|vivid-green-cyan` becomes `var(--wp--preset--color--vivid-green-cyan)`. 4219 * 4220 * @since 6.3.0 4221 * 4222 * @param string $value The variable such as var:preset|color|vivid-green-cyan to convert. 4223 * @return string The converted variable. 4224 */ 4225 private static function convert_custom_properties( $value ) { 4226 $prefix = 'var:'; 4227 $prefix_len = strlen( $prefix ); 4228 $token_in = '|'; 4229 $token_out = '--'; 4230 if ( str_starts_with( $value, $prefix ) ) { 4231 $unwrapped_name = str_replace( 4232 $token_in, 4233 $token_out, 4234 substr( $value, $prefix_len ) 4235 ); 4236 $value = "var(--wp--$unwrapped_name)"; 4237 } 4238 4239 return $value; 4240 } 4241 4242 /** 4243 * Given a tree, converts the internal representation of variables to the CSS representation. 4244 * It is recursive and modifies the input in-place. 4245 * 4246 * @since 6.3.0 4247 * 4248 * @param array $tree Input to process. 4249 * @return array The modified $tree. 4250 */ 4251 private static function resolve_custom_css_format( $tree ) { 4252 $prefix = 'var:'; 4253 4254 foreach ( $tree as $key => $data ) { 4255 if ( is_string( $data ) && str_starts_with( $data, $prefix ) ) { 4256 $tree[ $key ] = self::convert_custom_properties( $data ); 4257 } elseif ( is_array( $data ) ) { 4258 $tree[ $key ] = self::resolve_custom_css_format( $data ); 4259 } 4260 } 4261 4262 return $tree; 4263 } 4264 4265 /** 4266 * Returns the selectors metadata for a block. 4267 * 4268 * @since 6.3.0 4269 * 4270 * @param object $block_type The block type. 4271 * @param string $root_selector The block's root selector. 4272 * @return array The custom selectors set by the block. 4273 */ 4274 protected static function get_block_selectors( $block_type, $root_selector ) { 4275 if ( ! empty( $block_type->selectors ) ) { 4276 return $block_type->selectors; 4277 } 4278 4279 $selectors = array( 'root' => $root_selector ); 4280 foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) { 4281 $feature_selector = wp_get_block_css_selector( $block_type, $key ); 4282 if ( null !== $feature_selector ) { 4283 $selectors[ $feature ] = array( 'root' => $feature_selector ); 4284 } 4285 } 4286 4287 return $selectors; 4288 } 4289 4290 /** 4291 * Generates all the element selectors for a block. 4292 * 4293 * @since 6.3.0 4294 * 4295 * @param string $root_selector The block's root CSS selector. 4296 * @return array The block's element selectors. 4297 */ 4298 protected static function get_block_element_selectors( $root_selector ) { 4299 /* 4300 * Assign defaults, then override those that the block sets by itself. 4301 * If the block selector is compounded, will append the element to each 4302 * individual block selector. 4303 */ 4304 $block_selectors = explode( ',', $root_selector ); 4305 $element_selectors = array(); 4306 foreach ( static::ELEMENTS as $el_name => $el_selector ) { 4307 $element_selector = array(); 4308 foreach ( $block_selectors as $selector ) { 4309 if ( $selector === $el_selector ) { 4310 $element_selector = array( $el_selector ); 4311 break; 4312 } 4313 $element_selector[] = static::prepend_to_selector( $el_selector, $selector . ' ' ); 4314 } 4315 $element_selectors[ $el_name ] = implode( ',', $element_selector ); 4316 } 4317 4318 return $element_selectors; 4319 } 4320 4321 /** 4322 * Generates style declarations for a node's features e.g., color, border, 4323 * typography etc. that have custom selectors in their related block's 4324 * metadata. 4325 * 4326 * @since 6.3.0 4327 * 4328 * @param object $metadata The related block metadata containing selectors. 4329 * @param object $node A merged theme.json node for block or variation. 4330 * @return array The style declarations for the node's features with custom 4331 * selectors. 4332 */ 4333 protected function get_feature_declarations_for_node( $metadata, &$node ) { 4334 $declarations = array(); 4335 4336 if ( ! isset( $metadata['selectors'] ) ) { 4337 return $declarations; 4338 } 4339 4340 $settings = isset( $this->theme_json['settings'] ) 4341 ? $this->theme_json['settings'] 4342 : array(); 4343 4344 foreach ( $metadata['selectors'] as $feature => $feature_selectors ) { 4345 /* 4346 * Skip if this is the block's root selector or the block doesn't 4347 * have any styles for the feature. 4348 */ 4349 if ( 'root' === $feature || empty( $node[ $feature ] ) ) { 4350 continue; 4351 } 4352 4353 if ( is_array( $feature_selectors ) ) { 4354 foreach ( $feature_selectors as $subfeature => $subfeature_selector ) { 4355 if ( 'root' === $subfeature || empty( $node[ $feature ][ $subfeature ] ) ) { 4356 continue; 4357 } 4358 4359 /* 4360 * Create temporary node containing only the subfeature data 4361 * to leverage existing `compute_style_properties` function. 4362 */ 4363 $subfeature_node = array( 4364 $feature => array( 4365 $subfeature => $node[ $feature ][ $subfeature ], 4366 ), 4367 ); 4368 4369 // Generate style declarations. 4370 $new_declarations = static::compute_style_properties( $subfeature_node, $settings, null, $this->theme_json ); 4371 4372 // Merge subfeature declarations into feature declarations. 4373 if ( isset( $declarations[ $subfeature_selector ] ) ) { 4374 foreach ( $new_declarations as $new_declaration ) { 4375 $declarations[ $subfeature_selector ][] = $new_declaration; 4376 } 4377 } else { 4378 $declarations[ $subfeature_selector ] = $new_declarations; 4379 } 4380 4381 /* 4382 * Remove the subfeature from the block's node now its 4383 * styles will be included under its own selector not the 4384 * block's. 4385 */ 4386 unset( $node[ $feature ][ $subfeature ] ); 4387 } 4388 } 4389 4390 /* 4391 * Now subfeatures have been processed and removed we can process 4392 * feature root selector or simple string selector. 4393 */ 4394 if ( 4395 is_string( $feature_selectors ) || 4396 ( isset( $feature_selectors['root'] ) && $feature_selectors['root'] ) 4397 ) { 4398 $feature_selector = is_string( $feature_selectors ) ? $feature_selectors : $feature_selectors['root']; 4399 4400 /* 4401 * Create temporary node containing only the feature data 4402 * to leverage existing `compute_style_properties` function. 4403 */ 4404 $feature_node = array( $feature => $node[ $feature ] ); 4405 4406 // Generate the style declarations. 4407 $new_declarations = static::compute_style_properties( $feature_node, $settings, null, $this->theme_json ); 4408 4409 /* 4410 * Merge new declarations with any that already exist for 4411 * the feature selector. This may occur when multiple block 4412 * support features use the same custom selector. 4413 */ 4414 if ( isset( $declarations[ $feature_selector ] ) ) { 4415 foreach ( $new_declarations as $new_declaration ) { 4416 $declarations[ $feature_selector ][] = $new_declaration; 4417 } 4418 } else { 4419 $declarations[ $feature_selector ] = $new_declarations; 4420 } 4421 4422 /* 4423 * Remove the feature from the block's node now its styles 4424 * will be included under its own selector not the block's. 4425 */ 4426 unset( $node[ $feature ] ); 4427 } 4428 } 4429 4430 return $declarations; 4431 } 4432 4433 /** 4434 * Replaces CSS variables with their values in place. 4435 * 4436 * @since 6.3.0 4437 * @since 6.5.0 Check for empty style before processing its value. 4438 * 4439 * @param array $styles CSS declarations to convert. 4440 * @param array $values key => value pairs to use for replacement. 4441 * @return array 4442 */ 4443 private static function convert_variables_to_value( $styles, $values ) { 4444 foreach ( $styles as $key => $style ) { 4445 if ( empty( $style ) ) { 4446 continue; 4447 } 4448 4449 if ( is_array( $style ) ) { 4450 $styles[ $key ] = self::convert_variables_to_value( $style, $values ); 4451 continue; 4452 } 4453 4454 if ( 0 <= strpos( $style, 'var(' ) ) { 4455 // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group. 4456 4457 $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts ); 4458 4459 if ( $has_matches ) { 4460 $resolved_style = $styles[ $key ]; 4461 foreach ( $var_parts[1] as $index => $var_part ) { 4462 $key_in_values = 'var(' . $var_part . ')'; 4463 $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan). 4464 $fallback = $var_parts[2][ $index ]; // the fallback value. 4465 $resolved_style = str_replace( 4466 array( 4467 $rule_to_replace, 4468 $fallback, 4469 ), 4470 array( 4471 isset( $values[ $key_in_values ] ) ? $values[ $key_in_values ] : $rule_to_replace, 4472 isset( $values[ $fallback ] ) ? $values[ $fallback ] : $fallback, 4473 ), 4474 $resolved_style 4475 ); 4476 } 4477 $styles[ $key ] = $resolved_style; 4478 } 4479 } 4480 } 4481 4482 return $styles; 4483 } 4484 4485 /** 4486 * Resolves the values of CSS variables in the given styles. 4487 * 4488 * @since 6.3.0 4489 * 4490 * @param WP_Theme_JSON $theme_json The theme json resolver. 4491 * @return WP_Theme_JSON The $theme_json with resolved variables. 4492 */ 4493 public static function resolve_variables( $theme_json ) { 4494 $settings = $theme_json->get_settings(); 4495 $styles = $theme_json->get_raw_data()['styles']; 4496 $preset_vars = static::compute_preset_vars( $settings, static::VALID_ORIGINS ); 4497 $theme_vars = static::compute_theme_vars( $settings ); 4498 $vars = array_reduce( 4499 array_merge( $preset_vars, $theme_vars ), 4500 function ( $carry, $item ) { 4501 $name = $item['name']; 4502 $carry[ "var({$name})" ] = $item['value']; 4503 return $carry; 4504 }, 4505 array() 4506 ); 4507 4508 $theme_json->theme_json['styles'] = self::convert_variables_to_value( $styles, $vars ); 4509 return $theme_json; 4510 } 4511 4512 /** 4513 * Generates a selector for a block style variation. 4514 * 4515 * @since 6.5.0 4516 * 4517 * @param string $variation_name Name of the block style variation. 4518 * @param string $block_selector CSS selector for the block. 4519 * @return string Block selector with block style variation selector added to it. 4520 */ 4521 protected static function get_block_style_variation_selector( $variation_name, $block_selector ) { 4522 $variation_class = ".is-style-$variation_name"; 4523 4524 if ( ! $block_selector ) { 4525 return $variation_class; 4526 } 4527 4528 $limit = 1; 4529 $selector_parts = explode( ',', $block_selector ); 4530 $result = array(); 4531 4532 foreach ( $selector_parts as $part ) { 4533 $result[] = preg_replace_callback( 4534 '/((?::\([^)]+\))?\s*)([^\s:]+)/', 4535 function ( $matches ) use ( $variation_class ) { 4536 return $matches[1] . $matches[2] . $variation_class; 4537 }, 4538 $part, 4539 $limit 4540 ); 4541 } 4542 4543 return implode( ',', $result ); 4544 } 4545 4546 /** 4547 * Collects valid block style variations keyed by block type. 4548 * 4549 * @since 6.6.0 4550 * @since 6.8.0 Added the `$blocks_metadata` parameter. 4551 * 4552 * @param array $blocks_metadata Optional. List of metadata per block. Default is the metadata for all blocks. 4553 * @return array Valid block style variations by block type. 4554 */ 4555 protected static function get_valid_block_style_variations( $blocks_metadata = array() ) { 4556 $valid_variations = array(); 4557 $blocks_metadata = empty( $blocks_metadata ) ? static::get_blocks_metadata() : $blocks_metadata; 4558 foreach ( $blocks_metadata as $block_name => $block_meta ) { 4559 if ( ! isset( $block_meta['styleVariations'] ) ) { 4560 continue; 4561 } 4562 $valid_variations[ $block_name ] = array_keys( $block_meta['styleVariations'] ); 4563 } 4564 4565 return $valid_variations; 4566 } 4567 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Sat Dec 21 08:20:01 2024 | Cross-referenced by PHPXref |