[ 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 * @param string[] $origins A list of origins to include. By default it includes VALID_ORIGINS. 1321 * @param array $options { 1322 * Optional. An array of options for now used for internal purposes only (may change without notice). 1323 * 1324 * @type string $scope Makes sure all style are scoped to a given selector 1325 * @type string $root_selector Overwrites and forces a given selector to be used on the root node 1326 * @type bool $skip_root_layout_styles Omits root layout styles from the generated stylesheet. Default false. 1327 * @type bool $include_block_style_variations Includes styles for block style variations in the generated stylesheet. Default false. 1328 * } 1329 * @return string The resulting stylesheet. 1330 */ 1331 public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null, $options = array() ) { 1332 if ( null === $origins ) { 1333 $origins = static::VALID_ORIGINS; 1334 } 1335 1336 if ( is_string( $types ) ) { 1337 // Dispatch error and map old arguments to new ones. 1338 _deprecated_argument( __FUNCTION__, '5.9.0' ); 1339 if ( 'block_styles' === $types ) { 1340 $types = array( 'styles', 'presets' ); 1341 } elseif ( 'css_variables' === $types ) { 1342 $types = array( 'variables' ); 1343 } else { 1344 $types = array( 'variables', 'styles', 'presets' ); 1345 } 1346 } 1347 1348 $blocks_metadata = static::get_blocks_metadata(); 1349 $style_nodes = static::get_style_nodes( $this->theme_json, $blocks_metadata, $options ); 1350 $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata ); 1351 1352 $root_style_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $style_nodes, 'selector' ), true ); 1353 $root_settings_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $setting_nodes, 'selector' ), true ); 1354 1355 if ( ! empty( $options['scope'] ) ) { 1356 foreach ( $setting_nodes as &$node ) { 1357 $node['selector'] = static::scope_selector( $options['scope'], $node['selector'] ); 1358 } 1359 foreach ( $style_nodes as &$node ) { 1360 $node = static::scope_style_node_selectors( $options['scope'], $node ); 1361 } 1362 unset( $node ); 1363 } 1364 1365 if ( ! empty( $options['root_selector'] ) ) { 1366 if ( false !== $root_settings_key ) { 1367 $setting_nodes[ $root_settings_key ]['selector'] = $options['root_selector']; 1368 } 1369 if ( false !== $root_style_key ) { 1370 $style_nodes[ $root_style_key ]['selector'] = $options['root_selector']; 1371 } 1372 } 1373 1374 $stylesheet = ''; 1375 1376 if ( in_array( 'variables', $types, true ) ) { 1377 $stylesheet .= $this->get_css_variables( $setting_nodes, $origins ); 1378 } 1379 1380 if ( in_array( 'styles', $types, true ) ) { 1381 if ( false !== $root_style_key && empty( $options['skip_root_layout_styles'] ) ) { 1382 $stylesheet .= $this->get_root_layout_rules( $style_nodes[ $root_style_key ]['selector'], $style_nodes[ $root_style_key ] ); 1383 } 1384 $stylesheet .= $this->get_block_classes( $style_nodes ); 1385 } elseif ( in_array( 'base-layout-styles', $types, true ) ) { 1386 $root_selector = static::ROOT_BLOCK_SELECTOR; 1387 $columns_selector = '.wp-block-columns'; 1388 $post_template_selector = '.wp-block-post-template'; 1389 if ( ! empty( $options['scope'] ) ) { 1390 $root_selector = static::scope_selector( $options['scope'], $root_selector ); 1391 $columns_selector = static::scope_selector( $options['scope'], $columns_selector ); 1392 $post_template_selector = static::scope_selector( $options['scope'], $post_template_selector ); 1393 } 1394 if ( ! empty( $options['root_selector'] ) ) { 1395 $root_selector = $options['root_selector']; 1396 } 1397 /* 1398 * Base layout styles are provided as part of `styles`, so only output separately if explicitly requested. 1399 * For backwards compatibility, the Columns block is explicitly included, to support a different default gap value. 1400 */ 1401 $base_styles_nodes = array( 1402 array( 1403 'path' => array( 'styles' ), 1404 'selector' => $root_selector, 1405 ), 1406 array( 1407 'path' => array( 'styles', 'blocks', 'core/columns' ), 1408 'selector' => $columns_selector, 1409 'name' => 'core/columns', 1410 ), 1411 array( 1412 'path' => array( 'styles', 'blocks', 'core/post-template' ), 1413 'selector' => $post_template_selector, 1414 'name' => 'core/post-template', 1415 ), 1416 ); 1417 1418 foreach ( $base_styles_nodes as $base_style_node ) { 1419 $stylesheet .= $this->get_layout_styles( $base_style_node, $types ); 1420 } 1421 } 1422 1423 if ( in_array( 'presets', $types, true ) ) { 1424 $stylesheet .= $this->get_preset_classes( $setting_nodes, $origins ); 1425 } 1426 1427 // Load the custom CSS last so it has the highest specificity. 1428 if ( in_array( 'custom-css', $types, true ) ) { 1429 // Add the global styles root CSS. 1430 $stylesheet .= _wp_array_get( $this->theme_json, array( 'styles', 'css' ) ); 1431 } 1432 1433 return $stylesheet; 1434 } 1435 1436 /** 1437 * Processes the CSS, to apply nesting. 1438 * 1439 * @since 6.2.0 1440 * @since 6.6.0 Enforced 0-1-0 specificity for block custom CSS selectors. 1441 * 1442 * @param string $css The CSS to process. 1443 * @param string $selector The selector to nest. 1444 * @return string The processed CSS. 1445 */ 1446 protected function process_blocks_custom_css( $css, $selector ) { 1447 $processed_css = ''; 1448 1449 if ( empty( $css ) ) { 1450 return $processed_css; 1451 } 1452 1453 // Split CSS nested rules. 1454 $parts = explode( '&', $css ); 1455 foreach ( $parts as $part ) { 1456 if ( empty( $part ) ) { 1457 continue; 1458 } 1459 $is_root_css = ( ! str_contains( $part, '{' ) ); 1460 if ( $is_root_css ) { 1461 // If the part doesn't contain braces, it applies to the root level. 1462 $processed_css .= ':root :where(' . trim( $selector ) . '){' . trim( $part ) . '}'; 1463 } else { 1464 // If the part contains braces, it's a nested CSS rule. 1465 $part = explode( '{', str_replace( '}', '', $part ) ); 1466 if ( count( $part ) !== 2 ) { 1467 continue; 1468 } 1469 $nested_selector = $part[0]; 1470 $css_value = $part[1]; 1471 1472 /* 1473 * Handle pseudo elements such as ::before, ::after etc. Regex will also 1474 * capture any leading combinator such as >, +, or ~, as well as spaces. 1475 * This allows pseudo elements as descendants e.g. `.parent ::before`. 1476 */ 1477 $matches = array(); 1478 $has_pseudo_element = preg_match( '/([>+~\s]*::[a-zA-Z-]+)/', $nested_selector, $matches ); 1479 $pseudo_part = $has_pseudo_element ? $matches[1] : ''; 1480 $nested_selector = $has_pseudo_element ? str_replace( $pseudo_part, '', $nested_selector ) : $nested_selector; 1481 1482 // Finalize selector and re-append pseudo element if required. 1483 $part_selector = str_starts_with( $nested_selector, ' ' ) 1484 ? static::scope_selector( $selector, $nested_selector ) 1485 : static::append_to_selector( $selector, $nested_selector ); 1486 $final_selector = ":root :where($part_selector)$pseudo_part"; 1487 1488 $processed_css .= $final_selector . '{' . trim( $css_value ) . '}'; 1489 } 1490 } 1491 return $processed_css; 1492 } 1493 1494 /** 1495 * Returns the global styles custom CSS. 1496 * 1497 * @since 6.2.0 1498 * @deprecated 6.7.0 Use {@see 'get_stylesheet'} instead. 1499 * 1500 * @return string The global styles custom CSS. 1501 */ 1502 public function get_custom_css() { 1503 _deprecated_function( __METHOD__, '6.7.0', 'get_stylesheet' ); 1504 // Add the global styles root CSS. 1505 $stylesheet = isset( $this->theme_json['styles']['css'] ) ? $this->theme_json['styles']['css'] : ''; 1506 1507 // Add the global styles block CSS. 1508 if ( isset( $this->theme_json['styles']['blocks'] ) ) { 1509 foreach ( $this->theme_json['styles']['blocks'] as $name => $node ) { 1510 $custom_block_css = isset( $this->theme_json['styles']['blocks'][ $name ]['css'] ) 1511 ? $this->theme_json['styles']['blocks'][ $name ]['css'] 1512 : null; 1513 if ( $custom_block_css ) { 1514 $selector = static::$blocks_metadata[ $name ]['selector']; 1515 $stylesheet .= $this->process_blocks_custom_css( $custom_block_css, $selector ); 1516 } 1517 } 1518 } 1519 1520 return $stylesheet; 1521 } 1522 1523 /** 1524 * Returns the page templates of the active theme. 1525 * 1526 * @since 5.9.0 1527 * 1528 * @return array 1529 */ 1530 public function get_custom_templates() { 1531 $custom_templates = array(); 1532 if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) { 1533 return $custom_templates; 1534 } 1535 1536 foreach ( $this->theme_json['customTemplates'] as $item ) { 1537 if ( isset( $item['name'] ) ) { 1538 $custom_templates[ $item['name'] ] = array( 1539 'title' => isset( $item['title'] ) ? $item['title'] : '', 1540 'postTypes' => isset( $item['postTypes'] ) ? $item['postTypes'] : array( 'page' ), 1541 ); 1542 } 1543 } 1544 return $custom_templates; 1545 } 1546 1547 /** 1548 * Returns the template part data of active theme. 1549 * 1550 * @since 5.9.0 1551 * 1552 * @return array 1553 */ 1554 public function get_template_parts() { 1555 $template_parts = array(); 1556 if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) { 1557 return $template_parts; 1558 } 1559 1560 foreach ( $this->theme_json['templateParts'] as $item ) { 1561 if ( isset( $item['name'] ) ) { 1562 $template_parts[ $item['name'] ] = array( 1563 'title' => isset( $item['title'] ) ? $item['title'] : '', 1564 'area' => isset( $item['area'] ) ? $item['area'] : '', 1565 ); 1566 } 1567 } 1568 return $template_parts; 1569 } 1570 1571 /** 1572 * Converts each style section into a list of rulesets 1573 * containing the block styles to be appended to the stylesheet. 1574 * 1575 * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax 1576 * 1577 * For each section this creates a new ruleset such as: 1578 * 1579 * block-selector { 1580 * style-property-one: value; 1581 * } 1582 * 1583 * @since 5.8.0 As `get_block_styles()`. 1584 * @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()` 1585 * and no longer returns preset classes. 1586 * Removed the `$setting_nodes` parameter. 1587 * @since 6.1.0 Moved most internal logic to `get_styles_for_block()`. 1588 * 1589 * @param array $style_nodes Nodes with styles. 1590 * @return string The new stylesheet. 1591 */ 1592 protected function get_block_classes( $style_nodes ) { 1593 $block_rules = ''; 1594 1595 foreach ( $style_nodes as $metadata ) { 1596 if ( null === $metadata['selector'] ) { 1597 continue; 1598 } 1599 $block_rules .= static::get_styles_for_block( $metadata ); 1600 } 1601 1602 return $block_rules; 1603 } 1604 1605 /** 1606 * Gets the CSS layout rules for a particular block from theme.json layout definitions. 1607 * 1608 * @since 6.1.0 1609 * @since 6.3.0 Reduced specificity for layout margin rules. 1610 * @since 6.5.1 Only output rules referencing content and wide sizes when values exist. 1611 * @since 6.5.3 Add types parameter to check if only base layout styles are needed. 1612 * @since 6.6.0 Updated layout style specificity to be compatible with overall 0-1-0 specificity in global styles. 1613 * 1614 * @param array $block_metadata Metadata about the block to get styles for. 1615 * @param array $types Optional. Types of styles to output. If empty, all styles will be output. 1616 * @return string Layout styles for the block. 1617 */ 1618 protected function get_layout_styles( $block_metadata, $types = array() ) { 1619 $block_rules = ''; 1620 $block_type = null; 1621 1622 // Skip outputting layout styles if explicitly disabled. 1623 if ( current_theme_supports( 'disable-layout-styles' ) ) { 1624 return $block_rules; 1625 } 1626 1627 if ( isset( $block_metadata['name'] ) ) { 1628 $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] ); 1629 if ( ! block_has_support( $block_type, 'layout', false ) && ! block_has_support( $block_type, '__experimentalLayout', false ) ) { 1630 return $block_rules; 1631 } 1632 } 1633 1634 $selector = isset( $block_metadata['selector'] ) ? $block_metadata['selector'] : ''; 1635 $has_block_gap_support = isset( $this->theme_json['settings']['spacing']['blockGap'] ); 1636 $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. 1637 $node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() ); 1638 $layout_definitions = wp_get_layout_definitions(); 1639 $layout_selector_pattern = '/^[a-zA-Z0-9\-\.\,\ *+>:\(\)]*$/'; // Allow alphanumeric classnames, spaces, wildcard, sibling, child combinator and pseudo class selectors. 1640 1641 /* 1642 * Gap styles will only be output if the theme has block gap support, or supports a fallback gap. 1643 * Default layout gap styles will be skipped for themes that do not explicitly opt-in to blockGap with a `true` or `false` value. 1644 */ 1645 if ( $has_block_gap_support || $has_fallback_gap_support ) { 1646 $block_gap_value = null; 1647 // Use a fallback gap value if block gap support is not available. 1648 if ( ! $has_block_gap_support ) { 1649 $block_gap_value = static::ROOT_BLOCK_SELECTOR === $selector ? '0.5em' : null; 1650 if ( ! empty( $block_type ) ) { 1651 $block_gap_value = isset( $block_type->supports['spacing']['blockGap']['__experimentalDefault'] ) 1652 ? $block_type->supports['spacing']['blockGap']['__experimentalDefault'] 1653 : null; 1654 } 1655 } else { 1656 $block_gap_value = static::get_property_value( $node, array( 'spacing', 'blockGap' ) ); 1657 } 1658 1659 // Support split row / column values and concatenate to a shorthand value. 1660 if ( is_array( $block_gap_value ) ) { 1661 if ( isset( $block_gap_value['top'] ) && isset( $block_gap_value['left'] ) ) { 1662 $gap_row = static::get_property_value( $node, array( 'spacing', 'blockGap', 'top' ) ); 1663 $gap_column = static::get_property_value( $node, array( 'spacing', 'blockGap', 'left' ) ); 1664 $block_gap_value = $gap_row === $gap_column ? $gap_row : $gap_row . ' ' . $gap_column; 1665 } else { 1666 // Skip outputting gap value if not all sides are provided. 1667 $block_gap_value = null; 1668 } 1669 } 1670 1671 // If the block should have custom gap, add the gap styles. 1672 if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) { 1673 foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) { 1674 // Allow outputting fallback gap styles for flex and grid layout types when block gap support isn't available. 1675 if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key && 'grid' !== $layout_definition_key ) { 1676 continue; 1677 } 1678 1679 $class_name = isset( $layout_definition['className'] ) ? $layout_definition['className'] : false; 1680 $spacing_rules = isset( $layout_definition['spacingStyles'] ) ? $layout_definition['spacingStyles'] : array(); 1681 1682 if ( 1683 ! empty( $class_name ) && 1684 ! empty( $spacing_rules ) 1685 ) { 1686 foreach ( $spacing_rules as $spacing_rule ) { 1687 $declarations = array(); 1688 if ( 1689 isset( $spacing_rule['selector'] ) && 1690 preg_match( $layout_selector_pattern, $spacing_rule['selector'] ) && 1691 ! empty( $spacing_rule['rules'] ) 1692 ) { 1693 // Iterate over each of the styling rules and substitute non-string values such as `null` with the real `blockGap` value. 1694 foreach ( $spacing_rule['rules'] as $css_property => $css_value ) { 1695 $current_css_value = is_string( $css_value ) ? $css_value : $block_gap_value; 1696 if ( static::is_safe_css_declaration( $css_property, $current_css_value ) ) { 1697 $declarations[] = array( 1698 'name' => $css_property, 1699 'value' => $current_css_value, 1700 ); 1701 } 1702 } 1703 1704 if ( ! $has_block_gap_support ) { 1705 // For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles. 1706 $format = static::ROOT_BLOCK_SELECTOR === $selector ? ':where(.%2$s%3$s)' : ':where(%1$s.%2$s%3$s)'; 1707 $layout_selector = sprintf( 1708 $format, 1709 $selector, 1710 $class_name, 1711 $spacing_rule['selector'] 1712 ); 1713 } else { 1714 $format = static::ROOT_BLOCK_SELECTOR === $selector ? ':root :where(.%2$s)%3$s' : ':root :where(%1$s-%2$s)%3$s'; 1715 $layout_selector = sprintf( 1716 $format, 1717 $selector, 1718 $class_name, 1719 $spacing_rule['selector'] 1720 ); 1721 } 1722 $block_rules .= static::to_ruleset( $layout_selector, $declarations ); 1723 } 1724 } 1725 } 1726 } 1727 } 1728 } 1729 1730 // Output base styles. 1731 if ( 1732 static::ROOT_BLOCK_SELECTOR === $selector 1733 ) { 1734 $valid_display_modes = array( 'block', 'flex', 'grid' ); 1735 foreach ( $layout_definitions as $layout_definition ) { 1736 $class_name = isset( $layout_definition['className'] ) ? $layout_definition['className'] : false; 1737 $base_style_rules = isset( $layout_definition['baseStyles'] ) ? $layout_definition['baseStyles'] : array(); 1738 1739 if ( 1740 ! empty( $class_name ) && 1741 is_array( $base_style_rules ) 1742 ) { 1743 // Output display mode. This requires special handling as `display` is not exposed in `safe_style_css_filter`. 1744 if ( 1745 ! empty( $layout_definition['displayMode'] ) && 1746 is_string( $layout_definition['displayMode'] ) && 1747 in_array( $layout_definition['displayMode'], $valid_display_modes, true ) 1748 ) { 1749 $layout_selector = sprintf( 1750 '%s .%s', 1751 $selector, 1752 $class_name 1753 ); 1754 $block_rules .= static::to_ruleset( 1755 $layout_selector, 1756 array( 1757 array( 1758 'name' => 'display', 1759 'value' => $layout_definition['displayMode'], 1760 ), 1761 ) 1762 ); 1763 } 1764 1765 foreach ( $base_style_rules as $base_style_rule ) { 1766 $declarations = array(); 1767 1768 // Skip outputting base styles for flow and constrained layout types if theme doesn't support theme.json. The 'base-layout-styles' type flags this. 1769 if ( in_array( 'base-layout-styles', $types, true ) && ( 'default' === $layout_definition['name'] || 'constrained' === $layout_definition['name'] ) ) { 1770 continue; 1771 } 1772 1773 if ( 1774 isset( $base_style_rule['selector'] ) && 1775 preg_match( $layout_selector_pattern, $base_style_rule['selector'] ) && 1776 ! empty( $base_style_rule['rules'] ) 1777 ) { 1778 foreach ( $base_style_rule['rules'] as $css_property => $css_value ) { 1779 // Skip rules that reference content size or wide size if they are not defined in the theme.json. 1780 if ( 1781 is_string( $css_value ) && 1782 ( str_contains( $css_value, '--global--content-size' ) || str_contains( $css_value, '--global--wide-size' ) ) && 1783 ! isset( $this->theme_json['settings']['layout']['contentSize'] ) && 1784 ! isset( $this->theme_json['settings']['layout']['wideSize'] ) 1785 ) { 1786 continue; 1787 } 1788 1789 if ( static::is_safe_css_declaration( $css_property, $css_value ) ) { 1790 $declarations[] = array( 1791 'name' => $css_property, 1792 'value' => $css_value, 1793 ); 1794 } 1795 } 1796 1797 $layout_selector = sprintf( 1798 '.%s%s', 1799 $class_name, 1800 $base_style_rule['selector'] 1801 ); 1802 $block_rules .= static::to_ruleset( $layout_selector, $declarations ); 1803 } 1804 } 1805 } 1806 } 1807 } 1808 return $block_rules; 1809 } 1810 1811 /** 1812 * Creates new rulesets as classes for each preset value such as: 1813 * 1814 * .has-value-color { 1815 * color: value; 1816 * } 1817 * 1818 * .has-value-background-color { 1819 * background-color: value; 1820 * } 1821 * 1822 * .has-value-font-size { 1823 * font-size: value; 1824 * } 1825 * 1826 * .has-value-gradient-background { 1827 * background: value; 1828 * } 1829 * 1830 * p.has-value-gradient-background { 1831 * background: value; 1832 * } 1833 * 1834 * @since 5.9.0 1835 * 1836 * @param array $setting_nodes Nodes with settings. 1837 * @param string[] $origins List of origins to process presets from. 1838 * @return string The new stylesheet. 1839 */ 1840 protected function get_preset_classes( $setting_nodes, $origins ) { 1841 $preset_rules = ''; 1842 1843 foreach ( $setting_nodes as $metadata ) { 1844 if ( null === $metadata['selector'] ) { 1845 continue; 1846 } 1847 1848 $selector = $metadata['selector']; 1849 $node = _wp_array_get( $this->theme_json, $metadata['path'], array() ); 1850 $preset_rules .= static::compute_preset_classes( $node, $selector, $origins ); 1851 } 1852 1853 return $preset_rules; 1854 } 1855 1856 /** 1857 * Converts each styles section into a list of rulesets 1858 * to be appended to the stylesheet. 1859 * These rulesets contain all the css variables (custom variables and preset variables). 1860 * 1861 * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax 1862 * 1863 * For each section this creates a new ruleset such as: 1864 * 1865 * block-selector { 1866 * --wp--preset--category--slug: value; 1867 * --wp--custom--variable: value; 1868 * } 1869 * 1870 * @since 5.8.0 1871 * @since 5.9.0 Added the `$origins` parameter. 1872 * 1873 * @param array $nodes Nodes with settings. 1874 * @param string[] $origins List of origins to process. 1875 * @return string The new stylesheet. 1876 */ 1877 protected function get_css_variables( $nodes, $origins ) { 1878 $stylesheet = ''; 1879 foreach ( $nodes as $metadata ) { 1880 if ( null === $metadata['selector'] ) { 1881 continue; 1882 } 1883 1884 $selector = $metadata['selector']; 1885 1886 $node = _wp_array_get( $this->theme_json, $metadata['path'], array() ); 1887 $declarations = static::compute_preset_vars( $node, $origins ); 1888 $theme_vars_declarations = static::compute_theme_vars( $node ); 1889 foreach ( $theme_vars_declarations as $theme_vars_declaration ) { 1890 $declarations[] = $theme_vars_declaration; 1891 } 1892 1893 $stylesheet .= static::to_ruleset( $selector, $declarations ); 1894 } 1895 1896 return $stylesheet; 1897 } 1898 1899 /** 1900 * Given a selector and a declaration list, 1901 * creates the corresponding ruleset. 1902 * 1903 * @since 5.8.0 1904 * 1905 * @param string $selector CSS selector. 1906 * @param array $declarations List of declarations. 1907 * @return string The resulting CSS ruleset. 1908 */ 1909 protected static function to_ruleset( $selector, $declarations ) { 1910 if ( empty( $declarations ) ) { 1911 return ''; 1912 } 1913 1914 $declaration_block = array_reduce( 1915 $declarations, 1916 static function ( $carry, $element ) { 1917 return $carry .= $element['name'] . ': ' . $element['value'] . ';'; }, 1918 '' 1919 ); 1920 1921 return $selector . '{' . $declaration_block . '}'; 1922 } 1923 1924 /** 1925 * Given a settings array, returns the generated rulesets 1926 * for the preset classes. 1927 * 1928 * @since 5.8.0 1929 * @since 5.9.0 Added the `$origins` parameter. 1930 * @since 6.6.0 Added check for root CSS properties selector. 1931 * 1932 * @param array $settings Settings to process. 1933 * @param string $selector Selector wrapping the classes. 1934 * @param string[] $origins List of origins to process. 1935 * @return string The result of processing the presets. 1936 */ 1937 protected static function compute_preset_classes( $settings, $selector, $origins ) { 1938 if ( static::ROOT_BLOCK_SELECTOR === $selector || static::ROOT_CSS_PROPERTIES_SELECTOR === $selector ) { 1939 /* 1940 * Classes at the global level do not need any CSS prefixed, 1941 * and we don't want to increase its specificity. 1942 */ 1943 $selector = ''; 1944 } 1945 1946 $stylesheet = ''; 1947 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 1948 if ( empty( $preset_metadata['classes'] ) ) { 1949 continue; 1950 } 1951 $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins ); 1952 foreach ( $preset_metadata['classes'] as $class => $property ) { 1953 foreach ( $slugs as $slug ) { 1954 $css_var = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ); 1955 $class_name = static::replace_slug_in_string( $class, $slug ); 1956 1957 // $selector is often empty, so we can save ourselves the `append_to_selector()` call then. 1958 $new_selector = '' === $selector ? $class_name : static::append_to_selector( $selector, $class_name ); 1959 $stylesheet .= static::to_ruleset( 1960 $new_selector, 1961 array( 1962 array( 1963 'name' => $property, 1964 'value' => 'var(' . $css_var . ') !important', 1965 ), 1966 ) 1967 ); 1968 } 1969 } 1970 } 1971 1972 return $stylesheet; 1973 } 1974 1975 /** 1976 * Function that scopes a selector with another one. This works a bit like 1977 * SCSS nesting except the `&` operator isn't supported. 1978 * 1979 * <code> 1980 * $scope = '.a, .b .c'; 1981 * $selector = '> .x, .y'; 1982 * $merged = scope_selector( $scope, $selector ); 1983 * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y' 1984 * </code> 1985 * 1986 * @since 5.9.0 1987 * @since 6.6.0 Added early return if missing scope or selector. 1988 * 1989 * @param string $scope Selector to scope to. 1990 * @param string $selector Original selector. 1991 * @return string Scoped selector. 1992 */ 1993 public static function scope_selector( $scope, $selector ) { 1994 if ( ! $scope || ! $selector ) { 1995 return $selector; 1996 } 1997 1998 $scopes = explode( ',', $scope ); 1999 $selectors = explode( ',', $selector ); 2000 2001 $selectors_scoped = array(); 2002 foreach ( $scopes as $outer ) { 2003 foreach ( $selectors as $inner ) { 2004 $outer = trim( $outer ); 2005 $inner = trim( $inner ); 2006 if ( ! empty( $outer ) && ! empty( $inner ) ) { 2007 $selectors_scoped[] = $outer . ' ' . $inner; 2008 } elseif ( empty( $outer ) ) { 2009 $selectors_scoped[] = $inner; 2010 } elseif ( empty( $inner ) ) { 2011 $selectors_scoped[] = $outer; 2012 } 2013 } 2014 } 2015 2016 $result = implode( ', ', $selectors_scoped ); 2017 return $result; 2018 } 2019 2020 /** 2021 * Scopes the selectors for a given style node. 2022 * 2023 * This includes the primary selector, i.e. `$node['selector']`, as well as any custom 2024 * selectors for features and subfeatures, e.g. `$node['selectors']['border']` etc. 2025 * 2026 * @since 6.6.0 2027 * 2028 * @param string $scope Selector to scope to. 2029 * @param array $node Style node with selectors to scope. 2030 * @return array Node with updated selectors. 2031 */ 2032 protected static function scope_style_node_selectors( $scope, $node ) { 2033 $node['selector'] = static::scope_selector( $scope, $node['selector'] ); 2034 2035 if ( empty( $node['selectors'] ) ) { 2036 return $node; 2037 } 2038 2039 foreach ( $node['selectors'] as $feature => $selector ) { 2040 if ( is_string( $selector ) ) { 2041 $node['selectors'][ $feature ] = static::scope_selector( $scope, $selector ); 2042 } 2043 if ( is_array( $selector ) ) { 2044 foreach ( $selector as $subfeature => $subfeature_selector ) { 2045 $node['selectors'][ $feature ][ $subfeature ] = static::scope_selector( $scope, $subfeature_selector ); 2046 } 2047 } 2048 } 2049 2050 return $node; 2051 } 2052 2053 /** 2054 * Gets preset values keyed by slugs based on settings and metadata. 2055 * 2056 * <code> 2057 * $settings = array( 2058 * 'typography' => array( 2059 * 'fontFamilies' => array( 2060 * array( 2061 * 'slug' => 'sansSerif', 2062 * 'fontFamily' => '"Helvetica Neue", sans-serif', 2063 * ), 2064 * array( 2065 * 'slug' => 'serif', 2066 * 'colors' => 'Georgia, serif', 2067 * ) 2068 * ), 2069 * ), 2070 * ); 2071 * $meta = array( 2072 * 'path' => array( 'typography', 'fontFamilies' ), 2073 * 'value_key' => 'fontFamily', 2074 * ); 2075 * $values_by_slug = get_settings_values_by_slug(); 2076 * // $values_by_slug === array( 2077 * // 'sans-serif' => '"Helvetica Neue", sans-serif', 2078 * // 'serif' => 'Georgia, serif', 2079 * // ); 2080 * </code> 2081 * 2082 * @since 5.9.0 2083 * @since 6.6.0 Passing $settings to the callbacks defined in static::PRESETS_METADATA. 2084 * 2085 * @param array $settings Settings to process. 2086 * @param array $preset_metadata One of the PRESETS_METADATA values. 2087 * @param string[] $origins List of origins to process. 2088 * @return array Array of presets where each key is a slug and each value is the preset value. 2089 */ 2090 protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) { 2091 $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() ); 2092 2093 $result = array(); 2094 foreach ( $origins as $origin ) { 2095 if ( ! isset( $preset_per_origin[ $origin ] ) ) { 2096 continue; 2097 } 2098 foreach ( $preset_per_origin[ $origin ] as $preset ) { 2099 $slug = _wp_to_kebab_case( $preset['slug'] ); 2100 2101 $value = ''; 2102 if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) { 2103 $value_key = $preset_metadata['value_key']; 2104 $value = $preset[ $value_key ]; 2105 } elseif ( 2106 isset( $preset_metadata['value_func'] ) && 2107 is_callable( $preset_metadata['value_func'] ) 2108 ) { 2109 $value_func = $preset_metadata['value_func']; 2110 $value = call_user_func( $value_func, $preset, $settings ); 2111 } else { 2112 // If we don't have a value, then don't add it to the result. 2113 continue; 2114 } 2115 2116 $result[ $slug ] = $value; 2117 } 2118 } 2119 return $result; 2120 } 2121 2122 /** 2123 * Similar to get_settings_values_by_slug, but doesn't compute the value. 2124 * 2125 * @since 5.9.0 2126 * 2127 * @param array $settings Settings to process. 2128 * @param array $preset_metadata One of the PRESETS_METADATA values. 2129 * @param string[] $origins List of origins to process. 2130 * @return array Array of presets where the key and value are both the slug. 2131 */ 2132 protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) { 2133 if ( null === $origins ) { 2134 $origins = static::VALID_ORIGINS; 2135 } 2136 2137 $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() ); 2138 2139 $result = array(); 2140 foreach ( $origins as $origin ) { 2141 if ( ! isset( $preset_per_origin[ $origin ] ) ) { 2142 continue; 2143 } 2144 foreach ( $preset_per_origin[ $origin ] as $preset ) { 2145 $slug = _wp_to_kebab_case( $preset['slug'] ); 2146 2147 // Use the array as a set so we don't get duplicates. 2148 $result[ $slug ] = $slug; 2149 } 2150 } 2151 return $result; 2152 } 2153 2154 /** 2155 * Transforms a slug into a CSS Custom Property. 2156 * 2157 * @since 5.9.0 2158 * 2159 * @param string $input String to replace. 2160 * @param string $slug The slug value to use to generate the custom property. 2161 * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`. 2162 */ 2163 protected static function replace_slug_in_string( $input, $slug ) { 2164 return strtr( $input, array( '$slug' => $slug ) ); 2165 } 2166 2167 /** 2168 * Given the block settings, extracts the CSS Custom Properties 2169 * for the presets and adds them to the $declarations array 2170 * following the format: 2171 * 2172 * array( 2173 * 'name' => 'property_name', 2174 * 'value' => 'property_value, 2175 * ) 2176 * 2177 * @since 5.8.0 2178 * @since 5.9.0 Added the `$origins` parameter. 2179 * 2180 * @param array $settings Settings to process. 2181 * @param string[] $origins List of origins to process. 2182 * @return array The modified $declarations. 2183 */ 2184 protected static function compute_preset_vars( $settings, $origins ) { 2185 $declarations = array(); 2186 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 2187 if ( empty( $preset_metadata['css_vars'] ) ) { 2188 continue; 2189 } 2190 $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins ); 2191 foreach ( $values_by_slug as $slug => $value ) { 2192 $declarations[] = array( 2193 'name' => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ), 2194 'value' => $value, 2195 ); 2196 } 2197 } 2198 2199 return $declarations; 2200 } 2201 2202 /** 2203 * Given an array of settings, extracts the CSS Custom Properties 2204 * for the custom values and adds them to the $declarations 2205 * array following the format: 2206 * 2207 * array( 2208 * 'name' => 'property_name', 2209 * 'value' => 'property_value, 2210 * ) 2211 * 2212 * @since 5.8.0 2213 * 2214 * @param array $settings Settings to process. 2215 * @return array The modified $declarations. 2216 */ 2217 protected static function compute_theme_vars( $settings ) { 2218 $declarations = array(); 2219 $custom_values = isset( $settings['custom'] ) ? $settings['custom'] : array(); 2220 $css_vars = static::flatten_tree( $custom_values ); 2221 foreach ( $css_vars as $key => $value ) { 2222 $declarations[] = array( 2223 'name' => '--wp--custom--' . $key, 2224 'value' => $value, 2225 ); 2226 } 2227 2228 return $declarations; 2229 } 2230 2231 /** 2232 * Given a tree, it creates a flattened one 2233 * by merging the keys and binding the leaf values 2234 * to the new keys. 2235 * 2236 * It also transforms camelCase names into kebab-case 2237 * and substitutes '/' by '-'. 2238 * 2239 * This is thought to be useful to generate 2240 * CSS Custom Properties from a tree, 2241 * although there's nothing in the implementation 2242 * of this function that requires that format. 2243 * 2244 * For example, assuming the given prefix is '--wp' 2245 * and the token is '--', for this input tree: 2246 * 2247 * { 2248 * 'some/property': 'value', 2249 * 'nestedProperty': { 2250 * 'sub-property': 'value' 2251 * } 2252 * } 2253 * 2254 * it'll return this output: 2255 * 2256 * { 2257 * '--wp--some-property': 'value', 2258 * '--wp--nested-property--sub-property': 'value' 2259 * } 2260 * 2261 * @since 5.8.0 2262 * 2263 * @param array $tree Input tree to process. 2264 * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string. 2265 * @param string $token Optional. Token to use between levels. Default '--'. 2266 * @return array The flattened tree. 2267 */ 2268 protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) { 2269 $result = array(); 2270 foreach ( $tree as $property => $value ) { 2271 $new_key = $prefix . str_replace( 2272 '/', 2273 '-', 2274 strtolower( _wp_to_kebab_case( $property ) ) 2275 ); 2276 2277 if ( is_array( $value ) ) { 2278 $new_prefix = $new_key . $token; 2279 $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token ); 2280 foreach ( $flattened_subtree as $subtree_key => $subtree_value ) { 2281 $result[ $subtree_key ] = $subtree_value; 2282 } 2283 } else { 2284 $result[ $new_key ] = $value; 2285 } 2286 } 2287 return $result; 2288 } 2289 2290 /** 2291 * Given a styles array, it extracts the style properties 2292 * and adds them to the $declarations array following the format: 2293 * 2294 * array( 2295 * 'name' => 'property_name', 2296 * 'value' => 'property_value', 2297 * ) 2298 * 2299 * @since 5.8.0 2300 * @since 5.9.0 Added the `$settings` and `$properties` parameters. 2301 * @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters. 2302 * @since 6.5.0 Output a `min-height: unset` rule when `aspect-ratio` is set. 2303 * @since 6.6.0 Pass current theme JSON settings to wp_get_typography_font_size_value(), and process background properties. 2304 * @since 6.7.0 `ref` resolution of background properties, and assigning custom default values. 2305 * 2306 * @param array $styles Styles to process. 2307 * @param array $settings Theme settings. 2308 * @param array $properties Properties metadata. 2309 * @param array $theme_json Theme JSON array. 2310 * @param string $selector The style block selector. 2311 * @param boolean $use_root_padding Whether to add custom properties at root level. 2312 * @return array Returns the modified $declarations. 2313 */ 2314 protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) { 2315 if ( empty( $styles ) ) { 2316 return array(); 2317 } 2318 2319 if ( null === $properties ) { 2320 $properties = static::PROPERTIES_METADATA; 2321 } 2322 $declarations = array(); 2323 $root_variable_duplicates = array(); 2324 $root_style_length = strlen( '--wp--style--root--' ); 2325 2326 foreach ( $properties as $css_property => $value_path ) { 2327 if ( ! is_array( $value_path ) ) { 2328 continue; 2329 } 2330 2331 $is_root_style = str_starts_with( $css_property, '--wp--style--root--' ); 2332 if ( $is_root_style && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) { 2333 continue; 2334 } 2335 2336 $value = static::get_property_value( $styles, $value_path, $theme_json ); 2337 2338 /* 2339 * Root-level padding styles don't currently support strings with CSS shorthand values. 2340 * This may change: https://github.com/WordPress/gutenberg/issues/40132. 2341 */ 2342 if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) { 2343 continue; 2344 } 2345 2346 if ( $is_root_style && $use_root_padding ) { 2347 $root_variable_duplicates[] = substr( $css_property, $root_style_length ); 2348 } 2349 2350 /* 2351 * Processes background image styles. 2352 * If the value is a URL, it will be converted to a CSS `url()` value. 2353 * For uploaded image (images with a database ID), apply size and position defaults, 2354 * equal to those applied in block supports in lib/background.php. 2355 */ 2356 if ( 'background-image' === $css_property && ! empty( $value ) ) { 2357 $background_styles = wp_style_engine_get_styles( 2358 array( 'background' => array( 'backgroundImage' => $value ) ) 2359 ); 2360 $value = $background_styles['declarations'][ $css_property ]; 2361 } 2362 if ( empty( $value ) && static::ROOT_BLOCK_SELECTOR !== $selector && ! empty( $styles['background']['backgroundImage']['id'] ) ) { 2363 if ( 'background-size' === $css_property ) { 2364 $value = 'cover'; 2365 } 2366 // If the background size is set to `contain` and no position is set, set the position to `center`. 2367 if ( 'background-position' === $css_property ) { 2368 $background_size = $styles['background']['backgroundSize'] ?? null; 2369 $value = 'contain' === $background_size ? '50% 50%' : null; 2370 } 2371 } 2372 2373 // Skip if empty and not "0" or value represents array of longhand values. 2374 $has_missing_value = empty( $value ) && ! is_numeric( $value ); 2375 if ( $has_missing_value || is_array( $value ) ) { 2376 continue; 2377 } 2378 2379 /* 2380 * Look up protected properties, keyed by value path. 2381 * Skip protected properties that are explicitly set to `null`. 2382 */ 2383 $path_string = implode( '.', $value_path ); 2384 if ( 2385 isset( static::PROTECTED_PROPERTIES[ $path_string ] ) && 2386 _wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null 2387 ) { 2388 continue; 2389 } 2390 2391 // Calculates fluid typography rules where available. 2392 if ( 'font-size' === $css_property ) { 2393 /* 2394 * wp_get_typography_font_size_value() will check 2395 * if fluid typography has been activated and also 2396 * whether the incoming value can be converted to a fluid value. 2397 * Values that already have a clamp() function will not pass the test, 2398 * and therefore the original $value will be returned. 2399 * Pass the current theme_json settings to override any global settings. 2400 */ 2401 $value = wp_get_typography_font_size_value( array( 'size' => $value ), $settings ); 2402 } 2403 2404 if ( 'aspect-ratio' === $css_property ) { 2405 // For aspect ratio to work, other dimensions rules must be unset. 2406 // This ensures that a fixed height does not override the aspect ratio. 2407 $declarations[] = array( 2408 'name' => 'min-height', 2409 'value' => 'unset', 2410 ); 2411 } 2412 2413 $declarations[] = array( 2414 'name' => $css_property, 2415 'value' => $value, 2416 ); 2417 } 2418 2419 // If a variable value is added to the root, the corresponding property should be removed. 2420 foreach ( $root_variable_duplicates as $duplicate ) { 2421 $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true ); 2422 if ( is_numeric( $discard ) ) { 2423 array_splice( $declarations, $discard, 1 ); 2424 } 2425 } 2426 2427 return $declarations; 2428 } 2429 2430 /** 2431 * Returns the style property for the given path. 2432 * 2433 * It also converts references to a path to the value 2434 * stored at that location, e.g. 2435 * { "ref": "style.color.background" } => "#fff". 2436 * 2437 * @since 5.8.0 2438 * @since 5.9.0 Added support for values of array type, which are returned as is. 2439 * @since 6.1.0 Added the `$theme_json` parameter. 2440 * @since 6.3.0 It no longer converts the internal format "var:preset|color|secondary" 2441 * to the standard form "--wp--preset--color--secondary". 2442 * This is already done by the sanitize method, 2443 * so every property will be in the standard form. 2444 * @since 6.7.0 Added support for background image refs. 2445 * 2446 * @param array $styles Styles subtree. 2447 * @param array $path Which property to process. 2448 * @param array $theme_json Theme JSON array. 2449 * @return string|array Style property value. 2450 */ 2451 protected static function get_property_value( $styles, $path, $theme_json = null ) { 2452 $value = _wp_array_get( $styles, $path, '' ); 2453 2454 if ( '' === $value || null === $value ) { 2455 // No need to process the value further. 2456 return ''; 2457 } 2458 2459 /* 2460 * This converts references to a path to the value at that path 2461 * where the value is an array with a "ref" key, pointing to a path. 2462 * For example: { "ref": "style.color.background" } => "#fff". 2463 * In the case of backgroundImage, if both a ref and a URL are present in the value, 2464 * the URL takes precedence and the ref is ignored. 2465 */ 2466 if ( is_array( $value ) && isset( $value['ref'] ) ) { 2467 $value_path = explode( '.', $value['ref'] ); 2468 $ref_value = _wp_array_get( $theme_json, $value_path ); 2469 // Background Image refs can refer to a string or an array containing a URL string. 2470 $ref_value_url = $ref_value['url'] ?? null; 2471 // Only use the ref value if we find anything. 2472 if ( ! empty( $ref_value ) && ( is_string( $ref_value ) || is_string( $ref_value_url ) ) ) { 2473 $value = $ref_value; 2474 } 2475 2476 if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) { 2477 $path_string = json_encode( $path ); 2478 $ref_value_string = json_encode( $ref_value ); 2479 _doing_it_wrong( 2480 'get_property_value', 2481 sprintf( 2482 /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */ 2483 __( '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.' ), 2484 'theme.json', 2485 $ref_value_string, 2486 $path_string, 2487 $ref_value['ref'] 2488 ), 2489 '6.1.0' 2490 ); 2491 } 2492 } 2493 2494 if ( is_array( $value ) ) { 2495 return $value; 2496 } 2497 2498 return $value; 2499 } 2500 2501 /** 2502 * Builds metadata for the setting nodes, which returns in the form of: 2503 * 2504 * [ 2505 * [ 2506 * 'path' => ['path', 'to', 'some', 'node' ], 2507 * 'selector' => 'CSS selector for some node' 2508 * ], 2509 * [ 2510 * 'path' => [ 'path', 'to', 'other', 'node' ], 2511 * 'selector' => 'CSS selector for other node' 2512 * ], 2513 * ] 2514 * 2515 * @since 5.8.0 2516 * 2517 * @param array $theme_json The tree to extract setting nodes from. 2518 * @param array $selectors List of selectors per block. 2519 * @return array An array of setting nodes metadata. 2520 */ 2521 protected static function get_setting_nodes( $theme_json, $selectors = array() ) { 2522 $nodes = array(); 2523 if ( ! isset( $theme_json['settings'] ) ) { 2524 return $nodes; 2525 } 2526 2527 // Top-level. 2528 $nodes[] = array( 2529 'path' => array( 'settings' ), 2530 'selector' => static::ROOT_CSS_PROPERTIES_SELECTOR, 2531 ); 2532 2533 // Calculate paths for blocks. 2534 if ( ! isset( $theme_json['settings']['blocks'] ) ) { 2535 return $nodes; 2536 } 2537 2538 foreach ( $theme_json['settings']['blocks'] as $name => $node ) { 2539 $selector = null; 2540 if ( isset( $selectors[ $name ]['selector'] ) ) { 2541 $selector = $selectors[ $name ]['selector']; 2542 } 2543 2544 $nodes[] = array( 2545 'path' => array( 'settings', 'blocks', $name ), 2546 'selector' => $selector, 2547 ); 2548 } 2549 2550 return $nodes; 2551 } 2552 2553 /** 2554 * Builds metadata for the style nodes, which returns in the form of: 2555 * 2556 * [ 2557 * [ 2558 * 'path' => [ 'path', 'to', 'some', 'node' ], 2559 * 'selector' => 'CSS selector for some node', 2560 * 'duotone' => 'CSS selector for duotone for some node' 2561 * ], 2562 * [ 2563 * 'path' => ['path', 'to', 'other', 'node' ], 2564 * 'selector' => 'CSS selector for other node', 2565 * 'duotone' => null 2566 * ], 2567 * ] 2568 * 2569 * @since 5.8.0 2570 * @since 6.6.0 Added options array for modifying generated nodes. 2571 * 2572 * @param array $theme_json The tree to extract style nodes from. 2573 * @param array $selectors List of selectors per block. 2574 * @param array $options { 2575 * Optional. An array of options for now used for internal purposes only (may change without notice). 2576 * 2577 * @type bool $include_block_style_variations Includes style nodes for block style variations. Default false. 2578 * } 2579 * @return array An array of style nodes metadata. 2580 */ 2581 protected static function get_style_nodes( $theme_json, $selectors = array(), $options = array() ) { 2582 $nodes = array(); 2583 if ( ! isset( $theme_json['styles'] ) ) { 2584 return $nodes; 2585 } 2586 2587 // Top-level. 2588 $nodes[] = array( 2589 'path' => array( 'styles' ), 2590 'selector' => static::ROOT_BLOCK_SELECTOR, 2591 ); 2592 2593 if ( isset( $theme_json['styles']['elements'] ) ) { 2594 foreach ( self::ELEMENTS as $element => $selector ) { 2595 if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) { 2596 continue; 2597 } 2598 $nodes[] = array( 2599 'path' => array( 'styles', 'elements', $element ), 2600 'selector' => static::ELEMENTS[ $element ], 2601 ); 2602 2603 // Handle any pseudo selectors for the element. 2604 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) { 2605 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) { 2606 2607 if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) { 2608 $nodes[] = array( 2609 'path' => array( 'styles', 'elements', $element ), 2610 'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ), 2611 ); 2612 } 2613 } 2614 } 2615 } 2616 } 2617 2618 // Blocks. 2619 if ( ! isset( $theme_json['styles']['blocks'] ) ) { 2620 return $nodes; 2621 } 2622 2623 $block_nodes = static::get_block_nodes( $theme_json, $selectors, $options ); 2624 foreach ( $block_nodes as $block_node ) { 2625 $nodes[] = $block_node; 2626 } 2627 2628 /** 2629 * Filters the list of style nodes with metadata. 2630 * 2631 * This allows for things like loading block CSS independently. 2632 * 2633 * @since 6.1.0 2634 * 2635 * @param array $nodes Style nodes with metadata. 2636 */ 2637 return apply_filters( 'wp_theme_json_get_style_nodes', $nodes ); 2638 } 2639 2640 /** 2641 * A public helper to get the block nodes from a theme.json file. 2642 * 2643 * @since 6.1.0 2644 * 2645 * @return array The block nodes in theme.json. 2646 */ 2647 public function get_styles_block_nodes() { 2648 return static::get_block_nodes( $this->theme_json ); 2649 } 2650 2651 /** 2652 * Returns a filtered declarations array if there is a separator block with only a background 2653 * style defined in theme.json by adding a color attribute to reflect the changes in the front. 2654 * 2655 * @since 6.1.1 2656 * 2657 * @param array $declarations List of declarations. 2658 * @return array $declarations List of declarations filtered. 2659 */ 2660 private static function update_separator_declarations( $declarations ) { 2661 $background_color = ''; 2662 $border_color_matches = false; 2663 $text_color_matches = false; 2664 2665 foreach ( $declarations as $declaration ) { 2666 if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) { 2667 $background_color = $declaration['value']; 2668 } elseif ( 'border-color' === $declaration['name'] ) { 2669 $border_color_matches = true; 2670 } elseif ( 'color' === $declaration['name'] ) { 2671 $text_color_matches = true; 2672 } 2673 2674 if ( $background_color && $border_color_matches && $text_color_matches ) { 2675 break; 2676 } 2677 } 2678 2679 if ( $background_color && ! $border_color_matches && ! $text_color_matches ) { 2680 $declarations[] = array( 2681 'name' => 'color', 2682 'value' => $background_color, 2683 ); 2684 } 2685 2686 return $declarations; 2687 } 2688 2689 /** 2690 * An internal method to get the block nodes from a theme.json file. 2691 * 2692 * @since 6.1.0 2693 * @since 6.3.0 Refactored and stabilized selectors API. 2694 * @since 6.6.0 Added optional selectors and options for generating block nodes. 2695 * @since 6.7.0 Added $include_node_paths_only option. 2696 * 2697 * @param array $theme_json The theme.json converted to an array. 2698 * @param array $selectors Optional list of selectors per block. 2699 * @param array $options { 2700 * Optional. An array of options for now used for internal purposes only (may change without notice). 2701 * 2702 * @type bool $include_block_style_variations Include nodes for block style variations. Default false. 2703 * @type bool $include_node_paths_only Return only block nodes node paths. Default false. 2704 * } 2705 * @return array The block nodes in theme.json. 2706 */ 2707 private static function get_block_nodes( $theme_json, $selectors = array(), $options = array() ) { 2708 $nodes = array(); 2709 2710 if ( ! isset( $theme_json['styles']['blocks'] ) ) { 2711 return $nodes; 2712 } 2713 2714 $include_variations = $options['include_block_style_variations'] ?? false; 2715 $include_node_paths_only = $options['include_node_paths_only'] ?? false; 2716 2717 // If only node paths are to be returned, skip selector assignment. 2718 if ( ! $include_node_paths_only ) { 2719 $selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors; 2720 } 2721 2722 foreach ( $theme_json['styles']['blocks'] as $name => $node ) { 2723 $node_path = array( 'styles', 'blocks', $name ); 2724 if ( $include_node_paths_only ) { 2725 $variation_paths = array(); 2726 if ( $include_variations && isset( $node['variations'] ) ) { 2727 foreach ( $node['variations'] as $variation => $variation_node ) { 2728 $variation_paths[] = array( 2729 'path' => array( 'styles', 'blocks', $name, 'variations', $variation ), 2730 ); 2731 } 2732 } 2733 $node = array( 2734 'path' => $node_path, 2735 ); 2736 if ( ! empty( $variation_paths ) ) { 2737 $node['variations'] = $variation_paths; 2738 } 2739 $nodes[] = $node; 2740 } else { 2741 $selector = null; 2742 if ( isset( $selectors[ $name ]['selector'] ) ) { 2743 $selector = $selectors[ $name ]['selector']; 2744 } 2745 2746 $duotone_selector = null; 2747 if ( isset( $selectors[ $name ]['duotone'] ) ) { 2748 $duotone_selector = $selectors[ $name ]['duotone']; 2749 } 2750 2751 $feature_selectors = null; 2752 if ( isset( $selectors[ $name ]['selectors'] ) ) { 2753 $feature_selectors = $selectors[ $name ]['selectors']; 2754 } 2755 2756 $variation_selectors = array(); 2757 if ( $include_variations && isset( $node['variations'] ) ) { 2758 foreach ( $node['variations'] as $variation => $node ) { 2759 $variation_selectors[] = array( 2760 'path' => array( 'styles', 'blocks', $name, 'variations', $variation ), 2761 'selector' => $selectors[ $name ]['styleVariations'][ $variation ], 2762 ); 2763 } 2764 } 2765 2766 $nodes[] = array( 2767 'name' => $name, 2768 'path' => $node_path, 2769 'selector' => $selector, 2770 'selectors' => $feature_selectors, 2771 'duotone' => $duotone_selector, 2772 'features' => $feature_selectors, 2773 'variations' => $variation_selectors, 2774 'css' => $selector, 2775 ); 2776 } 2777 2778 if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) { 2779 foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) { 2780 $node_path = array( 'styles', 'blocks', $name, 'elements', $element ); 2781 if ( $include_node_paths_only ) { 2782 $nodes[] = array( 2783 'path' => $node_path, 2784 ); 2785 continue; 2786 } 2787 2788 $nodes[] = array( 2789 'path' => $node_path, 2790 'selector' => $selectors[ $name ]['elements'][ $element ], 2791 ); 2792 2793 // Handle any pseudo selectors for the element. 2794 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) { 2795 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) { 2796 if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) { 2797 $node_path = array( 'styles', 'blocks', $name, 'elements', $element ); 2798 if ( $include_node_paths_only ) { 2799 $nodes[] = array( 2800 'path' => $node_path, 2801 ); 2802 continue; 2803 } 2804 2805 $nodes[] = array( 2806 'path' => $node_path, 2807 'selector' => static::append_to_selector( $selectors[ $name ]['elements'][ $element ], $pseudo_selector ), 2808 ); 2809 } 2810 } 2811 } 2812 } 2813 } 2814 } 2815 2816 return $nodes; 2817 } 2818 2819 /** 2820 * Gets the CSS rules for a particular block from theme.json. 2821 * 2822 * @since 6.1.0 2823 * @since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image. 2824 * Updated general global styles specificity to 0-1-0. 2825 * Fixed custom CSS output in block style variations. 2826 * 2827 * @param array $block_metadata Metadata about the block to get styles for. 2828 * @return string Styles for the block. 2829 */ 2830 public function get_styles_for_block( $block_metadata ) { 2831 $node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() ); 2832 $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments']; 2833 $selector = $block_metadata['selector']; 2834 $settings = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array(); 2835 $feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $node ); 2836 $is_root_selector = static::ROOT_BLOCK_SELECTOR === $selector; 2837 2838 // If there are style variations, generate the declarations for them, including any feature selectors the block may have. 2839 $style_variation_declarations = array(); 2840 $style_variation_custom_css = array(); 2841 if ( ! empty( $block_metadata['variations'] ) ) { 2842 foreach ( $block_metadata['variations'] as $style_variation ) { 2843 $style_variation_node = _wp_array_get( $this->theme_json, $style_variation['path'], array() ); 2844 $clean_style_variation_selector = trim( $style_variation['selector'] ); 2845 2846 // Generate any feature/subfeature style declarations for the current style variation. 2847 $variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node ); 2848 2849 // Combine selectors with style variation's selector and add to overall style variation declarations. 2850 foreach ( $variation_declarations as $current_selector => $new_declarations ) { 2851 // If current selector includes block classname, remove it but leave the whitespace in. 2852 $shortened_selector = str_replace( $block_metadata['selector'] . ' ', ' ', $current_selector ); 2853 2854 // Prepend the variation selector to the current selector. 2855 $split_selectors = explode( ',', $shortened_selector ); 2856 $updated_selectors = array_map( 2857 static function ( $split_selector ) use ( $clean_style_variation_selector ) { 2858 return $clean_style_variation_selector . $split_selector; 2859 }, 2860 $split_selectors 2861 ); 2862 $combined_selectors = implode( ',', $updated_selectors ); 2863 2864 // Add the new declarations to the overall results under the modified selector. 2865 $style_variation_declarations[ $combined_selectors ] = $new_declarations; 2866 } 2867 2868 // Compute declarations for remaining styles not covered by feature level selectors. 2869 $style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json ); 2870 // Store custom CSS for the style variation. 2871 if ( isset( $style_variation_node['css'] ) ) { 2872 $style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] ); 2873 } 2874 } 2875 } 2876 /* 2877 * Get a reference to element name from path. 2878 * $block_metadata['path'] = array( 'styles','elements','link' ); 2879 * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ]. 2880 * Skip non-element paths like just ['styles']. 2881 */ 2882 $is_processing_element = in_array( 'elements', $block_metadata['path'], true ); 2883 2884 $current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null; 2885 2886 $element_pseudo_allowed = array(); 2887 2888 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) { 2889 $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ]; 2890 } 2891 2892 /* 2893 * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover"). 2894 * This also resets the array keys. 2895 */ 2896 $pseudo_matches = array_values( 2897 array_filter( 2898 $element_pseudo_allowed, 2899 static function ( $pseudo_selector ) use ( $selector ) { 2900 return str_contains( $selector, $pseudo_selector ); 2901 } 2902 ) 2903 ); 2904 2905 $pseudo_selector = isset( $pseudo_matches[0] ) ? $pseudo_matches[0] : null; 2906 2907 /* 2908 * If the current selector is a pseudo selector that's defined in the allow list for the current 2909 * element then compute the style properties for it. 2910 * Otherwise just compute the styles for the default selector as normal. 2911 */ 2912 if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) && 2913 isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) 2914 && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true ) 2915 ) { 2916 $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding ); 2917 } else { 2918 $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding ); 2919 } 2920 2921 $block_rules = ''; 2922 2923 /* 2924 * 1. Bespoke declaration modifiers: 2925 * - 'filter': Separate the declarations that use the general selector 2926 * from the ones using the duotone selector. 2927 * - 'background|background-image': set the html min-height to 100% 2928 * to ensure the background covers the entire viewport. 2929 */ 2930 $declarations_duotone = array(); 2931 $should_set_root_min_height = false; 2932 2933 foreach ( $declarations as $index => $declaration ) { 2934 if ( 'filter' === $declaration['name'] ) { 2935 /* 2936 * 'unset' filters happen when a filter is unset 2937 * in the site-editor UI. Because the 'unset' value 2938 * in the user origin overrides the value in the 2939 * theme origin, we can skip rendering anything 2940 * here as no filter needs to be applied anymore. 2941 * So only add declarations to with values other 2942 * than 'unset'. 2943 */ 2944 if ( 'unset' !== $declaration['value'] ) { 2945 $declarations_duotone[] = $declaration; 2946 } 2947 unset( $declarations[ $index ] ); 2948 } 2949 2950 if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) { 2951 $should_set_root_min_height = true; 2952 } 2953 } 2954 2955 /* 2956 * If root styles has a background-image or a background (gradient) set, 2957 * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view. 2958 * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly, 2959 * and matches the behavior of the site editor. 2960 */ 2961 if ( $should_set_root_min_height ) { 2962 $block_rules .= static::to_ruleset( 2963 'html', 2964 array( 2965 array( 2966 'name' => 'min-height', 2967 'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))', 2968 ), 2969 ) 2970 ); 2971 } 2972 2973 // Update declarations if there are separators with only background color defined. 2974 if ( '.wp-block-separator' === $selector ) { 2975 $declarations = static::update_separator_declarations( $declarations ); 2976 } 2977 2978 /* 2979 * Root selector (body) styles should not be wrapped in `:root where()` to keep 2980 * specificity at (0,0,1) and maintain backwards compatibility. 2981 * 2982 * Top-level element styles using element-only specificity selectors should 2983 * not get wrapped in `:root :where()` to maintain backwards compatibility. 2984 * 2985 * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so 2986 * still need to be wrapped in `:root :where` to cap specificity for nested 2987 * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly. 2988 */ 2989 $element_only_selector = $is_root_selector || ( 2990 $current_element && 2991 isset( static::ELEMENTS[ $current_element ] ) && 2992 // buttons, captions etc. still need `:root :where()` as they are class based selectors. 2993 ! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) && 2994 static::ELEMENTS[ $current_element ] === $selector 2995 ); 2996 2997 // 2. Generate and append the rules that use the general selector. 2998 $general_selector = $element_only_selector ? $selector : ":root :where($selector)"; 2999 $block_rules .= static::to_ruleset( $general_selector, $declarations ); 3000 3001 // 3. Generate and append the rules that use the duotone selector. 3002 if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) { 3003 $block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone ); 3004 } 3005 3006 // 4. Generate Layout block gap styles. 3007 if ( 3008 ! $is_root_selector && 3009 ! empty( $block_metadata['name'] ) 3010 ) { 3011 $block_rules .= $this->get_layout_styles( $block_metadata ); 3012 } 3013 3014 // 5. Generate and append the feature level rulesets. 3015 foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) { 3016 $block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations ); 3017 } 3018 3019 // 6. Generate and append the style variation rulesets. 3020 foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) { 3021 $block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations ); 3022 if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) { 3023 $block_rules .= $style_variation_custom_css[ $style_variation_selector ]; 3024 } 3025 } 3026 3027 // 7. Generate and append any custom CSS rules. 3028 if ( isset( $node['css'] ) && ! $is_root_selector ) { 3029 $block_rules .= $this->process_blocks_custom_css( $node['css'], $selector ); 3030 } 3031 3032 return $block_rules; 3033 } 3034 3035 /** 3036 * Outputs the CSS for layout rules on the root. 3037 * 3038 * @since 6.1.0 3039 * @since 6.6.0 Use `ROOT_CSS_PROPERTIES_SELECTOR` for CSS custom properties and improved consistency of root padding rules. 3040 * Updated specificity of body margin reset and first/last child selectors. 3041 * 3042 * @param string $selector The root node selector. 3043 * @param array $block_metadata The metadata for the root block. 3044 * @return string The additional root rules CSS. 3045 */ 3046 public function get_root_layout_rules( $selector, $block_metadata ) { 3047 $css = ''; 3048 $settings = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array(); 3049 $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments']; 3050 3051 /* 3052 * If there are content and wide widths in theme.json, output them 3053 * as custom properties on the body element so all blocks can use them. 3054 */ 3055 if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) { 3056 $content_size = isset( $settings['layout']['contentSize'] ) ? $settings['layout']['contentSize'] : $settings['layout']['wideSize']; 3057 $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial'; 3058 $wide_size = isset( $settings['layout']['wideSize'] ) ? $settings['layout']['wideSize'] : $settings['layout']['contentSize']; 3059 $wide_size = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial'; 3060 $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . ' { --wp--style--global--content-size: ' . $content_size . ';'; 3061 $css .= '--wp--style--global--wide-size: ' . $wide_size . '; }'; 3062 } 3063 3064 /* 3065 * Reset default browser margin on the body element. 3066 * This is set on the body selector **before** generating the ruleset 3067 * from the `theme.json`. This is to ensure that if the `theme.json` declares 3068 * `margin` in its `spacing` declaration for the `body` element then these 3069 * user-generated values take precedence in the CSS cascade. 3070 * @link https://github.com/WordPress/gutenberg/issues/36147. 3071 */ 3072 $css .= ':where(body) { margin: 0; }'; 3073 3074 if ( $use_root_padding ) { 3075 // Top and bottom padding are applied to the outer block container. 3076 $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }'; 3077 // Right and left padding are applied to the first container with `.has-global-padding` class. 3078 $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }'; 3079 // Alignfull children of the container with left and right padding have negative margins so they can still be full width. 3080 $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); }'; 3081 // 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. 3082 $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }'; 3083 // Alignfull direct children of the containers that are targeted by the rule above do not need negative margins. 3084 $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; }'; 3085 } 3086 3087 $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }'; 3088 $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }'; 3089 $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }'; 3090 3091 // Block gap styles will be output unless explicitly set to `null`. See static::PROTECTED_PROPERTIES. 3092 if ( isset( $this->theme_json['settings']['spacing']['blockGap'] ) ) { 3093 $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) ); 3094 $css .= ":where(.wp-site-blocks) > * { margin-block-start: $block_gap_value; margin-block-end: 0; }"; 3095 $css .= ':where(.wp-site-blocks) > :first-child { margin-block-start: 0; }'; 3096 $css .= ':where(.wp-site-blocks) > :last-child { margin-block-end: 0; }'; 3097 3098 // For backwards compatibility, ensure the legacy block gap CSS variable is still available. 3099 $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . " { --wp--style--block-gap: $block_gap_value; }"; 3100 } 3101 $css .= $this->get_layout_styles( $block_metadata ); 3102 3103 return $css; 3104 } 3105 3106 /** 3107 * For metadata values that can either be booleans or paths to booleans, gets the value. 3108 * 3109 * $data = array( 3110 * 'color' => array( 3111 * 'defaultPalette' => true 3112 * ) 3113 * ); 3114 * 3115 * static::get_metadata_boolean( $data, false ); 3116 * // => false 3117 * 3118 * static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) ); 3119 * // => true 3120 * 3121 * @since 6.0.0 3122 * 3123 * @param array $data The data to inspect. 3124 * @param bool|array $path Boolean or path to a boolean. 3125 * @param bool $default_value Default value if the referenced path is missing. 3126 * Default false. 3127 * @return bool Value of boolean metadata. 3128 */ 3129 protected static function get_metadata_boolean( $data, $path, $default_value = false ) { 3130 if ( is_bool( $path ) ) { 3131 return $path; 3132 } 3133 3134 if ( is_array( $path ) ) { 3135 $value = _wp_array_get( $data, $path ); 3136 if ( null !== $value ) { 3137 return $value; 3138 } 3139 } 3140 3141 return $default_value; 3142 } 3143 3144 /** 3145 * Merges new incoming data. 3146 * 3147 * @since 5.8.0 3148 * @since 5.9.0 Duotone preset also has origins. 3149 * @since 6.7.0 Replace background image objects during merge. 3150 * 3151 * @param WP_Theme_JSON $incoming Data to merge. 3152 */ 3153 public function merge( $incoming ) { 3154 $incoming_data = $incoming->get_raw_data(); 3155 $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data ); 3156 3157 /* 3158 * Recompute all the spacing sizes based on the new hierarchy of data. In the constructor 3159 * spacingScale and spacingSizes are both keyed by origin and VALID_ORIGINS is ordered, so 3160 * we can allow partial spacingScale data to inherit missing data from earlier layers when 3161 * computing the spacing sizes. 3162 * 3163 * This happens before the presets are merged to ensure that default spacing sizes can be 3164 * removed from the theme origin if $prevent_override is true. 3165 */ 3166 $flattened_spacing_scale = array(); 3167 foreach ( static::VALID_ORIGINS as $origin ) { 3168 $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin ); 3169 3170 // Apply the base spacing scale to the current layer. 3171 $base_spacing_scale = _wp_array_get( $this->theme_json, $scale_path, array() ); 3172 $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $base_spacing_scale ); 3173 3174 $spacing_scale = _wp_array_get( $incoming_data, $scale_path, null ); 3175 if ( ! isset( $spacing_scale ) ) { 3176 continue; 3177 } 3178 3179 // Allow partial scale settings by merging with lower layers. 3180 $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $spacing_scale ); 3181 3182 // Generate and merge the scales for this layer. 3183 $sizes_path = array( 'settings', 'spacing', 'spacingSizes', $origin ); 3184 $spacing_sizes = _wp_array_get( $incoming_data, $sizes_path, array() ); 3185 $spacing_scale_sizes = static::compute_spacing_sizes( $flattened_spacing_scale ); 3186 $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes ); 3187 3188 _wp_array_set( $incoming_data, $sizes_path, $merged_spacing_sizes ); 3189 } 3190 3191 /* 3192 * The array_replace_recursive algorithm merges at the leaf level, 3193 * but we don't want leaf arrays to be merged, so we overwrite it. 3194 * 3195 * For leaf values that are sequential arrays it will use the numeric indexes for replacement. 3196 * We rather replace the existing with the incoming value, if it exists. 3197 * This is the case of spacing.units. 3198 * 3199 * For leaf values that are associative arrays it will merge them as expected. 3200 * This is also not the behavior we want for the current associative arrays (presets). 3201 * We rather replace the existing with the incoming value, if it exists. 3202 * This happens, for example, when we merge data from theme.json upon existing 3203 * theme supports or when we merge anything coming from the same source twice. 3204 * This is the case of color.palette, color.gradients, color.duotone, 3205 * typography.fontSizes, or typography.fontFamilies. 3206 * 3207 * Additionally, for some preset types, we also want to make sure the 3208 * values they introduce don't conflict with default values. We do so 3209 * by checking the incoming slugs for theme presets and compare them 3210 * with the equivalent default presets: if a slug is present as a default 3211 * we remove it from the theme presets. 3212 */ 3213 $nodes = static::get_setting_nodes( $incoming_data ); 3214 $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) ); 3215 foreach ( $nodes as $node ) { 3216 // Replace the spacing.units. 3217 $path = $node['path']; 3218 $path[] = 'spacing'; 3219 $path[] = 'units'; 3220 3221 $content = _wp_array_get( $incoming_data, $path, null ); 3222 if ( isset( $content ) ) { 3223 _wp_array_set( $this->theme_json, $path, $content ); 3224 } 3225 3226 // Replace the presets. 3227 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 3228 $prevent_override = $preset_metadata['prevent_override']; 3229 if ( is_array( $prevent_override ) ) { 3230 $prevent_override = _wp_array_get( $this->theme_json['settings'], $preset_metadata['prevent_override'] ); 3231 } 3232 3233 foreach ( static::VALID_ORIGINS as $origin ) { 3234 $base_path = $node['path']; 3235 foreach ( $preset_metadata['path'] as $leaf ) { 3236 $base_path[] = $leaf; 3237 } 3238 3239 $path = $base_path; 3240 $path[] = $origin; 3241 3242 $content = _wp_array_get( $incoming_data, $path, null ); 3243 if ( ! isset( $content ) ) { 3244 continue; 3245 } 3246 3247 // Set names for theme presets based on the slug if they are not set and can use default names. 3248 if ( 'theme' === $origin && $preset_metadata['use_default_names'] ) { 3249 foreach ( $content as $key => $item ) { 3250 if ( ! isset( $item['name'] ) ) { 3251 $name = static::get_name_from_defaults( $item['slug'], $base_path ); 3252 if ( null !== $name ) { 3253 $content[ $key ]['name'] = $name; 3254 } 3255 } 3256 } 3257 } 3258 3259 // Filter out default slugs from theme presets when defaults should not be overridden. 3260 if ( 'theme' === $origin && $prevent_override ) { 3261 $slugs_node = static::get_default_slugs( $this->theme_json, $node['path'] ); 3262 $preset_global = _wp_array_get( $slugs_global, $preset_metadata['path'], array() ); 3263 $preset_node = _wp_array_get( $slugs_node, $preset_metadata['path'], array() ); 3264 $preset_slugs = array_merge_recursive( $preset_global, $preset_node ); 3265 3266 $content = static::filter_slugs( $content, $preset_slugs ); 3267 } 3268 3269 _wp_array_set( $this->theme_json, $path, $content ); 3270 } 3271 } 3272 } 3273 3274 /* 3275 * Style values are merged at the leaf level, however 3276 * some values provide exceptions, namely style values that are 3277 * objects and represent unique definitions for the style. 3278 */ 3279 $style_nodes = static::get_block_nodes( 3280 $this->theme_json, 3281 array(), 3282 array( 'include_node_paths_only' => true ) 3283 ); 3284 3285 // Add top-level styles. 3286 $style_nodes[] = array( 'path' => array( 'styles' ) ); 3287 3288 foreach ( $style_nodes as $style_node ) { 3289 $path = $style_node['path']; 3290 /* 3291 * Background image styles should be replaced, not merged, 3292 * as they themselves are specific object definitions for the style. 3293 */ 3294 $background_image_path = array_merge( $path, static::PROPERTIES_METADATA['background-image'] ); 3295 $content = _wp_array_get( $incoming_data, $background_image_path, null ); 3296 if ( isset( $content ) ) { 3297 _wp_array_set( $this->theme_json, $background_image_path, $content ); 3298 } 3299 } 3300 } 3301 3302 /** 3303 * Converts all filter (duotone) presets into SVGs. 3304 * 3305 * @since 5.9.1 3306 * 3307 * @param array $origins List of origins to process. 3308 * @return string SVG filters. 3309 */ 3310 public function get_svg_filters( $origins ) { 3311 $blocks_metadata = static::get_blocks_metadata(); 3312 $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata ); 3313 3314 $filters = ''; 3315 foreach ( $setting_nodes as $metadata ) { 3316 $node = _wp_array_get( $this->theme_json, $metadata['path'], array() ); 3317 if ( empty( $node['color']['duotone'] ) ) { 3318 continue; 3319 } 3320 3321 $duotone_presets = $node['color']['duotone']; 3322 3323 foreach ( $origins as $origin ) { 3324 if ( ! isset( $duotone_presets[ $origin ] ) ) { 3325 continue; 3326 } 3327 foreach ( $duotone_presets[ $origin ] as $duotone_preset ) { 3328 $filters .= wp_get_duotone_filter_svg( $duotone_preset ); 3329 } 3330 } 3331 } 3332 3333 return $filters; 3334 } 3335 3336 /** 3337 * Determines whether a presets should be overridden or not. 3338 * 3339 * @since 5.9.0 3340 * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead. 3341 * 3342 * @param array $theme_json The theme.json like structure to inspect. 3343 * @param array $path Path to inspect. 3344 * @param bool|array $override Data to compute whether to override the preset. 3345 * @return bool 3346 */ 3347 protected static function should_override_preset( $theme_json, $path, $override ) { 3348 _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' ); 3349 3350 if ( is_bool( $override ) ) { 3351 return $override; 3352 } 3353 3354 /* 3355 * The relationship between whether to override the defaults 3356 * and whether the defaults are enabled is inverse: 3357 * 3358 * - If defaults are enabled => theme presets should not be overridden 3359 * - If defaults are disabled => theme presets should be overridden 3360 * 3361 * For example, a theme sets defaultPalette to false, 3362 * making the default palette hidden from the user. 3363 * In that case, we want all the theme presets to be present, 3364 * so they should override the defaults. 3365 */ 3366 if ( is_array( $override ) ) { 3367 $value = _wp_array_get( $theme_json, array_merge( $path, $override ) ); 3368 if ( isset( $value ) ) { 3369 return ! $value; 3370 } 3371 3372 // Search the top-level key if none was found for this node. 3373 $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) ); 3374 if ( isset( $value ) ) { 3375 return ! $value; 3376 } 3377 3378 return true; 3379 } 3380 } 3381 3382 /** 3383 * Returns the default slugs for all the presets in an associative array 3384 * whose keys are the preset paths and the leaves is the list of slugs. 3385 * 3386 * For example: 3387 * 3388 * array( 3389 * 'color' => array( 3390 * 'palette' => array( 'slug-1', 'slug-2' ), 3391 * 'gradients' => array( 'slug-3', 'slug-4' ), 3392 * ), 3393 * ) 3394 * 3395 * @since 5.9.0 3396 * 3397 * @param array $data A theme.json like structure. 3398 * @param array $node_path The path to inspect. It's 'settings' by default. 3399 * @return array 3400 */ 3401 protected static function get_default_slugs( $data, $node_path ) { 3402 $slugs = array(); 3403 3404 foreach ( static::PRESETS_METADATA as $metadata ) { 3405 $path = $node_path; 3406 foreach ( $metadata['path'] as $leaf ) { 3407 $path[] = $leaf; 3408 } 3409 $path[] = 'default'; 3410 3411 $preset = _wp_array_get( $data, $path, null ); 3412 if ( ! isset( $preset ) ) { 3413 continue; 3414 } 3415 3416 $slugs_for_preset = array(); 3417 foreach ( $preset as $item ) { 3418 if ( isset( $item['slug'] ) ) { 3419 $slugs_for_preset[] = $item['slug']; 3420 } 3421 } 3422 3423 _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset ); 3424 } 3425 3426 return $slugs; 3427 } 3428 3429 /** 3430 * Gets a `default`'s preset name by a provided slug. 3431 * 3432 * @since 5.9.0 3433 * 3434 * @param string $slug The slug we want to find a match from default presets. 3435 * @param array $base_path The path to inspect. It's 'settings' by default. 3436 * @return string|null 3437 */ 3438 protected function get_name_from_defaults( $slug, $base_path ) { 3439 $path = $base_path; 3440 $path[] = 'default'; 3441 $default_content = _wp_array_get( $this->theme_json, $path, null ); 3442 if ( ! $default_content ) { 3443 return null; 3444 } 3445 foreach ( $default_content as $item ) { 3446 if ( $slug === $item['slug'] ) { 3447 return $item['name']; 3448 } 3449 } 3450 return null; 3451 } 3452 3453 /** 3454 * Removes the preset values whose slug is equal to any of given slugs. 3455 * 3456 * @since 5.9.0 3457 * 3458 * @param array $node The node with the presets to validate. 3459 * @param array $slugs The slugs that should not be overridden. 3460 * @return array The new node. 3461 */ 3462 protected static function filter_slugs( $node, $slugs ) { 3463 if ( empty( $slugs ) ) { 3464 return $node; 3465 } 3466 3467 $new_node = array(); 3468 foreach ( $node as $value ) { 3469 if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) { 3470 $new_node[] = $value; 3471 } 3472 } 3473 3474 return $new_node; 3475 } 3476 3477 /** 3478 * Removes insecure data from theme.json. 3479 * 3480 * @since 5.9.0 3481 * @since 6.3.2 Preserves global styles block variations when securing styles. 3482 * @since 6.6.0 Updated to allow variation element styles and $origin parameter. 3483 * 3484 * @param array $theme_json Structure to sanitize. 3485 * @param string $origin Optional. What source of data this object represents. 3486 * One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'. 3487 * @return array Sanitized structure. 3488 */ 3489 public static function remove_insecure_properties( $theme_json, $origin = 'theme' ) { 3490 if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) { 3491 $origin = 'theme'; 3492 } 3493 3494 $sanitized = array(); 3495 3496 $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin ); 3497 3498 $blocks_metadata = static::get_blocks_metadata(); 3499 $valid_block_names = array_keys( $blocks_metadata ); 3500 $valid_element_names = array_keys( static::ELEMENTS ); 3501 $valid_variations = static::get_valid_block_style_variations( $blocks_metadata ); 3502 3503 $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names, $valid_variations ); 3504 3505 $blocks_metadata = static::get_blocks_metadata(); 3506 $style_options = array( 'include_block_style_variations' => true ); // Allow variations data. 3507 $style_nodes = static::get_style_nodes( $theme_json, $blocks_metadata, $style_options ); 3508 3509 foreach ( $style_nodes as $metadata ) { 3510 $input = _wp_array_get( $theme_json, $metadata['path'], array() ); 3511 if ( empty( $input ) ) { 3512 continue; 3513 } 3514 3515 // The global styles custom CSS is not sanitized, but can only be edited by users with 'edit_css' capability. 3516 if ( isset( $input['css'] ) && current_user_can( 'edit_css' ) ) { 3517 $output = $input; 3518 } else { 3519 $output = static::remove_insecure_styles( $input ); 3520 } 3521 3522 /* 3523 * Get a reference to element name from path. 3524 * $metadata['path'] = array( 'styles', 'elements', 'link' ); 3525 */ 3526 $current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ]; 3527 3528 /* 3529 * $output is stripped of pseudo selectors. Re-add and process them 3530 * or insecure styles here. 3531 */ 3532 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) { 3533 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) { 3534 if ( isset( $input[ $pseudo_selector ] ) ) { 3535 $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] ); 3536 } 3537 } 3538 } 3539 3540 if ( ! empty( $output ) ) { 3541 _wp_array_set( $sanitized, $metadata['path'], $output ); 3542 } 3543 3544 if ( isset( $metadata['variations'] ) ) { 3545 foreach ( $metadata['variations'] as $variation ) { 3546 $variation_input = _wp_array_get( $theme_json, $variation['path'], array() ); 3547 if ( empty( $variation_input ) ) { 3548 continue; 3549 } 3550 3551 $variation_output = static::remove_insecure_styles( $variation_input ); 3552 3553 // Process a variation's elements and element pseudo selector styles. 3554 if ( isset( $variation_input['elements'] ) ) { 3555 foreach ( $valid_element_names as $element_name ) { 3556 $element_input = $variation_input['elements'][ $element_name ] ?? null; 3557 if ( $element_input ) { 3558 $element_output = static::remove_insecure_styles( $element_input ); 3559 3560 if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) { 3561 foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) { 3562 if ( isset( $element_input[ $pseudo_selector ] ) ) { 3563 $element_output[ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $pseudo_selector ] ); 3564 } 3565 } 3566 } 3567 3568 if ( ! empty( $element_output ) ) { 3569 _wp_array_set( $variation_output, array( 'elements', $element_name ), $element_output ); 3570 } 3571 } 3572 } 3573 } 3574 3575 if ( ! empty( $variation_output ) ) { 3576 _wp_array_set( $sanitized, $variation['path'], $variation_output ); 3577 } 3578 } 3579 } 3580 } 3581 3582 $setting_nodes = static::get_setting_nodes( $theme_json ); 3583 foreach ( $setting_nodes as $metadata ) { 3584 $input = _wp_array_get( $theme_json, $metadata['path'], array() ); 3585 if ( empty( $input ) ) { 3586 continue; 3587 } 3588 3589 $output = static::remove_insecure_settings( $input ); 3590 if ( ! empty( $output ) ) { 3591 _wp_array_set( $sanitized, $metadata['path'], $output ); 3592 } 3593 } 3594 3595 if ( empty( $sanitized['styles'] ) ) { 3596 unset( $theme_json['styles'] ); 3597 } else { 3598 $theme_json['styles'] = $sanitized['styles']; 3599 } 3600 3601 if ( empty( $sanitized['settings'] ) ) { 3602 unset( $theme_json['settings'] ); 3603 } else { 3604 $theme_json['settings'] = $sanitized['settings']; 3605 } 3606 3607 return $theme_json; 3608 } 3609 3610 /** 3611 * Processes a setting node and returns the same node 3612 * without the insecure settings. 3613 * 3614 * @since 5.9.0 3615 * 3616 * @param array $input Node to process. 3617 * @return array 3618 */ 3619 protected static function remove_insecure_settings( $input ) { 3620 $output = array(); 3621 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 3622 foreach ( static::VALID_ORIGINS as $origin ) { 3623 $path_with_origin = $preset_metadata['path']; 3624 $path_with_origin[] = $origin; 3625 $presets = _wp_array_get( $input, $path_with_origin, null ); 3626 if ( null === $presets ) { 3627 continue; 3628 } 3629 3630 $escaped_preset = array(); 3631 foreach ( $presets as $preset ) { 3632 if ( 3633 esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] && 3634 sanitize_html_class( $preset['slug'] ) === $preset['slug'] 3635 ) { 3636 $value = null; 3637 if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) { 3638 $value = $preset[ $preset_metadata['value_key'] ]; 3639 } elseif ( 3640 isset( $preset_metadata['value_func'] ) && 3641 is_callable( $preset_metadata['value_func'] ) 3642 ) { 3643 $value = call_user_func( $preset_metadata['value_func'], $preset ); 3644 } 3645 3646 $preset_is_valid = true; 3647 foreach ( $preset_metadata['properties'] as $property ) { 3648 if ( ! static::is_safe_css_declaration( $property, $value ) ) { 3649 $preset_is_valid = false; 3650 break; 3651 } 3652 } 3653 3654 if ( $preset_is_valid ) { 3655 $escaped_preset[] = $preset; 3656 } 3657 } 3658 } 3659 3660 if ( ! empty( $escaped_preset ) ) { 3661 _wp_array_set( $output, $path_with_origin, $escaped_preset ); 3662 } 3663 } 3664 } 3665 3666 // Ensure indirect properties not included in any `PRESETS_METADATA` value are allowed. 3667 static::remove_indirect_properties( $input, $output ); 3668 3669 return $output; 3670 } 3671 3672 /** 3673 * Processes a style node and returns the same node 3674 * without the insecure styles. 3675 * 3676 * @since 5.9.0 3677 * 3678 * @param array $input Node to process. 3679 * @return array 3680 */ 3681 protected static function remove_insecure_styles( $input ) { 3682 $output = array(); 3683 $declarations = static::compute_style_properties( $input ); 3684 3685 foreach ( $declarations as $declaration ) { 3686 if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) { 3687 $path = static::PROPERTIES_METADATA[ $declaration['name'] ]; 3688 3689 /* 3690 * Check the value isn't an array before adding so as to not 3691 * double up shorthand and longhand styles. 3692 */ 3693 $value = _wp_array_get( $input, $path, array() ); 3694 if ( ! is_array( $value ) ) { 3695 _wp_array_set( $output, $path, $value ); 3696 } 3697 } 3698 } 3699 3700 // Ensure indirect properties not handled by `compute_style_properties` are allowed. 3701 static::remove_indirect_properties( $input, $output ); 3702 3703 return $output; 3704 } 3705 3706 /** 3707 * Checks that a declaration provided by the user is safe. 3708 * 3709 * @since 5.9.0 3710 * 3711 * @param string $property_name Property name in a CSS declaration, i.e. the `color` in `color: red`. 3712 * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`. 3713 * @return bool 3714 */ 3715 protected static function is_safe_css_declaration( $property_name, $property_value ) { 3716 $style_to_validate = $property_name . ': ' . $property_value; 3717 $filtered = esc_html( safecss_filter_attr( $style_to_validate ) ); 3718 return ! empty( trim( $filtered ) ); 3719 } 3720 3721 /** 3722 * Removes indirect properties from the given input node and 3723 * sets in the given output node. 3724 * 3725 * @since 6.2.0 3726 * 3727 * @param array $input Node to process. 3728 * @param array $output The processed node. Passed by reference. 3729 */ 3730 private static function remove_indirect_properties( $input, &$output ) { 3731 foreach ( static::INDIRECT_PROPERTIES_METADATA as $property => $paths ) { 3732 foreach ( $paths as $path ) { 3733 $value = _wp_array_get( $input, $path ); 3734 if ( 3735 is_string( $value ) && 3736 static::is_safe_css_declaration( $property, $value ) 3737 ) { 3738 _wp_array_set( $output, $path, $value ); 3739 } 3740 } 3741 } 3742 } 3743 3744 /** 3745 * Returns the raw data. 3746 * 3747 * @since 5.8.0 3748 * 3749 * @return array Raw data. 3750 */ 3751 public function get_raw_data() { 3752 return $this->theme_json; 3753 } 3754 3755 /** 3756 * Transforms the given editor settings according the 3757 * add_theme_support format to the theme.json format. 3758 * 3759 * @since 5.8.0 3760 * 3761 * @param array $settings Existing editor settings. 3762 * @return array Config that adheres to the theme.json schema. 3763 */ 3764 public static function get_from_editor_settings( $settings ) { 3765 $theme_settings = array( 3766 'version' => static::LATEST_SCHEMA, 3767 'settings' => array(), 3768 ); 3769 3770 // Deprecated theme supports. 3771 if ( isset( $settings['disableCustomColors'] ) ) { 3772 $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors']; 3773 } 3774 3775 if ( isset( $settings['disableCustomGradients'] ) ) { 3776 $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients']; 3777 } 3778 3779 if ( isset( $settings['disableCustomFontSizes'] ) ) { 3780 $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes']; 3781 } 3782 3783 if ( isset( $settings['enableCustomLineHeight'] ) ) { 3784 $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight']; 3785 } 3786 3787 if ( isset( $settings['enableCustomUnits'] ) ) { 3788 $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ? 3789 array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) : 3790 $settings['enableCustomUnits']; 3791 } 3792 3793 if ( isset( $settings['colors'] ) ) { 3794 $theme_settings['settings']['color']['palette'] = $settings['colors']; 3795 } 3796 3797 if ( isset( $settings['gradients'] ) ) { 3798 $theme_settings['settings']['color']['gradients'] = $settings['gradients']; 3799 } 3800 3801 if ( isset( $settings['fontSizes'] ) ) { 3802 $font_sizes = $settings['fontSizes']; 3803 // Back-compatibility for presets without units. 3804 foreach ( $font_sizes as $key => $font_size ) { 3805 if ( is_numeric( $font_size['size'] ) ) { 3806 $font_sizes[ $key ]['size'] = $font_size['size'] . 'px'; 3807 } 3808 } 3809 $theme_settings['settings']['typography']['fontSizes'] = $font_sizes; 3810 } 3811 3812 if ( isset( $settings['enableCustomSpacing'] ) ) { 3813 $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing']; 3814 } 3815 3816 if ( isset( $settings['spacingSizes'] ) ) { 3817 $theme_settings['settings']['spacing']['spacingSizes'] = $settings['spacingSizes']; 3818 } 3819 3820 return $theme_settings; 3821 } 3822 3823 /** 3824 * Returns the current theme's wanted patterns(slugs) to be 3825 * registered from Pattern Directory. 3826 * 3827 * @since 6.0.0 3828 * 3829 * @return string[] 3830 */ 3831 public function get_patterns() { 3832 if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) { 3833 return $this->theme_json['patterns']; 3834 } 3835 return array(); 3836 } 3837 3838 /** 3839 * Returns a valid theme.json as provided by a theme. 3840 * 3841 * Unlike get_raw_data() this returns the presets flattened, as provided by a theme. 3842 * This also uses appearanceTools instead of their opt-ins if all of them are true. 3843 * 3844 * @since 6.0.0 3845 * 3846 * @return array 3847 */ 3848 public function get_data() { 3849 $output = $this->theme_json; 3850 $nodes = static::get_setting_nodes( $output ); 3851 3852 /** 3853 * Flatten the theme & custom origins into a single one. 3854 * 3855 * For example, the following: 3856 * 3857 * { 3858 * "settings": { 3859 * "color": { 3860 * "palette": { 3861 * "theme": [ {} ], 3862 * "custom": [ {} ] 3863 * } 3864 * } 3865 * } 3866 * } 3867 * 3868 * will be converted to: 3869 * 3870 * { 3871 * "settings": { 3872 * "color": { 3873 * "palette": [ {} ] 3874 * } 3875 * } 3876 * } 3877 */ 3878 foreach ( $nodes as $node ) { 3879 foreach ( static::PRESETS_METADATA as $preset_metadata ) { 3880 $path = $node['path']; 3881 foreach ( $preset_metadata['path'] as $preset_metadata_path ) { 3882 $path[] = $preset_metadata_path; 3883 } 3884 $preset = _wp_array_get( $output, $path, null ); 3885 if ( null === $preset ) { 3886 continue; 3887 } 3888 3889 $items = array(); 3890 if ( isset( $preset['theme'] ) ) { 3891 foreach ( $preset['theme'] as $item ) { 3892 $slug = $item['slug']; 3893 unset( $item['slug'] ); 3894 $items[ $slug ] = $item; 3895 } 3896 } 3897 if ( isset( $preset['custom'] ) ) { 3898 foreach ( $preset['custom'] as $item ) { 3899 $slug = $item['slug']; 3900 unset( $item['slug'] ); 3901 $items[ $slug ] = $item; 3902 } 3903 } 3904 $flattened_preset = array(); 3905 foreach ( $items as $slug => $value ) { 3906 $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value ); 3907 } 3908 _wp_array_set( $output, $path, $flattened_preset ); 3909 } 3910 } 3911 3912 /* 3913 * If all of the static::APPEARANCE_TOOLS_OPT_INS are true, 3914 * this code unsets them and sets 'appearanceTools' instead. 3915 */ 3916 foreach ( $nodes as $node ) { 3917 $all_opt_ins_are_set = true; 3918 foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) { 3919 $full_path = $node['path']; 3920 foreach ( $opt_in_path as $opt_in_path_item ) { 3921 $full_path[] = $opt_in_path_item; 3922 } 3923 /* 3924 * Use "unset prop" as a marker instead of "null" because 3925 * "null" can be a valid value for some props (e.g. blockGap). 3926 */ 3927 $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' ); 3928 if ( 'unset prop' === $opt_in_value ) { 3929 $all_opt_ins_are_set = false; 3930 break; 3931 } 3932 } 3933 3934 if ( $all_opt_ins_are_set ) { 3935 $node_path_with_appearance_tools = $node['path']; 3936 $node_path_with_appearance_tools[] = 'appearanceTools'; 3937 _wp_array_set( $output, $node_path_with_appearance_tools, true ); 3938 foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) { 3939 $full_path = $node['path']; 3940 foreach ( $opt_in_path as $opt_in_path_item ) { 3941 $full_path[] = $opt_in_path_item; 3942 } 3943 /* 3944 * Use "unset prop" as a marker instead of "null" because 3945 * "null" can be a valid value for some props (e.g. blockGap). 3946 */ 3947 $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' ); 3948 if ( true !== $opt_in_value ) { 3949 continue; 3950 } 3951 3952 /* 3953 * The following could be improved to be path independent. 3954 * At the moment it relies on a couple of assumptions: 3955 * 3956 * - all opt-ins having a path of size 2. 3957 * - there's two sources of settings: the top-level and the block-level. 3958 */ 3959 if ( 3960 ( 1 === count( $node['path'] ) ) && 3961 ( 'settings' === $node['path'][0] ) 3962 ) { 3963 // Top-level settings. 3964 unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] ); 3965 if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) { 3966 unset( $output['settings'][ $opt_in_path[0] ] ); 3967 } 3968 } elseif ( 3969 ( 3 === count( $node['path'] ) ) && 3970 ( 'settings' === $node['path'][0] ) && 3971 ( 'blocks' === $node['path'][1] ) 3972 ) { 3973 // Block-level settings. 3974 $block_name = $node['path'][2]; 3975 unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] ); 3976 if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) { 3977 unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ); 3978 } 3979 } 3980 } 3981 } 3982 } 3983 3984 wp_recursive_ksort( $output ); 3985 3986 return $output; 3987 } 3988 3989 /** 3990 * Sets the spacingSizes array based on the spacingScale values from theme.json. 3991 * 3992 * @since 6.1.0 3993 * @deprecated 6.6.0 No longer used as the spacingSizes are automatically 3994 * generated in the constructor and merge methods instead 3995 * of manually after instantiation. 3996 * 3997 * @return null|void 3998 */ 3999 public function set_spacing_sizes() { 4000 _deprecated_function( __METHOD__, '6.6.0' ); 4001 4002 $spacing_scale = isset( $this->theme_json['settings']['spacing']['spacingScale'] ) 4003 ? $this->theme_json['settings']['spacing']['spacingScale'] 4004 : array(); 4005 4006 if ( ! isset( $spacing_scale['steps'] ) 4007 || ! is_numeric( $spacing_scale['steps'] ) 4008 || ! isset( $spacing_scale['mediumStep'] ) 4009 || ! isset( $spacing_scale['unit'] ) 4010 || ! isset( $spacing_scale['operator'] ) 4011 || ! isset( $spacing_scale['increment'] ) 4012 || ! isset( $spacing_scale['steps'] ) 4013 || ! is_numeric( $spacing_scale['increment'] ) 4014 || ! is_numeric( $spacing_scale['mediumStep'] ) 4015 || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) { 4016 if ( ! empty( $spacing_scale ) ) { 4017 wp_trigger_error( 4018 __METHOD__, 4019 sprintf( 4020 /* translators: 1: theme.json, 2: settings.spacing.spacingScale */ 4021 __( 'Some of the %1$s %2$s values are invalid' ), 4022 'theme.json', 4023 'settings.spacing.spacingScale' 4024 ), 4025 E_USER_NOTICE 4026 ); 4027 } 4028 return null; 4029 } 4030 4031 // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0. 4032 if ( 0 === $spacing_scale['steps'] ) { 4033 return null; 4034 } 4035 4036 $spacing_sizes = static::compute_spacing_sizes( $spacing_scale ); 4037 4038 // If there are 7 or fewer steps in the scale revert to numbers for labels instead of t-shirt sizes. 4039 if ( $spacing_scale['steps'] <= 7 ) { 4040 for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) { 4041 $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 ); 4042 } 4043 } 4044 4045 _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes ); 4046 } 4047 4048 /** 4049 * Merges two sets of spacing size presets. 4050 * 4051 * @since 6.6.0 4052 * 4053 * @param array $base The base set of spacing sizes. 4054 * @param array $incoming The set of spacing sizes to merge with the base. Duplicate slugs will override the base values. 4055 * @return array The merged set of spacing sizes. 4056 */ 4057 private static function merge_spacing_sizes( $base, $incoming ) { 4058 // Preserve the order if there are no base (spacingScale) values. 4059 if ( empty( $base ) ) { 4060 return $incoming; 4061 } 4062 $merged = array(); 4063 foreach ( $base as $item ) { 4064 $merged[ $item['slug'] ] = $item; 4065 } 4066 foreach ( $incoming as $item ) { 4067 $merged[ $item['slug'] ] = $item; 4068 } 4069 ksort( $merged, SORT_NUMERIC ); 4070 return array_values( $merged ); 4071 } 4072 4073 /** 4074 * Generates a set of spacing sizes by starting with a medium size and 4075 * applying an operator with an increment value to generate the rest of the 4076 * sizes outward from the medium size. The medium slug is '50' with the rest 4077 * of the slugs being 10 apart. The generated names use t-shirt sizing. 4078 * 4079 * Example: 4080 * 4081 * $spacing_scale = array( 4082 * 'steps' => 4, 4083 * 'mediumStep' => 16, 4084 * 'unit' => 'px', 4085 * 'operator' => '+', 4086 * 'increment' => 2, 4087 * ); 4088 * $spacing_sizes = static::compute_spacing_sizes( $spacing_scale ); 4089 * // -> array( 4090 * // array( 'name' => 'Small', 'slug' => '40', 'size' => '14px' ), 4091 * // array( 'name' => 'Medium', 'slug' => '50', 'size' => '16px' ), 4092 * // array( 'name' => 'Large', 'slug' => '60', 'size' => '18px' ), 4093 * // array( 'name' => 'X-Large', 'slug' => '70', 'size' => '20px' ), 4094 * // ) 4095 * 4096 * @since 6.6.0 4097 * 4098 * @param array $spacing_scale { 4099 * The spacing scale values. All are required. 4100 * 4101 * @type int $steps The number of steps in the scale. (up to 10 steps are supported.) 4102 * @type float $mediumStep The middle value that gets the slug '50'. (For even number of steps, this becomes the first middle value.) 4103 * @type string $unit The CSS unit to use for the sizes. 4104 * @type string $operator The mathematical operator to apply to generate the other sizes. Either '+' or '*'. 4105 * @type float $increment The value used with the operator to generate the other sizes. 4106 * } 4107 * @return array The spacing sizes presets or an empty array if some spacing scale values are missing or invalid. 4108 */ 4109 private static function compute_spacing_sizes( $spacing_scale ) { 4110 /* 4111 * This condition is intentionally missing some checks on ranges for the values in order to 4112 * keep backwards compatibility with the previous implementation. 4113 */ 4114 if ( 4115 ! isset( $spacing_scale['steps'] ) || 4116 ! is_numeric( $spacing_scale['steps'] ) || 4117 0 === $spacing_scale['steps'] || 4118 ! isset( $spacing_scale['mediumStep'] ) || 4119 ! is_numeric( $spacing_scale['mediumStep'] ) || 4120 ! isset( $spacing_scale['unit'] ) || 4121 ! isset( $spacing_scale['operator'] ) || 4122 ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) || 4123 ! isset( $spacing_scale['increment'] ) || 4124 ! is_numeric( $spacing_scale['increment'] ) 4125 ) { 4126 return array(); 4127 } 4128 4129 $unit = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] ); 4130 $current_step = $spacing_scale['mediumStep']; 4131 $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 ); 4132 $x_small_count = null; 4133 $below_sizes = array(); 4134 $slug = 40; 4135 $remainder = 0; 4136 4137 for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) { 4138 if ( '+' === $spacing_scale['operator'] ) { 4139 $current_step -= $spacing_scale['increment']; 4140 } elseif ( $spacing_scale['increment'] > 1 ) { 4141 $current_step /= $spacing_scale['increment']; 4142 } else { 4143 $current_step *= $spacing_scale['increment']; 4144 } 4145 4146 if ( $current_step <= 0 ) { 4147 $remainder = $below_midpoint_count; 4148 break; 4149 } 4150 4151 $below_sizes[] = array( 4152 /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */ 4153 'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ), 4154 'slug' => (string) $slug, 4155 'size' => round( $current_step, 2 ) . $unit, 4156 ); 4157 4158 if ( $below_midpoint_count === $steps_mid_point - 2 ) { 4159 $x_small_count = 2; 4160 } 4161 4162 if ( $below_midpoint_count < $steps_mid_point - 2 ) { 4163 ++$x_small_count; 4164 } 4165 4166 $slug -= 10; 4167 } 4168 4169 $below_sizes = array_reverse( $below_sizes ); 4170 4171 $below_sizes[] = array( 4172 'name' => __( 'Medium' ), 4173 'slug' => '50', 4174 'size' => $spacing_scale['mediumStep'] . $unit, 4175 ); 4176 4177 $current_step = $spacing_scale['mediumStep']; 4178 $x_large_count = null; 4179 $above_sizes = array(); 4180 $slug = 60; 4181 $steps_above = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder; 4182 4183 for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) { 4184 $current_step = '+' === $spacing_scale['operator'] 4185 ? $current_step + $spacing_scale['increment'] 4186 : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] ); 4187 4188 $above_sizes[] = array( 4189 /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */ 4190 'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ), 4191 'slug' => (string) $slug, 4192 'size' => round( $current_step, 2 ) . $unit, 4193 ); 4194 4195 if ( 1 === $above_midpoint_count ) { 4196 $x_large_count = 2; 4197 } 4198 4199 if ( $above_midpoint_count > 1 ) { 4200 ++$x_large_count; 4201 } 4202 4203 $slug += 10; 4204 } 4205 4206 $spacing_sizes = $below_sizes; 4207 foreach ( $above_sizes as $above_sizes_item ) { 4208 $spacing_sizes[] = $above_sizes_item; 4209 } 4210 4211 return $spacing_sizes; 4212 } 4213 4214 /** 4215 * This is used to convert the internal representation of variables to the CSS representation. 4216 * For example, `var:preset|color|vivid-green-cyan` becomes `var(--wp--preset--color--vivid-green-cyan)`. 4217 * 4218 * @since 6.3.0 4219 * 4220 * @param string $value The variable such as var:preset|color|vivid-green-cyan to convert. 4221 * @return string The converted variable. 4222 */ 4223 private static function convert_custom_properties( $value ) { 4224 $prefix = 'var:'; 4225 $prefix_len = strlen( $prefix ); 4226 $token_in = '|'; 4227 $token_out = '--'; 4228 if ( str_starts_with( $value, $prefix ) ) { 4229 $unwrapped_name = str_replace( 4230 $token_in, 4231 $token_out, 4232 substr( $value, $prefix_len ) 4233 ); 4234 $value = "var(--wp--$unwrapped_name)"; 4235 } 4236 4237 return $value; 4238 } 4239 4240 /** 4241 * Given a tree, converts the internal representation of variables to the CSS representation. 4242 * It is recursive and modifies the input in-place. 4243 * 4244 * @since 6.3.0 4245 * 4246 * @param array $tree Input to process. 4247 * @return array The modified $tree. 4248 */ 4249 private static function resolve_custom_css_format( $tree ) { 4250 $prefix = 'var:'; 4251 4252 foreach ( $tree as $key => $data ) { 4253 if ( is_string( $data ) && str_starts_with( $data, $prefix ) ) { 4254 $tree[ $key ] = self::convert_custom_properties( $data ); 4255 } elseif ( is_array( $data ) ) { 4256 $tree[ $key ] = self::resolve_custom_css_format( $data ); 4257 } 4258 } 4259 4260 return $tree; 4261 } 4262 4263 /** 4264 * Returns the selectors metadata for a block. 4265 * 4266 * @since 6.3.0 4267 * 4268 * @param object $block_type The block type. 4269 * @param string $root_selector The block's root selector. 4270 * @return array The custom selectors set by the block. 4271 */ 4272 protected static function get_block_selectors( $block_type, $root_selector ) { 4273 if ( ! empty( $block_type->selectors ) ) { 4274 return $block_type->selectors; 4275 } 4276 4277 $selectors = array( 'root' => $root_selector ); 4278 foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) { 4279 $feature_selector = wp_get_block_css_selector( $block_type, $key ); 4280 if ( null !== $feature_selector ) { 4281 $selectors[ $feature ] = array( 'root' => $feature_selector ); 4282 } 4283 } 4284 4285 return $selectors; 4286 } 4287 4288 /** 4289 * Generates all the element selectors for a block. 4290 * 4291 * @since 6.3.0 4292 * 4293 * @param string $root_selector The block's root CSS selector. 4294 * @return array The block's element selectors. 4295 */ 4296 protected static function get_block_element_selectors( $root_selector ) { 4297 /* 4298 * Assign defaults, then override those that the block sets by itself. 4299 * If the block selector is compounded, will append the element to each 4300 * individual block selector. 4301 */ 4302 $block_selectors = explode( ',', $root_selector ); 4303 $element_selectors = array(); 4304 foreach ( static::ELEMENTS as $el_name => $el_selector ) { 4305 $element_selector = array(); 4306 foreach ( $block_selectors as $selector ) { 4307 if ( $selector === $el_selector ) { 4308 $element_selector = array( $el_selector ); 4309 break; 4310 } 4311 $element_selector[] = static::prepend_to_selector( $el_selector, $selector . ' ' ); 4312 } 4313 $element_selectors[ $el_name ] = implode( ',', $element_selector ); 4314 } 4315 4316 return $element_selectors; 4317 } 4318 4319 /** 4320 * Generates style declarations for a node's features e.g., color, border, 4321 * typography etc. that have custom selectors in their related block's 4322 * metadata. 4323 * 4324 * @since 6.3.0 4325 * 4326 * @param object $metadata The related block metadata containing selectors. 4327 * @param object $node A merged theme.json node for block or variation. 4328 * @return array The style declarations for the node's features with custom 4329 * selectors. 4330 */ 4331 protected function get_feature_declarations_for_node( $metadata, &$node ) { 4332 $declarations = array(); 4333 4334 if ( ! isset( $metadata['selectors'] ) ) { 4335 return $declarations; 4336 } 4337 4338 $settings = isset( $this->theme_json['settings'] ) 4339 ? $this->theme_json['settings'] 4340 : array(); 4341 4342 foreach ( $metadata['selectors'] as $feature => $feature_selectors ) { 4343 /* 4344 * Skip if this is the block's root selector or the block doesn't 4345 * have any styles for the feature. 4346 */ 4347 if ( 'root' === $feature || empty( $node[ $feature ] ) ) { 4348 continue; 4349 } 4350 4351 if ( is_array( $feature_selectors ) ) { 4352 foreach ( $feature_selectors as $subfeature => $subfeature_selector ) { 4353 if ( 'root' === $subfeature || empty( $node[ $feature ][ $subfeature ] ) ) { 4354 continue; 4355 } 4356 4357 /* 4358 * Create temporary node containing only the subfeature data 4359 * to leverage existing `compute_style_properties` function. 4360 */ 4361 $subfeature_node = array( 4362 $feature => array( 4363 $subfeature => $node[ $feature ][ $subfeature ], 4364 ), 4365 ); 4366 4367 // Generate style declarations. 4368 $new_declarations = static::compute_style_properties( $subfeature_node, $settings, null, $this->theme_json ); 4369 4370 // Merge subfeature declarations into feature declarations. 4371 if ( isset( $declarations[ $subfeature_selector ] ) ) { 4372 foreach ( $new_declarations as $new_declaration ) { 4373 $declarations[ $subfeature_selector ][] = $new_declaration; 4374 } 4375 } else { 4376 $declarations[ $subfeature_selector ] = $new_declarations; 4377 } 4378 4379 /* 4380 * Remove the subfeature from the block's node now its 4381 * styles will be included under its own selector not the 4382 * block's. 4383 */ 4384 unset( $node[ $feature ][ $subfeature ] ); 4385 } 4386 } 4387 4388 /* 4389 * Now subfeatures have been processed and removed we can process 4390 * feature root selector or simple string selector. 4391 */ 4392 if ( 4393 is_string( $feature_selectors ) || 4394 ( isset( $feature_selectors['root'] ) && $feature_selectors['root'] ) 4395 ) { 4396 $feature_selector = is_string( $feature_selectors ) ? $feature_selectors : $feature_selectors['root']; 4397 4398 /* 4399 * Create temporary node containing only the feature data 4400 * to leverage existing `compute_style_properties` function. 4401 */ 4402 $feature_node = array( $feature => $node[ $feature ] ); 4403 4404 // Generate the style declarations. 4405 $new_declarations = static::compute_style_properties( $feature_node, $settings, null, $this->theme_json ); 4406 4407 /* 4408 * Merge new declarations with any that already exist for 4409 * the feature selector. This may occur when multiple block 4410 * support features use the same custom selector. 4411 */ 4412 if ( isset( $declarations[ $feature_selector ] ) ) { 4413 foreach ( $new_declarations as $new_declaration ) { 4414 $declarations[ $feature_selector ][] = $new_declaration; 4415 } 4416 } else { 4417 $declarations[ $feature_selector ] = $new_declarations; 4418 } 4419 4420 /* 4421 * Remove the feature from the block's node now its styles 4422 * will be included under its own selector not the block's. 4423 */ 4424 unset( $node[ $feature ] ); 4425 } 4426 } 4427 4428 return $declarations; 4429 } 4430 4431 /** 4432 * Replaces CSS variables with their values in place. 4433 * 4434 * @since 6.3.0 4435 * @since 6.5.0 Check for empty style before processing its value. 4436 * 4437 * @param array $styles CSS declarations to convert. 4438 * @param array $values key => value pairs to use for replacement. 4439 * @return array 4440 */ 4441 private static function convert_variables_to_value( $styles, $values ) { 4442 foreach ( $styles as $key => $style ) { 4443 if ( empty( $style ) ) { 4444 continue; 4445 } 4446 4447 if ( is_array( $style ) ) { 4448 $styles[ $key ] = self::convert_variables_to_value( $style, $values ); 4449 continue; 4450 } 4451 4452 if ( 0 <= strpos( $style, 'var(' ) ) { 4453 // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group. 4454 4455 $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts ); 4456 4457 if ( $has_matches ) { 4458 $resolved_style = $styles[ $key ]; 4459 foreach ( $var_parts[1] as $index => $var_part ) { 4460 $key_in_values = 'var(' . $var_part . ')'; 4461 $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan). 4462 $fallback = $var_parts[2][ $index ]; // the fallback value. 4463 $resolved_style = str_replace( 4464 array( 4465 $rule_to_replace, 4466 $fallback, 4467 ), 4468 array( 4469 isset( $values[ $key_in_values ] ) ? $values[ $key_in_values ] : $rule_to_replace, 4470 isset( $values[ $fallback ] ) ? $values[ $fallback ] : $fallback, 4471 ), 4472 $resolved_style 4473 ); 4474 } 4475 $styles[ $key ] = $resolved_style; 4476 } 4477 } 4478 } 4479 4480 return $styles; 4481 } 4482 4483 /** 4484 * Resolves the values of CSS variables in the given styles. 4485 * 4486 * @since 6.3.0 4487 * 4488 * @param WP_Theme_JSON $theme_json The theme json resolver. 4489 * @return WP_Theme_JSON The $theme_json with resolved variables. 4490 */ 4491 public static function resolve_variables( $theme_json ) { 4492 $settings = $theme_json->get_settings(); 4493 $styles = $theme_json->get_raw_data()['styles']; 4494 $preset_vars = static::compute_preset_vars( $settings, static::VALID_ORIGINS ); 4495 $theme_vars = static::compute_theme_vars( $settings ); 4496 $vars = array_reduce( 4497 array_merge( $preset_vars, $theme_vars ), 4498 function ( $carry, $item ) { 4499 $name = $item['name']; 4500 $carry[ "var({$name})" ] = $item['value']; 4501 return $carry; 4502 }, 4503 array() 4504 ); 4505 4506 $theme_json->theme_json['styles'] = self::convert_variables_to_value( $styles, $vars ); 4507 return $theme_json; 4508 } 4509 4510 /** 4511 * Generates a selector for a block style variation. 4512 * 4513 * @since 6.5.0 4514 * 4515 * @param string $variation_name Name of the block style variation. 4516 * @param string $block_selector CSS selector for the block. 4517 * @return string Block selector with block style variation selector added to it. 4518 */ 4519 protected static function get_block_style_variation_selector( $variation_name, $block_selector ) { 4520 $variation_class = ".is-style-$variation_name"; 4521 4522 if ( ! $block_selector ) { 4523 return $variation_class; 4524 } 4525 4526 $limit = 1; 4527 $selector_parts = explode( ',', $block_selector ); 4528 $result = array(); 4529 4530 foreach ( $selector_parts as $part ) { 4531 $result[] = preg_replace_callback( 4532 '/((?::\([^)]+\))?\s*)([^\s:]+)/', 4533 function ( $matches ) use ( $variation_class ) { 4534 return $matches[1] . $matches[2] . $variation_class; 4535 }, 4536 $part, 4537 $limit 4538 ); 4539 } 4540 4541 return implode( ',', $result ); 4542 } 4543 4544 /** 4545 * Collects valid block style variations keyed by block type. 4546 * 4547 * @since 6.6.0 4548 * @since 6.8.0 Added the `$blocks_metadata` parameter. 4549 * 4550 * @param array $blocks_metadata Optional. List of metadata per block. Default is the metadata for all blocks. 4551 * @return array Valid block style variations by block type. 4552 */ 4553 protected static function get_valid_block_style_variations( $blocks_metadata = array() ) { 4554 $valid_variations = array(); 4555 $blocks_metadata = empty( $blocks_metadata ) ? static::get_blocks_metadata() : $blocks_metadata; 4556 foreach ( $blocks_metadata as $block_name => $block_meta ) { 4557 if ( ! isset( $block_meta['styleVariations'] ) ) { 4558 continue; 4559 } 4560 $valid_variations[ $block_name ] = array_keys( $block_meta['styleVariations'] ); 4561 } 4562 4563 return $valid_variations; 4564 } 4565 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Thu Nov 21 08:20:01 2024 | Cross-referenced by PHPXref |