PluginProbe
Gutenberg / 19.6.1
Gutenberg v19.6.1
24.0.0 23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 All 403 releases
gutenberg / lib / class-wp-theme-json-gutenberg.php

class-wp-theme-json-gutenberg.php in Gutenberg 19.6.1, at lib/class-wp-theme-json-gutenberg.php

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