-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
class-wp-theme-json-gutenberg.php
1787 lines (1618 loc) · 54.3 KB
/
class-wp-theme-json-gutenberg.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_Gutenberg 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_Gutenberg {
/**
* Container of data in theme.json format.
*
* @var array
*/
private $theme_json = null;
/**
* Holds block metadata extracted from block.json
* to be shared among all instances so we don't
* process it twice.
*
* @var array
*/
private static $blocks_metadata = null;
/**
* The CSS selector for the top-level styles.
*
* @var string
*/
const ROOT_BLOCK_SELECTOR = 'body';
/**
* The sources of data this object can represent.
*
* @since 5.8.0
* @var string[]
*/
const VALID_ORIGINS = array(
'default',
'theme',
'custom',
);
/**
* Presets are a set of values that serve
* to bootstrap some styles: colors, font sizes, etc.
*
* They are a unkeyed array of values such as:
*
* ```php
* array(
* array(
* 'slug' => 'unique-name-within-the-set',
* 'name' => 'Name for the UI',
* <value_key> => 'value'
* ),
* )
* ```
*
* This contains the necessary metadata to process them:
*
* - path => where to find the preset within the settings section
* - override => whether a theme preset with the same slug as a default preset
* can override it
* - value_key => the key that represents the value
* - value_func => optionally, instead of value_key, a function to generate
* the value that takes a preset as an argument
* (either value_key or value_func should be present)
* - css_vars => template string to use in generating the CSS Custom Property.
* Example output: "--wp--preset--duotone--blue: <value>" will generate as many CSS Custom Properties as presets defined
* substituting the $slug for the slug's value for each preset value.
* - classes => array containing a structure with the classes to
* generate for the presets, where for each array item
* the key is the class name and the value the property name.
* The "$slug" substring will be replaced by the slug of each preset.
* For example:
* 'classes' => array(
* '.has-$slug-color' => 'color',
* '.has-$slug-background-color' => 'background-color',
* '.has-$slug-border-color' => 'border-color',
* )
* - properties => array of CSS properties to be used by kses to
* validate the content of each preset
* by means of the remove_insecure_properties method.
*/
const PRESETS_METADATA = array(
array(
'path' => array( 'color', 'palette' ),
'override' => false,
'value_key' => 'color',
'css_vars' => '--wp--preset--color--$slug',
'classes' => array(
'.has-$slug-color' => 'color',
'.has-$slug-background-color' => 'background-color',
'.has-$slug-border-color' => 'border-color',
),
'properties' => array( 'color', 'background-color', 'border-color' ),
),
array(
'path' => array( 'color', 'gradients' ),
'override' => false,
'value_key' => 'gradient',
'css_vars' => '--wp--preset--gradient--$slug',
'classes' => array( '.has-$slug-gradient-background' => 'background' ),
'properties' => array( 'background' ),
),
array(
'path' => array( 'color', 'duotone' ),
'override' => true,
'value_func' => 'gutenberg_render_duotone_filter_preset',
'css_vars' => '--wp--preset--duotone--$slug',
'classes' => array(),
'properties' => array( 'filter' ),
),
array(
'path' => array( 'typography', 'fontSizes' ),
'override' => true,
'value_key' => 'size',
'css_vars' => '--wp--preset--font-size--$slug',
'classes' => array( '.has-$slug-font-size' => 'font-size' ),
'properties' => array( 'font-size' ),
),
array(
'path' => array( 'typography', 'fontFamilies' ),
'override' => true,
'value_key' => 'fontFamily',
'css_vars' => '--wp--preset--font-family--$slug',
'classes' => array( '.has-$slug-font-family' => 'font-family' ),
'properties' => array( 'font-family' ),
),
);
/**
* 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' ),
'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--block-gap' => array( 'spacing', 'blockGap' ),
'text-decoration' => array( 'typography', 'textDecoration' ),
'text-transform' => array( 'typography', 'textTransform' ),
'filter' => array( 'filter', 'duotone' ),
);
/**
* Protected style properties.
*
* These style properties are only rendered if a setting enables it
* via a value other than `null`.
*
* Each element maps the style property to the corresponding theme.json
* setting key.
*/
const PROTECTED_PROPERTIES = array(
'spacing.blockGap' => array( 'spacing', 'blockGap' ),
);
/**
* The top-level keys a theme.json can have.
*
* @var string[]
*/
const VALID_TOP_LEVEL_KEYS = array(
'customTemplates',
'settings',
'styles',
'templateParts',
'version',
);
/**
* The valid properties under the settings key.
*
* @var array
*/
const VALID_SETTINGS = array(
'appearanceTools' => null,
'border' => array(
'color' => null,
'radius' => null,
'style' => null,
'width' => null,
),
'color' => array(
'background' => null,
'custom' => null,
'customDuotone' => null,
'customGradient' => null,
'defaultGradients' => null,
'defaultPalette' => null,
'duotone' => null,
'gradients' => null,
'link' => null,
'palette' => null,
'text' => null,
),
'custom' => null,
'layout' => array(
'contentSize' => null,
'wideSize' => null,
),
'spacing' => array(
'blockGap' => null,
'margin' => null,
'padding' => null,
'units' => null,
),
'typography' => array(
'customFontSize' => null,
'dropCap' => null,
'fontFamilies' => null,
'fontSizes' => null,
'fontStyle' => null,
'fontWeight' => null,
'letterSpacing' => null,
'lineHeight' => null,
'textDecoration' => null,
'textTransform' => null,
),
);
/**
* The valid properties under the styles key.
*
* @var array
*/
const VALID_STYLES = array(
'border' => array(
'color' => null,
'radius' => null,
'style' => null,
'width' => null,
),
'color' => array(
'background' => null,
'gradient' => null,
'text' => 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,
),
);
/**
* The valid elements that can be found under styles.
*
* @var string[]
*/
const ELEMENTS = array(
'link' => 'a',
'h1' => 'h1',
'h2' => 'h2',
'h3' => 'h3',
'h4' => 'h4',
'h5' => 'h5',
'h6' => 'h6',
);
/**
* The latest version of the schema in use.
*
* @var int
*/
const LATEST_SCHEMA = 2;
/**
* Constructor.
*
* @param array $theme_json A structure that follows the theme.json schema.
* @param string $origin Optional. What source of data this object represents.
* One of 'default', 'theme', or 'custom'. Default 'theme'.
*/
public function __construct( $theme_json = array(), $origin = 'theme' ) {
if ( ! in_array( $origin, self::VALID_ORIGINS, true ) ) {
$origin = 'theme';
}
$this->theme_json = WP_Theme_JSON_Schema_Gutenberg::migrate( $theme_json );
$valid_block_names = array_keys( self::get_blocks_metadata() );
$valid_element_names = array_keys( self::ELEMENTS );
$theme_json = self::sanitize( $this->theme_json, $valid_block_names, $valid_element_names );
$this->theme_json = self::maybe_opt_in_into_settings( $theme_json );
// Internally, presets are keyed by origin.
$nodes = self::get_setting_nodes( $this->theme_json );
foreach ( $nodes as $node ) {
foreach ( self::PRESETS_METADATA as $preset_metadata ) {
$path = array_merge( $node['path'], $preset_metadata['path'] );
$preset = _wp_array_get( $this->theme_json, $path, null );
if ( null !== $preset ) {
// If the preset is not already keyed by origin.
if ( isset( $preset[0] ) || empty( $preset ) ) {
_wp_array_set( $this->theme_json, $path, array( $origin => $preset ) );
}
}
}
}
}
/**
* Enables some opt-in settings if theme declared support.
*
* @param array $theme_json A theme.json structure to modify.
* @return array The modified theme.json structure.
*/
private static function maybe_opt_in_into_settings( $theme_json ) {
$new_theme_json = $theme_json;
if ( isset( $new_theme_json['settings']['appearanceTools'] ) ) {
self::do_opt_in_into_settings( $new_theme_json['settings'] );
}
if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) {
foreach ( $new_theme_json['settings']['blocks'] as &$block ) {
if ( isset( $block['appearanceTools'] ) ) {
self::do_opt_in_into_settings( $block );
}
}
}
return $new_theme_json;
}
/**
* Enables some settings.
*
* @param array $context The context to which the settings belong.
*/
private static function do_opt_in_into_settings( &$context ) {
$to_opt_in = array(
array( 'border', 'color' ),
array( 'border', 'radius' ),
array( 'border', 'style' ),
array( 'border', 'width' ),
array( 'color', 'link' ),
array( 'spacing', 'blockGap' ),
array( 'spacing', 'margin' ),
array( 'spacing', 'padding' ),
array( 'typography', 'lineHeight' ),
);
foreach ( $to_opt_in as $path ) {
if ( null === _wp_array_get( $context, $path, null ) ) {
_wp_array_set( $context, $path, true );
}
}
unset( $context['appearanceTools'] );
}
/**
* Sanitizes the input according to the schemas.
*
* @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.
*/
private static function sanitize( $input, $valid_block_names, $valid_element_names ) {
$output = array();
if ( ! is_array( $input ) ) {
return $output;
}
$output = array_intersect_key( $input, array_flip( self::VALID_TOP_LEVEL_KEYS ) );
// Build the schema based on valid block & element names.
$schema = array();
$schema_styles_elements = array();
foreach ( $valid_element_names as $element ) {
$schema_styles_elements[ $element ] = self::VALID_STYLES;
}
$schema_styles_blocks = array();
$schema_settings_blocks = array();
foreach ( $valid_block_names as $block ) {
$schema_settings_blocks[ $block ] = self::VALID_SETTINGS;
$schema_styles_blocks[ $block ] = self::VALID_STYLES;
$schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
}
$schema['styles'] = self::VALID_STYLES;
$schema['styles']['blocks'] = $schema_styles_blocks;
$schema['styles']['elements'] = $schema_styles_elements;
$schema['settings'] = self::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 = self::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
if ( empty( $result ) ) {
unset( $output[ $subtree ] );
} else {
$output[ $subtree ] = $result;
}
}
return $output;
}
/**
* 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.
*/
private static function get_blocks_metadata() {
if ( null !== self::$blocks_metadata ) {
return self::$blocks_metadata;
}
self::$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'] )
) {
self::$blocks_metadata[ $block_name ]['selector'] = $block_type->supports['__experimentalSelector'];
} else {
self::$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'] )
) {
self::$blocks_metadata[ $block_name ]['duotone'] = $block_type->supports['color']['__experimentalDuotone'];
}
// 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( ',', self::$blocks_metadata[ $block_name ]['selector'] );
foreach ( self::ELEMENTS as $el_name => $el_selector ) {
$element_selector = array();
foreach ( $block_selectors as $selector ) {
$element_selector[] = $selector . ' ' . $el_selector;
}
self::$blocks_metadata[ $block_name ]['elements'][ $el_name ] = implode( ',', $element_selector );
}
}
return self::$blocks_metadata;
}
/**
* Given a tree, removes the keys that are not present in the schema.
*
* It is recursive and modifies the input in-place.
*
* @param array $tree Input to process.
* @param array $schema Schema to adhere to.
* @return array Returns the modified $tree.
*/
private static function remove_keys_not_in_schema( $tree, $schema ) {
$tree = array_intersect_key( $tree, $schema );
foreach ( $schema as $key => $data ) {
if ( ! isset( $tree[ $key ] ) ) {
continue;
}
if ( is_array( $schema[ $key ] ) && is_array( $tree[ $key ] ) ) {
$tree[ $key ] = self::remove_keys_not_in_schema( $tree[ $key ], $schema[ $key ] );
if ( empty( $tree[ $key ] ) ) {
unset( $tree[ $key ] );
}
} elseif ( is_array( $schema[ $key ] ) && ! is_array( $tree[ $key ] ) ) {
unset( $tree[ $key ] );
}
}
return $tree;
}
/**
* Returns the existing settings for each block.
*
* Example:
*
* {
* 'root': {
* 'color': {
* 'custom': true
* }
* },
* 'core/paragraph': {
* 'spacing': {
* 'customPadding': true
* }
* }
* }
*
* @return array Settings per block.
*/
public function get_settings() {
if ( ! isset( $this->theme_json['settings'] ) ) {
return array();
} else {
return $this->theme_json['settings'];
}
}
/**
* 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 self::VALID_ORIGINS.
* @return string Stylesheet.
*/
public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = self::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 = self::get_blocks_metadata();
$style_nodes = self::get_style_nodes( $this->theme_json, $blocks_metadata );
$setting_nodes = self::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 );
}
if ( in_array( 'presets', $types, true ) ) {
$stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
}
return $stylesheet;
}
/**
* Returns the page templates of the current theme.
*
* @return array
*/
public function get_custom_templates() {
$custom_templates = array();
if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) {
return $custom_templates;
}
foreach ( $this->theme_json['customTemplates'] as $item ) {
if ( isset( $item['name'] ) ) {
$custom_templates[ $item['name'] ] = array(
'title' => isset( $item['title'] ) ? $item['title'] : '',
'postTypes' => isset( $item['postTypes'] ) ? $item['postTypes'] : array( 'page' ),
);
}
}
return $custom_templates;
}
/**
* Returns the template part data of current theme.
*
* @return array
*/
public function get_template_parts() {
$template_parts = array();
if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) {
return $template_parts;
}
foreach ( $this->theme_json['templateParts'] as $item ) {
if ( isset( $item['name'] ) ) {
$template_parts[ $item['name'] ] = array(
'title' => isset( $item['title'] ) ? $item['title'] : '',
'area' => isset( $item['area'] ) ? $item['area'] : '',
);
}
}
return $template_parts;
}
/**
* 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.
*/
private function get_block_classes( $style_nodes ) {
$block_rules = '';
foreach ( $style_nodes as $metadata ) {
if ( null === $metadata['selector'] ) {
continue;
}
$node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
$selector = $metadata['selector'];
$settings = _wp_array_get( $this->theme_json, array( 'settings' ) );
$declarations = self::compute_style_properties( $node, $settings );
// 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 the rules that use the general selector.
$block_rules .= self::to_ruleset( $selector, $declarations );
// 3. Generate the rules that use the duotone selector.
if ( isset( $metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
$selector_duotone = self::scope_selector( $metadata['selector'], $metadata['duotone'] );
$block_rules .= self::to_ruleset( $selector_duotone, $declarations_duotone );
}
if ( self::ROOT_BLOCK_SELECTOR === $selector ) {
$block_rules .= 'body { margin: 0; }';
$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; }';
$has_block_gap_support = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'blockGap' ) ) !== null;
if ( $has_block_gap_support ) {
$block_rules .= '.wp-site-blocks > * { margin-top: 0; margin-bottom: 0; }';
$block_rules .= '.wp-site-blocks > * + * { margin-top: var( --wp--style--block-gap ); }';
}
}
}
return $block_rules;
}
/**
* Creates new rulesets as classes for each preset value such as:
*
* .has-value-color {
* color: value;
* }
*
* .has-value-background-color {
* background-color: value;
* }
*
* .has-value-font-size {
* font-size: value;
* }
*
* .has-value-gradient-background {
* background: value;
* }
*
* p.has-value-gradient-background {
* background: value;
* }
*
* @param array $setting_nodes Nodes with settings.
* @param array $origins List of origins to process presets from.
* @return string The new stylesheet.
*/
private function get_preset_classes( $setting_nodes, $origins ) {
$preset_rules = '';
foreach ( $setting_nodes as $metadata ) {
if ( null === $metadata['selector'] ) {
continue;
}
$selector = $metadata['selector'];
$node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
$preset_rules .= self::compute_preset_classes( $node, $selector, $origins );
}
return $preset_rules;
}
/**
* Converts each styles section into a list of rulesets
* to be appended to the stylesheet.
* These rulesets contain all the css variables (custom variables and preset variables).
*
* 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 {
* --wp--preset--category--slug: value;
* --wp--custom--variable: value;
* }
*
* @param array $nodes Nodes with settings.
* @param array $origins List of origins to process.
* @return string The new stylesheet.
*/
private function get_css_variables( $nodes, $origins ) {
$stylesheet = '';
foreach ( $nodes as $metadata ) {
if ( null === $metadata['selector'] ) {
continue;
}
$selector = $metadata['selector'];
$node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
$declarations = array_merge( self::compute_preset_vars( $node, $origins ), self::compute_theme_vars( $node ) );
$stylesheet .= self::to_ruleset( $selector, $declarations );
}
return $stylesheet;
}
/**
* Given a selector and a declaration list,
* creates the corresponding ruleset.
*
* To help debugging, will add some space
* if SCRIPT_DEBUG is defined and true.
*
* @param string $selector CSS selector.
* @param array $declarations List of declarations.
*
* @return string CSS ruleset.
*/
private static function to_ruleset( $selector, $declarations ) {
if ( empty( $declarations ) ) {
return '';
}
$ruleset = '';
if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
$declaration_block = array_reduce(
$declarations,
function ( $carry, $element ) {
return $carry .= "\t" . $element['name'] . ': ' . $element['value'] . ";\n"; },
''
);
$ruleset .= $selector . " {\n" . $declaration_block . "}\n";
} else {
$declaration_block = array_reduce(
$declarations,
function ( $carry, $element ) {
return $carry .= $element['name'] . ': ' . $element['value'] . ';'; },
''
);
$ruleset .= $selector . '{' . $declaration_block . '}';
}
return $ruleset;
}
/**
* 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".
*
* @param string $selector Original selector.
* @param string $to_append Selector to append.
* @return string
*/
private static function append_to_selector( $selector, $to_append ) {
$new_selectors = array();
$selectors = explode( ',', $selector );
foreach ( $selectors as $sel ) {
$new_selectors[] = $sel . $to_append;
}
return implode( ',', $new_selectors );
}
/**
* Given a settings array, it returns the generated rulesets
* for the preset classes.
*
* @param array $settings Settings to process.
* @param string $selector Selector wrapping the classes.
* @param array $origins List of origins to process.
* @return string The result of processing the presets.
*/
private static function compute_preset_classes( $settings, $selector, $origins ) {
if ( self::ROOT_BLOCK_SELECTOR === $selector ) {
// Classes at the global level do not need any CSS prefixed,
// and we don't want to increase its specificity.
$selector = '';
}
$stylesheet = '';
foreach ( self::PRESETS_METADATA as $preset_metadata ) {
$slugs = self::get_settings_slugs( $settings, $preset_metadata, $origins );
foreach ( $preset_metadata['classes'] as $class => $property ) {
foreach ( $slugs as $slug ) {
$css_var = self::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
$class_name = self::replace_slug_in_string( $class, $slug );
$stylesheet .= self::to_ruleset(
self::append_to_selector( $selector, $class_name ),
array(
array(
'name' => $property,
'value' => 'var(' . $css_var . ') !important',
),
)
);
}
}
}
return $stylesheet;
}
/**
* Function that scopes a selector with another one. This works a bit like
* SCSS nesting except the `&` operator isn't supported.
*
* <code>
* $scope = '.a, .b .c';
* $selector = '> .x, .y';
* $merged = scope_selector( $scope, $selector );
* // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
* </code>
*
* @param string $scope Selector to scope to.
* @param string $selector Original selector.
*
* @return string Scoped selector.
*/
private static function scope_selector( $scope, $selector ) {
$scopes = explode( ',', $scope );
$selectors = explode( ',', $selector );
$selectors_scoped = array();
foreach ( $scopes as $outer ) {
foreach ( $selectors as $inner ) {
$selectors_scoped[] = trim( $outer ) . ' ' . trim( $inner );
}
}
return implode( ', ', $selectors_scoped );
}
/**
* Gets preset values keyed by slugs based on settings and metadata.
*
* <code>
* $settings = array(
* 'typography' => array(
* 'fontFamilies' => array(
* array(
* 'slug' => 'sansSerif',
* 'fontFamily' => '"Helvetica Neue", sans-serif',
* ),
* array(
* 'slug' => 'serif',
* 'colors' => 'Georgia, serif',
* )
* ),
* ),
* );
* $meta = array(
* 'path' => array( 'typography', 'fontFamilies' ),
* 'value_key' => 'fontFamily',
* );
* $values_by_slug = get_settings_values_by_slug();
* // $values_by_slug === array(
* // 'sans-serif' => '"Helvetica Neue", sans-serif',
* // 'serif' => 'Georgia, serif',
* // );
* </code>
*
* @param array $settings Settings to process.
* @param array $preset_metadata One of the PRESETS_METADATA values.
* @param array $origins List of origins to process.
* @return array Array of presets where each key is a slug and each value is the preset value.
*/
private static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
$preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
$result = array();
foreach ( $origins as $origin ) {
if ( ! isset( $preset_per_origin[ $origin ] ) ) {
continue;
}
foreach ( $preset_per_origin[ $origin ] as $preset ) {
$slug = _wp_to_kebab_case( $preset['slug'] );
$value = '';
if ( isset( $preset_metadata['value_key'] ) ) {
$value_key = $preset_metadata['value_key'];
$value = $preset[ $value_key ];
} elseif (