-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
class-wp-theme-json-6-1.php
1472 lines (1311 loc) · 55.2 KB
/
class-wp-theme-json-6-1.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* WP_Theme_JSON_6_1 class
*
* @package gutenberg
*/
/**
* Class that encapsulates the processing of structures that adhere to the theme.json spec.
*
* This class is for internal core usage and is not supposed to be used by extenders (plugins and/or themes).
* This is a low-level API that may need to do breaking changes. Please,
* use get_global_settings, get_global_styles, and get_global_stylesheet instead.
*
* @access private
*/
class WP_Theme_JSON_6_1 extends WP_Theme_JSON_6_0 {
/**
* Define which defines which pseudo selectors are enabled for
* which elements.
* Note: this will effect both top level and block level elements.
*/
const VALID_ELEMENT_PSEUDO_SELECTORS = array(
'link' => array( ':hover', ':focus', ':active', ':visited' ),
'button' => array( ':hover', ':focus', ':active', ':visited' ),
);
/**
* Metadata for style properties.
*
* Each element is a direct mapping from the CSS property name to the
* path to the value in theme.json & block attributes.
*/
const PROPERTIES_METADATA = array(
'background' => array( 'color', 'gradient' ),
'background-color' => array( 'color', 'background' ),
'border-radius' => array( 'border', 'radius' ),
'border-top-left-radius' => array( 'border', 'radius', 'topLeft' ),
'border-top-right-radius' => array( 'border', 'radius', 'topRight' ),
'border-bottom-left-radius' => array( 'border', 'radius', 'bottomLeft' ),
'border-bottom-right-radius' => array( 'border', 'radius', 'bottomRight' ),
'border-color' => array( 'border', 'color' ),
'border-width' => array( 'border', 'width' ),
'border-style' => array( 'border', 'style' ),
'border-top-color' => array( 'border', 'top', 'color' ),
'border-top-width' => array( 'border', 'top', 'width' ),
'border-top-style' => array( 'border', 'top', 'style' ),
'border-right-color' => array( 'border', 'right', 'color' ),
'border-right-width' => array( 'border', 'right', 'width' ),
'border-right-style' => array( 'border', 'right', 'style' ),
'border-bottom-color' => array( 'border', 'bottom', 'color' ),
'border-bottom-width' => array( 'border', 'bottom', 'width' ),
'border-bottom-style' => array( 'border', 'bottom', 'style' ),
'border-left-color' => array( 'border', 'left', 'color' ),
'border-left-width' => array( 'border', 'left', 'width' ),
'border-left-style' => array( 'border', 'left', 'style' ),
'color' => array( 'color', 'text' ),
'font-family' => array( 'typography', 'fontFamily' ),
'font-size' => array( 'typography', 'fontSize' ),
'font-style' => array( 'typography', 'fontStyle' ),
'font-weight' => array( 'typography', 'fontWeight' ),
'letter-spacing' => array( 'typography', 'letterSpacing' ),
'line-height' => array( 'typography', 'lineHeight' ),
'margin' => array( 'spacing', 'margin' ),
'margin-top' => array( 'spacing', 'margin', 'top' ),
'margin-right' => array( 'spacing', 'margin', 'right' ),
'margin-bottom' => array( 'spacing', 'margin', 'bottom' ),
'margin-left' => array( 'spacing', 'margin', 'left' ),
'padding' => array( 'spacing', 'padding' ),
'padding-top' => array( 'spacing', 'padding', 'top' ),
'padding-right' => array( 'spacing', 'padding', 'right' ),
'padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
'padding-left' => array( 'spacing', 'padding', 'left' ),
'--wp--style--root--padding' => array( 'spacing', 'padding' ),
'--wp--style--root--padding-top' => array( 'spacing', 'padding', 'top' ),
'--wp--style--root--padding-right' => array( 'spacing', 'padding', 'right' ),
'--wp--style--root--padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
'--wp--style--root--padding-left' => array( 'spacing', 'padding', 'left' ),
'text-decoration' => array( 'typography', 'textDecoration' ),
'text-transform' => array( 'typography', 'textTransform' ),
'filter' => array( 'filter', 'duotone' ),
'box-shadow' => array( 'shadow' ),
);
/**
* The valid elements that can be found under styles.
*
* @var string[]
*/
const ELEMENTS = array(
'link' => 'a:where(:not(.wp-element-button))', // The where is needed to lower the specificity.
'heading' => 'h1, h2, h3, h4, h5, h6',
'h1' => 'h1',
'h2' => 'h2',
'h3' => 'h3',
'h4' => 'h4',
'h5' => 'h5',
'h6' => 'h6',
'button' => '.wp-element-button, .wp-block-button__link', // We have the .wp-block-button__link class so that this will target older buttons that have been serialized.
'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', // The block classes are necessary to target older content that won't use the new class names.
'cite' => 'cite',
);
const __EXPERIMENTAL_ELEMENT_CLASS_NAMES = array(
'button' => 'wp-element-button',
'caption' => 'wp-element-caption',
);
// List of block support features that can have their related styles
// generated under their own feature level selector rather than the block's.
const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = array(
'__experimentalBorder' => 'border',
'color' => 'color',
'spacing' => 'spacing',
'typography' => 'typography',
);
/**
* Given an element name, returns a class name.
*
* @param string $element The name of the element.
*
* @return string The name of the class.
*
* @since 6.1.0
*/
public static function get_element_class_name( $element ) {
return array_key_exists( $element, static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES ) ? static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ] : '';
}
/**
* Sanitizes the input according to the schemas.
*
* @since 5.8.0
* @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters.
*
* @param array $input Structure to sanitize.
* @param array $valid_block_names List of valid block names.
* @param array $valid_element_names List of valid element names.
* @return array The sanitized output.
*/
protected static function sanitize( $input, $valid_block_names, $valid_element_names ) {
$output = array();
if ( ! is_array( $input ) ) {
return $output;
}
// Preserve only the top most level keys.
$output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) );
// Remove any rules that are annotated as "top" in VALID_STYLES constant.
// Some styles are only meant to be available at the top-level (e.g.: blockGap),
// hence, the schema for blocks & elements should not have them.
$styles_non_top_level = static::VALID_STYLES;
foreach ( array_keys( $styles_non_top_level ) as $section ) {
if ( array_key_exists( $section, $styles_non_top_level ) && is_array( $styles_non_top_level[ $section ] ) ) {
foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) {
if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) {
unset( $styles_non_top_level[ $section ][ $prop ] );
}
}
}
}
// Build the schema based on valid block & element names.
$schema = array();
$schema_styles_elements = array();
// Set allowed element pseudo selectors based on per element allow list.
// Target data structure in schema:
// e.g.
// - top level elements: `$schema['styles']['elements']['link'][':hover']`.
// - block level elements: `$schema['styles']['blocks']['core/button']['elements']['link'][':hover']`.
foreach ( $valid_element_names as $element ) {
$schema_styles_elements[ $element ] = $styles_non_top_level;
if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
$schema_styles_elements[ $element ][ $pseudo_selector ] = $styles_non_top_level;
}
}
}
$schema_styles_blocks = array();
$schema_settings_blocks = array();
foreach ( $valid_block_names as $block ) {
$schema_settings_blocks[ $block ] = static::VALID_SETTINGS;
$schema_styles_blocks[ $block ] = $styles_non_top_level;
$schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
}
$schema['styles'] = static::VALID_STYLES;
$schema['styles']['blocks'] = $schema_styles_blocks;
$schema['styles']['elements'] = $schema_styles_elements;
$schema['settings'] = static::VALID_SETTINGS;
$schema['settings']['blocks'] = $schema_settings_blocks;
// Remove anything that's not present in the schema.
foreach ( array( 'styles', 'settings' ) as $subtree ) {
if ( ! isset( $input[ $subtree ] ) ) {
continue;
}
if ( ! is_array( $input[ $subtree ] ) ) {
unset( $output[ $subtree ] );
continue;
}
$result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
if ( empty( $result ) ) {
unset( $output[ $subtree ] );
} else {
$output[ $subtree ] = $result;
}
}
return $output;
}
/**
* Removes insecure data from theme.json.
*
* @since 5.9.0
*
* @param array $theme_json Structure to sanitize.
* @return array Sanitized structure.
*/
public static function remove_insecure_properties( $theme_json ) {
$sanitized = array();
$theme_json = WP_Theme_JSON_Schema::migrate( $theme_json );
$valid_block_names = array_keys( static::get_blocks_metadata() );
$valid_element_names = array_keys( static::ELEMENTS );
$theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names );
$blocks_metadata = static::get_blocks_metadata();
$style_nodes = static::get_style_nodes( $theme_json, $blocks_metadata );
foreach ( $style_nodes as $metadata ) {
$input = _wp_array_get( $theme_json, $metadata['path'], array() );
if ( empty( $input ) ) {
continue;
}
$output = static::remove_insecure_styles( $input );
// Get a reference to element name from path.
// $metadata['path'] = array('styles','elements','link');.
$current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ];
// $output is stripped of pseudo selectors. Readd and process them
// for insecure styles here.
if ( array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) {
if ( isset( $input[ $pseudo_selector ] ) ) {
$output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] );
}
}
}
if ( ! empty( $output ) ) {
_wp_array_set( $sanitized, $metadata['path'], $output );
}
}
$setting_nodes = static::get_setting_nodes( $theme_json );
foreach ( $setting_nodes as $metadata ) {
$input = _wp_array_get( $theme_json, $metadata['path'], array() );
if ( empty( $input ) ) {
continue;
}
$output = static::remove_insecure_settings( $input );
if ( ! empty( $output ) ) {
_wp_array_set( $sanitized, $metadata['path'], $output );
}
}
if ( empty( $sanitized['styles'] ) ) {
unset( $theme_json['styles'] );
} else {
$theme_json['styles'] = $sanitized['styles'];
}
if ( empty( $sanitized['settings'] ) ) {
unset( $theme_json['settings'] );
} else {
$theme_json['settings'] = $sanitized['settings'];
}
return $theme_json;
}
/**
* The valid properties under the styles key.
*
* @var array
*/
const VALID_STYLES = array(
'border' => array(
'color' => null,
'radius' => null,
'style' => null,
'width' => null,
'top' => null,
'right' => null,
'bottom' => null,
'left' => null,
),
'color' => array(
'background' => null,
'gradient' => null,
'text' => null,
),
'shadow' => null,
'filter' => array(
'duotone' => null,
),
'spacing' => array(
'margin' => null,
'padding' => null,
'blockGap' => null,
),
'typography' => array(
'fontFamily' => null,
'fontSize' => null,
'fontStyle' => null,
'fontWeight' => null,
'letterSpacing' => null,
'lineHeight' => null,
'textDecoration' => null,
'textTransform' => null,
),
);
/**
* Function that appends a sub-selector to a existing one.
*
* Given the compounded $selector "h1, h2, h3"
* and the $to_append selector ".some-class" the result will be
* "h1.some-class, h2.some-class, h3.some-class".
*
* @since 5.8.0
* @since 6.1.0 Added append position.
*
* @param string $selector Original selector.
* @param string $to_append Selector to append.
* @param string $position A position sub-selector should be appended. Default: 'right'.
* @return string
*/
protected static function append_to_selector( $selector, $to_append, $position = 'right' ) {
$new_selectors = array();
$selectors = explode( ',', $selector );
foreach ( $selectors as $sel ) {
$new_selectors[] = 'right' === $position ? $sel . $to_append : $to_append . $sel;
}
return implode( ',', $new_selectors );
}
/**
* Returns the metadata for each block.
*
* Example:
*
* {
* 'core/paragraph': {
* 'selector': 'p',
* 'elements': {
* 'link' => 'link selector',
* 'etc' => 'element selector'
* }
* },
* 'core/heading': {
* 'selector': 'h1',
* 'elements': {}
* },
* 'core/image': {
* 'selector': '.wp-block-image',
* 'duotone': 'img',
* 'elements': {}
* }
* }
*
* @return array Block metadata.
*/
protected static function get_blocks_metadata() {
if ( null !== static::$blocks_metadata ) {
return static::$blocks_metadata;
}
static::$blocks_metadata = array();
$registry = WP_Block_Type_Registry::get_instance();
$blocks = $registry->get_all_registered();
foreach ( $blocks as $block_name => $block_type ) {
if (
isset( $block_type->supports['__experimentalSelector'] ) &&
is_string( $block_type->supports['__experimentalSelector'] )
) {
static::$blocks_metadata[ $block_name ]['selector'] = $block_type->supports['__experimentalSelector'];
} else {
static::$blocks_metadata[ $block_name ]['selector'] = '.wp-block-' . str_replace( '/', '-', str_replace( 'core/', '', $block_name ) );
}
if (
isset( $block_type->supports['color']['__experimentalDuotone'] ) &&
is_string( $block_type->supports['color']['__experimentalDuotone'] )
) {
static::$blocks_metadata[ $block_name ]['duotone'] = $block_type->supports['color']['__experimentalDuotone'];
}
// Generate block support feature level selectors if opted into
// for the current block.
$features = array();
foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) {
if (
isset( $block_type->supports[ $key ]['__experimentalSelector'] ) &&
$block_type->supports[ $key ]['__experimentalSelector']
) {
$features[ $feature ] = static::scope_selector(
static::$blocks_metadata[ $block_name ]['selector'],
$block_type->supports[ $key ]['__experimentalSelector']
);
}
}
if ( ! empty( $features ) ) {
static::$blocks_metadata[ $block_name ]['features'] = $features;
}
// Assign defaults, then overwrite those that the block sets by itself.
// If the block selector is compounded, will append the element to each
// individual block selector.
$block_selectors = explode( ',', static::$blocks_metadata[ $block_name ]['selector'] );
foreach ( static::ELEMENTS as $el_name => $el_selector ) {
$element_selector = array();
foreach ( $block_selectors as $selector ) {
if ( $selector === $el_selector ) {
$element_selector = array( $el_selector );
break;
}
$element_selector = static::append_to_selector( $el_selector, $selector . ' ', 'left' );
}
static::$blocks_metadata[ $block_name ]['elements'][ $el_name ] = $element_selector;
}
}
return static::$blocks_metadata;
}
/**
* Builds metadata for the style nodes, which returns in the form of:
*
* [
* [
* 'path' => [ 'path', 'to', 'some', 'node' ],
* 'selector' => 'CSS selector for some node',
* 'duotone' => 'CSS selector for duotone for some node'
* ],
* [
* 'path' => ['path', 'to', 'other', 'node' ],
* 'selector' => 'CSS selector for other node',
* 'duotone' => null
* ],
* ]
*
* @since 5.8.0
*
* @param array $theme_json The tree to extract style nodes from.
* @param array $selectors List of selectors per block.
* @return array
*/
protected static function get_style_nodes( $theme_json, $selectors = array() ) {
$nodes = array();
if ( ! isset( $theme_json['styles'] ) ) {
return $nodes;
}
// Top-level.
$nodes[] = array(
'path' => array( 'styles' ),
'selector' => static::ROOT_BLOCK_SELECTOR,
);
if ( isset( $theme_json['styles']['elements'] ) ) {
foreach ( self::ELEMENTS as $element => $selector ) {
if ( ! isset( $theme_json['styles']['elements'][ $element ] ) || ! array_key_exists( $element, static::ELEMENTS ) ) {
continue;
}
// Handle element defaults.
$nodes[] = array(
'path' => array( 'styles', 'elements', $element ),
'selector' => static::ELEMENTS[ $element ],
);
// Handle any pseudo selectors for the element.
if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) {
$nodes[] = array(
'path' => array( 'styles', 'elements', $element ),
'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ),
);
}
}
}
}
}
// Blocks.
if ( ! isset( $theme_json['styles']['blocks'] ) ) {
return $nodes;
}
$nodes = array_merge( $nodes, static::get_block_nodes( $theme_json, $selectors ) );
// This filter allows us to modify the output of WP_Theme_JSON so that we can do things like loading block CSS independently.
return apply_filters( 'gutenberg_get_style_nodes', $nodes );
}
/**
* A public helper to get the block nodes from a theme.json file.
*
* @return array The block nodes in theme.json.
*/
public function get_styles_block_nodes() {
return static::get_block_nodes( $this->theme_json );
}
/**
* An internal method to get the block nodes from a theme.json file.
*
* @param array $theme_json The theme.json converted to an array.
* @param array $selectors Optional list of selectors per block.
*
* @return array The block nodes in theme.json.
*/
private static function get_block_nodes( $theme_json, $selectors = array() ) {
$selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors;
$nodes = array();
if ( ! isset( $theme_json['styles'] ) ) {
return $nodes;
}
// Blocks.
if ( ! isset( $theme_json['styles']['blocks'] ) ) {
return $nodes;
}
foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
$selector = null;
if ( isset( $selectors[ $name ]['selector'] ) ) {
$selector = $selectors[ $name ]['selector'];
}
$duotone_selector = null;
if ( isset( $selectors[ $name ]['duotone'] ) ) {
$duotone_selector = $selectors[ $name ]['duotone'];
}
$feature_selectors = null;
if ( isset( $selectors[ $name ]['features'] ) ) {
$feature_selectors = $selectors[ $name ]['features'];
}
$nodes[] = array(
'name' => $name,
'path' => array( 'styles', 'blocks', $name ),
'selector' => $selector,
'duotone' => $duotone_selector,
'features' => $feature_selectors,
);
if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) {
foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) {
$nodes[] = array(
'path' => array( 'styles', 'blocks', $name, 'elements', $element ),
'selector' => $selectors[ $name ]['elements'][ $element ],
);
// Handle any pseudo selectors for the element.
if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) {
$nodes[] = array(
'path' => array( 'styles', 'blocks', $name, 'elements', $element ),
'selector' => static::append_to_selector( $selectors[ $name ]['elements'][ $element ], $pseudo_selector ),
);
}
}
}
}
}
}
return $nodes;
}
/**
* Returns the stylesheet that results of processing
* the theme.json structure this object represents.
*
* @param array $types Types of styles to load. Will load all by default. It accepts:
* 'variables': only the CSS Custom Properties for presets & custom ones.
* 'styles': only the styles section in theme.json.
* 'presets': only the classes for the presets.
* @param array $origins A list of origins to include. By default it includes VALID_ORIGINS.
* @return string Stylesheet.
*/
public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null ) {
if ( null === $origins ) {
$origins = static::VALID_ORIGINS;
}
if ( is_string( $types ) ) {
// Dispatch error and map old arguments to new ones.
_deprecated_argument( __FUNCTION__, '5.9' );
if ( 'block_styles' === $types ) {
$types = array( 'styles', 'presets' );
} elseif ( 'css_variables' === $types ) {
$types = array( 'variables' );
} else {
$types = array( 'variables', 'styles', 'presets' );
}
}
$blocks_metadata = static::get_blocks_metadata();
$style_nodes = static::get_style_nodes( $this->theme_json, $blocks_metadata );
$setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
$stylesheet = '';
if ( in_array( 'variables', $types, true ) ) {
$stylesheet .= $this->get_css_variables( $setting_nodes, $origins );
}
if ( in_array( 'styles', $types, true ) ) {
$stylesheet .= $this->get_block_classes( $style_nodes );
} elseif ( in_array( 'base-layout-styles', $types, true ) ) {
// Base layout styles are provided as part of `styles`, so only output separately if explicitly requested.
// For backwards compatibility, the Columns block is explicitly included, to support a different default gap value.
$base_styles_nodes = array(
array(
'path' => array( 'styles' ),
'selector' => static::ROOT_BLOCK_SELECTOR,
),
array(
'path' => array( 'styles', 'blocks', 'core/columns' ),
'selector' => '.wp-block-columns',
'name' => 'core/columns',
),
);
foreach ( $base_styles_nodes as $base_style_node ) {
$stylesheet .= $this->get_layout_styles( $base_style_node );
}
}
if ( in_array( 'presets', $types, true ) ) {
$stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
}
return $stylesheet;
}
/**
* Gets the CSS rules for a particular block from theme.json.
*
* @param array $block_metadata Metadata about the block to get styles for.
*
* @return string Styles for the block.
*/
public function get_styles_for_block( $block_metadata ) {
$node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
$use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
$selector = $block_metadata['selector'];
$settings = _wp_array_get( $this->theme_json, array( 'settings' ) );
// Process style declarations for block support features the current
// block contains selectors for. Values for a feature with a custom
// selector are filtered from the theme.json node before it is
// processed as normal.
$feature_declarations = array();
if ( ! empty( $block_metadata['features'] ) ) {
foreach ( $block_metadata['features'] as $feature_name => $feature_selector ) {
if ( ! empty( $node[ $feature_name ] ) ) {
// Create temporary node containing only the feature data
// to leverage existing `compute_style_properties` function.
$feature = array( $feature_name => $node[ $feature_name ] );
// Generate the feature's declarations only.
$new_feature_declarations = static::compute_style_properties( $feature, $settings, null, $this->theme_json );
// Merge new declarations with any that already exist for
// the feature selector. This may occur when multiple block
// support features use the same custom selector.
if ( isset( $feature_declarations[ $feature_selector ] ) ) {
$feature_declarations[ $feature_selector ] = array_merge( $feature_declarations[ $feature_selector ], $new_feature_declarations );
} else {
$feature_declarations[ $feature_selector ] = $new_feature_declarations;
}
// Remove the feature from the block's node now the
// styles will be included under the feature level selector.
unset( $node[ $feature_name ] );
}
}
}
// Get a reference to element name from path.
// $block_metadata['path'] = array('styles','elements','link');
// Make sure that $block_metadata['path'] describes an element node, like ['styles', 'element', 'link'].
// Skip non-element paths like just ['styles'].
$is_processing_element = in_array( 'elements', $block_metadata['path'], true );
$current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null;
$element_pseudo_allowed = array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ? static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] : array();
// Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
// This also resets the array keys.
$pseudo_matches = array_values(
array_filter(
$element_pseudo_allowed,
function( $pseudo_selector ) use ( $selector ) {
return str_contains( $selector, $pseudo_selector );
}
)
);
$pseudo_selector = isset( $pseudo_matches[0] ) ? $pseudo_matches[0] : null;
// If the current selector is a pseudo selector that's defined in the allow list for the current
// element then compute the style properties for it.
// Otherwise just compute the styles for the default selector as normal.
if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) && array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true ) ) {
$declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
} else {
$declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
}
$block_rules = '';
// 1. Separate the ones who use the general selector
// and the ones who use the duotone selector.
$declarations_duotone = array();
foreach ( $declarations as $index => $declaration ) {
if ( 'filter' === $declaration['name'] ) {
unset( $declarations[ $index ] );
$declarations_duotone[] = $declaration;
}
}
// 2. Generate and append the rules that use the general selector.
$block_rules .= static::to_ruleset( $selector, $declarations );
// 3. Generate and append the rules that use the duotone selector.
if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
$selector_duotone = static::scope_selector( $block_metadata['selector'], $block_metadata['duotone'] );
$block_rules .= static::to_ruleset( $selector_duotone, $declarations_duotone );
}
// 4. Generate Layout block gap styles.
if (
static::ROOT_BLOCK_SELECTOR !== $selector &&
! empty( $block_metadata['name'] )
) {
$block_rules .= $this->get_layout_styles( $block_metadata );
}
// 5. Generate and append the feature level rulesets.
foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
$block_rules .= static::to_ruleset( $feature_selector, $individual_feature_declarations );
}
if ( static::ROOT_BLOCK_SELECTOR === $selector ) {
/*
* Reset default browser margin on the root body element.
* This is set on the root selector **before** generating the ruleset
* from the `theme.json`. This is to ensure that if the `theme.json` declares
* `margin` in its `spacing` declaration for the `body` element then these
* user-generated values take precedence in the CSS cascade.
* @link https://github.com/WordPress/gutenberg/issues/36147.
*/
$block_rules .= 'body { margin: 0;';
/*
* If there are content and wide widths in theme.json, output them
* as custom properties on the body element so all blocks can use them.
*/
if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) {
$content_size = isset( $settings['layout']['contentSize'] ) ? $settings['layout']['contentSize'] : $settings['layout']['wideSize'];
$content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial';
$wide_size = isset( $settings['layout']['wideSize'] ) ? $settings['layout']['wideSize'] : $settings['layout']['contentSize'];
$wide_size = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial';
$block_rules .= '--wp--style--global--content-size: ' . $content_size . ';';
$block_rules .= '--wp--style--global--wide-size: ' . $wide_size . ';';
}
$block_rules .= '}';
}
if ( static::ROOT_BLOCK_SELECTOR === $selector ) {
if ( $use_root_padding ) {
$block_rules .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }';
$block_rules .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
$block_rules .= '.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }';
$block_rules .= '.has-global-padding > .alignfull > :where([class*="wp-block-"]:not(.alignfull):not(.alignfull):not([class*="__"]),p,h1,h2,h3,h4,h5,h6,ul,ol) { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
}
$block_rules .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
$block_rules .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
$block_rules .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
$block_gap_value = _wp_array_get( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ), '0.5em' );
$has_block_gap_support = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'blockGap' ) ) !== null;
if ( $has_block_gap_support ) {
$block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) );
$block_rules .= '.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }';
$block_rules .= ".wp-site-blocks > * + * { margin-block-start: $block_gap_value; }";
// For backwards compatibility, ensure the legacy block gap CSS variable is still available.
$block_rules .= "$selector { --wp--style--block-gap: $block_gap_value; }";
}
$block_rules .= $this->get_layout_styles( $block_metadata );
}
return $block_rules;
}
/**
* Converts each style section into a list of rulesets
* containing the block styles to be appended to the stylesheet.
*
* See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
*
* For each section this creates a new ruleset such as:
*
* block-selector {
* style-property-one: value;
* }
*
* @param array $style_nodes Nodes with styles.
* @return string The new stylesheet.
*/
protected function get_block_classes( $style_nodes ) {
$block_rules = '';
foreach ( $style_nodes as $metadata ) {
if ( null === $metadata['selector'] ) {
continue;
}
$block_rules .= static::get_styles_for_block( $metadata );
}
return $block_rules;
}
/**
* Given a styles array, it extracts the style properties
* and adds them to the $declarations array following the format:
*
* ```php
* array(
* 'name' => 'property_name',
* 'value' => 'property_value,
* )
* ```
*
* @param array $styles Styles to process.
* @param array $settings Theme settings.
* @param array $properties Properties metadata.
* @param array $theme_json Theme JSON array.
* @param string $selector The style block selector.
* @param boolean $use_root_padding Whether to add custom properties at root level.
* @return array Returns the modified $declarations.
*/
protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) {
if ( null === $properties ) {
$properties = static::PROPERTIES_METADATA;
}
$declarations = array();
if ( empty( $styles ) ) {
return $declarations;
}
$root_variable_duplicates = array();
foreach ( $properties as $css_property => $value_path ) {
$value = static::get_property_value( $styles, $value_path, $theme_json );
if ( str_starts_with( $css_property, '--wp--style--root--' ) && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) {
continue;
}
// Root-level padding styles don't currently support strings with CSS shorthand values.
// This may change: https://github.com/WordPress/gutenberg/issues/40132.
if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) {
continue;
}
if ( str_starts_with( $css_property, '--wp--style--root--' ) && $use_root_padding ) {
$root_variable_duplicates[] = substr( $css_property, strlen( '--wp--style--root--' ) );
}
// Look up protected properties, keyed by value path.
// Skip protected properties that are explicitly set to `null`.
if ( is_array( $value_path ) ) {
$path_string = implode( '.', $value_path );
if (
array_key_exists( $path_string, static::PROTECTED_PROPERTIES ) &&
_wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null
) {
continue;
}
}
// Skip if empty and not "0" or value represents array of longhand values.
$has_missing_value = empty( $value ) && ! is_numeric( $value );
if ( $has_missing_value || is_array( $value ) ) {
continue;
}
$declarations[] = array(
'name' => $css_property,
'value' => $value,
);
}
// If a variable value is added to the root, the corresponding property should be removed.
foreach ( $root_variable_duplicates as $duplicate ) {
$discard = array_search( $duplicate, array_column( $declarations, 'name' ), true );
if ( is_numeric( $discard ) ) {
array_splice( $declarations, $discard, 1 );
}
}
return $declarations;
}
/**
* Returns the style property for the given path.
*
* It also converts CSS Custom Property stored as
* "var:preset|color|secondary" to the form
* "--wp--preset--color--secondary".
*
* It also converts references to a path to the value
* stored at that location, e.g.
* { "ref": "style.color.background" } => "#fff".
*
* @param array $styles Styles subtree.
* @param array $path Which property to process.
* @param array $theme_json Theme JSON array.
* @return string Style property value.
*/
protected static function get_property_value( $styles, $path, $theme_json = null ) {
$value = _wp_array_get( $styles, $path, '' );
// This converts references to a path to the value at that path
// where the values is an array with a "ref" key, pointing to a path.
// For example: { "ref": "style.color.background" } => "#fff".
if ( is_array( $value ) && array_key_exists( 'ref', $value ) ) {
$value_path = explode( '.', $value['ref'] );
$ref_value = _wp_array_get( $theme_json, $value_path );
// Only use the ref value if we find anything.
if ( ! empty( $ref_value ) && is_string( $ref_value ) ) {
$value = $ref_value;
}
if ( is_array( $ref_value ) && array_key_exists( 'ref', $ref_value ) ) {
$path_string = json_encode( $path );
$ref_value_string = json_encode( $ref_value );
_doing_it_wrong( 'get_property_value', "Your theme.json file uses a dynamic value (${ref_value_string}) for the path at ${path_string}. However, the value at ${path_string} is also a dynamic value (pointing to ${ref_value['ref']}) and pointing to another dynamic value is not supported. Please update ${path_string} to point directly to ${ref_value['ref']}.", '6.1.0' );
}
}
if ( '' === $value || is_array( $value ) ) {
return $value;
}
// Convert custom CSS properties.
$prefix = 'var:';
$prefix_len = strlen( $prefix );
$token_in = '|';
$token_out = '--';
if ( 0 === strncmp( $value, $prefix, $prefix_len ) ) {