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