-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
use-global-styles-output.js
1434 lines (1306 loc) · 41.1 KB
/
use-global-styles-output.js
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
/**
* WordPress dependencies
*/
import {
__EXPERIMENTAL_STYLE_PROPERTY as STYLE_PROPERTY,
__EXPERIMENTAL_ELEMENTS as ELEMENTS,
getBlockSupport,
getBlockTypes,
store as blocksStore,
} from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';
import { useContext, useMemo } from '@wordpress/element';
import { getCSSRules } from '@wordpress/style-engine';
import { privateApis as componentsPrivateApis } from '@wordpress/components';
/**
* Internal dependencies
*/
import {
PRESET_METADATA,
ROOT_BLOCK_SELECTOR,
ROOT_CSS_PROPERTIES_SELECTOR,
scopeSelector,
scopeFeatureSelectors,
appendToSelector,
getBlockStyleVariationSelector,
} from './utils';
import { getBlockCSSSelector } from './get-block-css-selector';
import { getTypographyFontSizeValue } from './typography-utils';
import { GlobalStylesContext } from './context';
import { useGlobalSetting } from './hooks';
import { getDuotoneFilter } from '../duotone/utils';
import { getGapCSSValue } from '../../hooks/gap';
import { store as blockEditorStore } from '../../store';
import { LAYOUT_DEFINITIONS } from '../../layouts/definitions';
import { getValueFromObjectPath, setImmutably } from '../../utils/object';
import { unlock } from '../../lock-unlock';
import { setThemeFileUris } from './theme-file-uri-utils';
// 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 = {
__experimentalBorder: 'border',
color: 'color',
spacing: 'spacing',
typography: 'typography',
};
const { kebabCase } = unlock( componentsPrivateApis );
function compileStyleValue( uncompiledValue ) {
const VARIABLE_REFERENCE_PREFIX = 'var:';
const VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE = '|';
const VARIABLE_PATH_SEPARATOR_TOKEN_STYLE = '--';
if ( uncompiledValue?.startsWith?.( VARIABLE_REFERENCE_PREFIX ) ) {
const variable = uncompiledValue
.slice( VARIABLE_REFERENCE_PREFIX.length )
.split( VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE )
.join( VARIABLE_PATH_SEPARATOR_TOKEN_STYLE );
return `var(--wp--${ variable })`;
}
return uncompiledValue;
}
/**
* Transform given preset tree into a set of style declarations.
*
* @param {Object} blockPresets
* @param {Object} mergedSettings Merged theme.json settings.
*
* @return {Array<Object>} An array of style declarations.
*/
function getPresetsDeclarations( blockPresets = {}, mergedSettings ) {
return PRESET_METADATA.reduce(
( declarations, { path, valueKey, valueFunc, cssVarInfix } ) => {
const presetByOrigin = getValueFromObjectPath(
blockPresets,
path,
[]
);
[ 'default', 'theme', 'custom' ].forEach( ( origin ) => {
if ( presetByOrigin[ origin ] ) {
presetByOrigin[ origin ].forEach( ( value ) => {
if ( valueKey && ! valueFunc ) {
declarations.push(
`--wp--preset--${ cssVarInfix }--${ kebabCase(
value.slug
) }: ${ value[ valueKey ] }`
);
} else if (
valueFunc &&
typeof valueFunc === 'function'
) {
declarations.push(
`--wp--preset--${ cssVarInfix }--${ kebabCase(
value.slug
) }: ${ valueFunc( value, mergedSettings ) }`
);
}
} );
}
} );
return declarations;
},
[]
);
}
/**
* Transform given preset tree into a set of preset class declarations.
*
* @param {?string} blockSelector
* @param {Object} blockPresets
* @return {string} CSS declarations for the preset classes.
*/
function getPresetsClasses( blockSelector = '*', blockPresets = {} ) {
return PRESET_METADATA.reduce(
( declarations, { path, cssVarInfix, classes } ) => {
if ( ! classes ) {
return declarations;
}
const presetByOrigin = getValueFromObjectPath(
blockPresets,
path,
[]
);
[ 'default', 'theme', 'custom' ].forEach( ( origin ) => {
if ( presetByOrigin[ origin ] ) {
presetByOrigin[ origin ].forEach( ( { slug } ) => {
classes.forEach( ( { classSuffix, propertyName } ) => {
const classSelectorToUse = `.has-${ kebabCase(
slug
) }-${ classSuffix }`;
const selectorToUse = blockSelector
.split( ',' ) // Selector can be "h1, h2, h3"
.map(
( selector ) =>
`${ selector }${ classSelectorToUse }`
)
.join( ',' );
const value = `var(--wp--preset--${ cssVarInfix }--${ kebabCase(
slug
) })`;
declarations += `${ selectorToUse }{${ propertyName }: ${ value } !important;}`;
} );
} );
}
} );
return declarations;
},
''
);
}
function getPresetsSvgFilters( blockPresets = {} ) {
return PRESET_METADATA.filter(
// Duotone are the only type of filters for now.
( metadata ) => metadata.path.at( -1 ) === 'duotone'
).flatMap( ( metadata ) => {
const presetByOrigin = getValueFromObjectPath(
blockPresets,
metadata.path,
{}
);
return [ 'default', 'theme' ]
.filter( ( origin ) => presetByOrigin[ origin ] )
.flatMap( ( origin ) =>
presetByOrigin[ origin ].map( ( preset ) =>
getDuotoneFilter(
`wp-duotone-${ preset.slug }`,
preset.colors
)
)
)
.join( '' );
} );
}
function flattenTree( input = {}, prefix, token ) {
let result = [];
Object.keys( input ).forEach( ( key ) => {
const newKey = prefix + kebabCase( key.replace( '/', '-' ) );
const newLeaf = input[ key ];
if ( newLeaf instanceof Object ) {
const newPrefix = newKey + token;
result = [ ...result, ...flattenTree( newLeaf, newPrefix, token ) ];
} else {
result.push( `${ newKey }: ${ newLeaf }` );
}
} );
return result;
}
/**
* Gets variation selector string from feature selector.
*
* @param {string} featureSelector The feature selector.
*
* @param {string} styleVariationSelector The style variation selector.
* @return {string} Combined selector string.
*/
function concatFeatureVariationSelectorString(
featureSelector,
styleVariationSelector
) {
const featureSelectors = featureSelector.split( ',' );
const combinedSelectors = [];
featureSelectors.forEach( ( selector ) => {
combinedSelectors.push(
`${ styleVariationSelector.trim() }${ selector.trim() }`
);
} );
return combinedSelectors.join( ', ' );
}
/**
* Generate style declarations for a block's custom feature and subfeature
* selectors.
*
* NOTE: The passed `styles` object will be mutated by this function.
*
* @param {Object} selectors Custom selectors object for a block.
* @param {Object} styles A block's styles object.
*
* @return {Object} Style declarations.
*/
const getFeatureDeclarations = ( selectors, styles ) => {
const declarations = {};
Object.entries( selectors ).forEach( ( [ feature, selector ] ) => {
// We're only processing features/subfeatures that have styles.
if ( feature === 'root' || ! styles?.[ feature ] ) {
return;
}
const isShorthand = typeof selector === 'string';
// If we have a selector object instead of shorthand process it.
if ( ! isShorthand ) {
Object.entries( selector ).forEach(
( [ subfeature, subfeatureSelector ] ) => {
// Don't process root feature selector yet or any
// subfeature that doesn't have a style.
if (
subfeature === 'root' ||
! styles?.[ feature ][ subfeature ]
) {
return;
}
// Create a temporary styles object and build
// declarations for subfeature.
const subfeatureStyles = {
[ feature ]: {
[ subfeature ]: styles[ feature ][ subfeature ],
},
};
const newDeclarations =
getStylesDeclarations( subfeatureStyles );
// Merge new declarations in with any others that
// share the same selector.
declarations[ subfeatureSelector ] = [
...( declarations[ subfeatureSelector ] || [] ),
...newDeclarations,
];
// Remove the subfeature's style now it will be
// included under its own selector not the block's.
delete styles[ feature ][ subfeature ];
}
);
}
// Now subfeatures have been processed and removed, we can
// process root, or shorthand, feature selectors.
if ( isShorthand || selector.root ) {
const featureSelector = isShorthand ? selector : selector.root;
// Create temporary style object and build declarations for feature.
const featureStyles = { [ feature ]: styles[ feature ] };
const newDeclarations = getStylesDeclarations( featureStyles );
// Merge new declarations with any others that share the selector.
declarations[ featureSelector ] = [
...( declarations[ featureSelector ] || [] ),
...newDeclarations,
];
// Remove the feature from the block's styles now as it will be
// included under its own selector not the block's.
delete styles[ feature ];
}
} );
return declarations;
};
/**
* Transform given style tree into a set of style declarations.
*
* @param {Object} blockStyles Block styles.
*
* @param {string} selector The selector these declarations should attach to.
*
* @param {boolean} useRootPaddingAlign Whether to use CSS custom properties in root selector.
*
* @param {Object} tree A theme.json tree containing layout definitions.
*
* @param {boolean} disableRootPadding Whether to force disable the root padding styles.
* @return {Array} An array of style declarations.
*/
export function getStylesDeclarations(
blockStyles = {},
selector = '',
useRootPaddingAlign,
tree = {},
disableRootPadding = false
) {
const isRoot = ROOT_BLOCK_SELECTOR === selector;
const output = Object.entries( STYLE_PROPERTY ).reduce(
(
declarations,
[ key, { value, properties, useEngine, rootOnly } ]
) => {
if ( rootOnly && ! isRoot ) {
return declarations;
}
const pathToValue = value;
if ( pathToValue[ 0 ] === 'elements' || useEngine ) {
return declarations;
}
const styleValue = getValueFromObjectPath(
blockStyles,
pathToValue
);
// Root-level padding styles don't currently support strings with CSS shorthand values.
// This may change: https://github.com/WordPress/gutenberg/issues/40132.
if (
key === '--wp--style--root--padding' &&
( typeof styleValue === 'string' || ! useRootPaddingAlign )
) {
return declarations;
}
if ( properties && typeof styleValue !== 'string' ) {
Object.entries( properties ).forEach( ( entry ) => {
const [ name, prop ] = entry;
if (
! getValueFromObjectPath( styleValue, [ prop ], false )
) {
// Do not create a declaration
// for sub-properties that don't have any value.
return;
}
const cssProperty = name.startsWith( '--' )
? name
: kebabCase( name );
declarations.push(
`${ cssProperty }: ${ compileStyleValue(
getValueFromObjectPath( styleValue, [ prop ] )
) }`
);
} );
} else if (
getValueFromObjectPath( blockStyles, pathToValue, false )
) {
const cssProperty = key.startsWith( '--' )
? key
: kebabCase( key );
declarations.push(
`${ cssProperty }: ${ compileStyleValue(
getValueFromObjectPath( blockStyles, pathToValue )
) }`
);
}
return declarations;
},
[]
);
// The goal is to move everything to server side generated engine styles
// This is temporary as we absorb more and more styles into the engine.
const extraRules = getCSSRules( blockStyles );
extraRules.forEach( ( rule ) => {
// Don't output padding properties if padding variables are set or if we're not editing a full template.
if (
isRoot &&
( useRootPaddingAlign || disableRootPadding ) &&
rule.key.startsWith( 'padding' )
) {
return;
}
const cssProperty = rule.key.startsWith( '--' )
? rule.key
: kebabCase( rule.key );
let ruleValue = rule.value;
if ( typeof ruleValue !== 'string' && ruleValue?.ref ) {
const refPath = ruleValue.ref.split( '.' );
ruleValue = compileStyleValue(
getValueFromObjectPath( tree, refPath )
);
// Presence of another ref indicates a reference to another dynamic value.
// Pointing to another dynamic value is not supported.
if ( ! ruleValue || ruleValue?.ref ) {
return;
}
}
// Calculate fluid typography rules where available.
if ( cssProperty === 'font-size' ) {
/*
* getTypographyFontSizeValue() will check
* if fluid typography has been activated and also
* whether the incoming value can be converted to a fluid value.
* Values that already have a "clamp()" function will not pass the test,
* and therefore the original $value will be returned.
*/
ruleValue = getTypographyFontSizeValue(
{ size: ruleValue },
tree?.settings
);
}
// For aspect ratio to work, other dimensions rules (and Cover block defaults) must be unset.
// This ensures that a fixed height does not override the aspect ratio.
if ( cssProperty === 'aspect-ratio' ) {
output.push( 'min-height: unset' );
}
output.push( `${ cssProperty }: ${ ruleValue }` );
} );
return output;
}
/**
* Get generated CSS for layout styles by looking up layout definitions provided
* in theme.json, and outputting common layout styles, and specific blockGap values.
*
* @param {Object} props
* @param {Object} props.layoutDefinitions Layout definitions, keyed by layout type.
* @param {Object} props.style A style object containing spacing values.
* @param {string} props.selector Selector used to group together layout styling rules.
* @param {boolean} props.hasBlockGapSupport Whether or not the theme opts-in to blockGap support.
* @param {boolean} props.hasFallbackGapSupport Whether or not the theme allows fallback gap styles.
* @param {?string} props.fallbackGapValue An optional fallback gap value if no real gap value is available.
* @return {string} Generated CSS rules for the layout styles.
*/
export function getLayoutStyles( {
layoutDefinitions = LAYOUT_DEFINITIONS,
style,
selector,
hasBlockGapSupport,
hasFallbackGapSupport,
fallbackGapValue,
} ) {
let ruleset = '';
let gapValue = hasBlockGapSupport
? getGapCSSValue( style?.spacing?.blockGap )
: '';
// Ensure a fallback gap value for the root layout definitions,
// and use a fallback value if one is provided for the current block.
if ( hasFallbackGapSupport ) {
if ( selector === ROOT_BLOCK_SELECTOR ) {
gapValue = ! gapValue ? '0.5em' : gapValue;
} else if ( ! hasBlockGapSupport && fallbackGapValue ) {
gapValue = fallbackGapValue;
}
}
if ( gapValue && layoutDefinitions ) {
Object.values( layoutDefinitions ).forEach(
( { className, name, spacingStyles } ) => {
// Allow outputting fallback gap styles for flex layout type when block gap support isn't available.
if (
! hasBlockGapSupport &&
'flex' !== name &&
'grid' !== name
) {
return;
}
if ( spacingStyles?.length ) {
spacingStyles.forEach( ( spacingStyle ) => {
const declarations = [];
if ( spacingStyle.rules ) {
Object.entries( spacingStyle.rules ).forEach(
( [ cssProperty, cssValue ] ) => {
declarations.push(
`${ cssProperty }: ${
cssValue ? cssValue : gapValue
}`
);
}
);
}
if ( declarations.length ) {
let combinedSelector = '';
if ( ! hasBlockGapSupport ) {
// For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles.
combinedSelector =
selector === ROOT_BLOCK_SELECTOR
? `:where(.${ className }${
spacingStyle?.selector || ''
})`
: `:where(${ selector }.${ className }${
spacingStyle?.selector || ''
})`;
} else {
combinedSelector =
selector === ROOT_BLOCK_SELECTOR
? `.${ className }${
spacingStyle?.selector || ''
}`
: `${ selector }-${ className }${
spacingStyle?.selector || ''
}`;
}
ruleset += `${ combinedSelector } { ${ declarations.join(
'; '
) }; }`;
}
} );
}
}
);
// For backwards compatibility, ensure the legacy block gap CSS variable is still available.
if ( selector === ROOT_BLOCK_SELECTOR && hasBlockGapSupport ) {
ruleset += `${ ROOT_CSS_PROPERTIES_SELECTOR } { --wp--style--block-gap: ${ gapValue }; }`;
}
}
// Output base styles
if ( selector === ROOT_BLOCK_SELECTOR && layoutDefinitions ) {
const validDisplayModes = [ 'block', 'flex', 'grid' ];
Object.values( layoutDefinitions ).forEach(
( { className, displayMode, baseStyles } ) => {
if (
displayMode &&
validDisplayModes.includes( displayMode )
) {
ruleset += `${ selector } .${ className } { display:${ displayMode }; }`;
}
if ( baseStyles?.length ) {
baseStyles.forEach( ( baseStyle ) => {
const declarations = [];
if ( baseStyle.rules ) {
Object.entries( baseStyle.rules ).forEach(
( [ cssProperty, cssValue ] ) => {
declarations.push(
`${ cssProperty }: ${ cssValue }`
);
}
);
}
if ( declarations.length ) {
const combinedSelector = `.${ className }${
baseStyle?.selector || ''
}`;
ruleset += `${ combinedSelector } { ${ declarations.join(
'; '
) }; }`;
}
} );
}
}
);
}
return ruleset;
}
const STYLE_KEYS = [
'border',
'color',
'dimensions',
'spacing',
'typography',
'filter',
'outline',
'shadow',
'background',
];
function pickStyleKeys( treeToPickFrom ) {
if ( ! treeToPickFrom ) {
return {};
}
const entries = Object.entries( treeToPickFrom );
const pickedEntries = entries.filter( ( [ key ] ) =>
STYLE_KEYS.includes( key )
);
// clone the style objects so that `getFeatureDeclarations` can remove consumed keys from it
const clonedEntries = pickedEntries.map( ( [ key, style ] ) => [
key,
JSON.parse( JSON.stringify( style ) ),
] );
return Object.fromEntries( clonedEntries );
}
export const getNodesWithStyles = ( tree, blockSelectors ) => {
const nodes = [];
if ( ! tree?.styles ) {
return nodes;
}
// Top-level.
const styles = pickStyleKeys( tree.styles );
if ( styles ) {
nodes.push( {
styles,
selector: ROOT_BLOCK_SELECTOR,
} );
}
Object.entries( ELEMENTS ).forEach( ( [ name, selector ] ) => {
if ( tree.styles?.elements?.[ name ] ) {
nodes.push( {
styles: tree.styles?.elements?.[ name ],
selector,
} );
}
} );
// Iterate over blocks: they can have styles & elements.
Object.entries( tree.styles?.blocks ?? {} ).forEach(
( [ blockName, node ] ) => {
const blockStyles = pickStyleKeys( node );
if ( node?.variations ) {
const variations = {};
Object.entries( node.variations ).forEach(
( [ variationName, variation ] ) => {
variations[ variationName ] =
pickStyleKeys( variation );
if ( variation?.css ) {
variations[ variationName ].css = variation.css;
}
const variationSelector =
blockSelectors[ blockName ]
.styleVariationSelectors?.[ variationName ];
// Process the variation's inner element styles.
// This comes before the inner block styles so the
// element styles within the block type styles take
// precedence over these.
Object.entries( variation?.elements ?? {} ).forEach(
( [ element, elementStyles ] ) => {
if ( elementStyles && ELEMENTS[ element ] ) {
nodes.push( {
styles: elementStyles,
selector: scopeSelector(
variationSelector,
ELEMENTS[ element ]
),
} );
}
}
);
// Process the variations inner block type styles.
Object.entries( variation?.blocks ?? {} ).forEach(
( [
variationBlockName,
variationBlockStyles,
] ) => {
const variationBlockSelector = scopeSelector(
variationSelector,
blockSelectors[ variationBlockName ]
.selector
);
const variationDuotoneSelector = scopeSelector(
variationSelector,
blockSelectors[ variationBlockName ]
.duotoneSelector
);
const variationFeatureSelectors =
scopeFeatureSelectors(
variationSelector,
blockSelectors[ variationBlockName ]
.featureSelectors
);
const variationBlockStyleNodes =
pickStyleKeys( variationBlockStyles );
if ( variationBlockStyles?.css ) {
variationBlockStyleNodes.css =
variationBlockStyles.css;
}
nodes.push( {
selector: variationBlockSelector,
duotoneSelector: variationDuotoneSelector,
featureSelectors: variationFeatureSelectors,
fallbackGapValue:
blockSelectors[ variationBlockName ]
.fallbackGapValue,
hasLayoutSupport:
blockSelectors[ variationBlockName ]
.hasLayoutSupport,
styles: variationBlockStyleNodes,
} );
// Process element styles for the inner blocks
// of the variation.
Object.entries(
variationBlockStyles.elements ?? {}
).forEach(
( [
variationBlockElement,
variationBlockElementStyles,
] ) => {
if (
variationBlockElementStyles &&
ELEMENTS[ variationBlockElement ]
) {
nodes.push( {
styles: variationBlockElementStyles,
selector: scopeSelector(
variationBlockSelector,
ELEMENTS[
variationBlockElement
]
),
} );
}
}
);
}
);
}
);
blockStyles.variations = variations;
}
if ( blockSelectors?.[ blockName ]?.selector ) {
nodes.push( {
duotoneSelector:
blockSelectors[ blockName ].duotoneSelector,
fallbackGapValue:
blockSelectors[ blockName ].fallbackGapValue,
hasLayoutSupport:
blockSelectors[ blockName ].hasLayoutSupport,
selector: blockSelectors[ blockName ].selector,
styles: blockStyles,
featureSelectors:
blockSelectors[ blockName ].featureSelectors,
styleVariationSelectors:
blockSelectors[ blockName ].styleVariationSelectors,
} );
}
Object.entries( node?.elements ?? {} ).forEach(
( [ elementName, value ] ) => {
if (
value &&
blockSelectors?.[ blockName ] &&
ELEMENTS[ elementName ]
) {
nodes.push( {
styles: value,
selector: blockSelectors[ blockName ]?.selector
.split( ',' )
.map( ( sel ) => {
const elementSelectors =
ELEMENTS[ elementName ].split( ',' );
return elementSelectors.map(
( elementSelector ) =>
sel + ' ' + elementSelector
);
} )
.join( ',' ),
} );
}
}
);
}
);
return nodes;
};
export const getNodesWithSettings = ( tree, blockSelectors ) => {
const nodes = [];
if ( ! tree?.settings ) {
return nodes;
}
const pickPresets = ( treeToPickFrom ) => {
let presets = {};
PRESET_METADATA.forEach( ( { path } ) => {
const value = getValueFromObjectPath( treeToPickFrom, path, false );
if ( value !== false ) {
presets = setImmutably( presets, path, value );
}
} );
return presets;
};
// Top-level.
const presets = pickPresets( tree.settings );
const custom = tree.settings?.custom;
if ( Object.keys( presets ).length > 0 || custom ) {
nodes.push( {
presets,
custom,
selector: ROOT_CSS_PROPERTIES_SELECTOR,
} );
}
// Blocks.
Object.entries( tree.settings?.blocks ?? {} ).forEach(
( [ blockName, node ] ) => {
const blockPresets = pickPresets( node );
const blockCustom = node.custom;
if ( Object.keys( blockPresets ).length > 0 || blockCustom ) {
nodes.push( {
presets: blockPresets,
custom: blockCustom,
selector: blockSelectors[ blockName ]?.selector,
} );
}
}
);
return nodes;
};
export const toCustomProperties = ( tree, blockSelectors ) => {
const settings = getNodesWithSettings( tree, blockSelectors );
let ruleset = '';
settings.forEach( ( { presets, custom, selector } ) => {
const declarations = getPresetsDeclarations( presets, tree?.settings );
const customProps = flattenTree( custom, '--wp--custom--', '--' );
if ( customProps.length > 0 ) {
declarations.push( ...customProps );
}
if ( declarations.length > 0 ) {
ruleset += `${ selector }{${ declarations.join( ';' ) };}`;
}
} );
return ruleset;
};
export const toStyles = (
tree,
blockSelectors,
hasBlockGapSupport,
hasFallbackGapSupport,
disableLayoutStyles = false,
disableRootPadding = false,
styleOptions = undefined
) => {
// These allow opting out of certain sets of styles.
const options = {
blockGap: true,
blockStyles: true,
layoutStyles: true,
marginReset: true,
presets: true,
rootPadding: true,
variationStyles: false,
...styleOptions,
};
const nodesWithStyles = getNodesWithStyles( tree, blockSelectors );
const nodesWithSettings = getNodesWithSettings( tree, blockSelectors );
const useRootPaddingAlign = tree?.settings?.useRootPaddingAwareAlignments;
const { contentSize, wideSize } = tree?.settings?.layout || {};
const hasBodyStyles =
options.marginReset || options.rootPadding || options.layoutStyles;
let ruleset = '';
if ( options.presets && ( contentSize || wideSize ) ) {
ruleset += `${ ROOT_CSS_PROPERTIES_SELECTOR } {`;
ruleset = contentSize
? ruleset + ` --wp--style--global--content-size: ${ contentSize };`
: ruleset;
ruleset = wideSize
? ruleset + ` --wp--style--global--wide-size: ${ wideSize };`
: ruleset;
ruleset += '}';
}
if ( hasBodyStyles ) {
/*
* Reset default browser margin on the body element.
* This is set on the body 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.
*/
ruleset += ':where(body) {margin: 0;';
// Root padding styles should be output for full templates, patterns and template parts.
if ( options.rootPadding && useRootPaddingAlign ) {
/*
* These rules reproduce the ones from https://github.com/WordPress/gutenberg/blob/79103f124925d1f457f627e154f52a56228ed5ad/lib/class-wp-theme-json-gutenberg.php#L2508
* almost exactly, but for the selectors that target block wrappers in the front end. This code only runs in the editor, so it doesn't need those selectors.
*/
ruleset += `padding-right: 0; padding-left: 0; padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom) }
.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }
.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }
.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull, .alignwide)) { padding-right: 0; padding-left: 0; }
.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull, .alignwide)) > .alignfull { margin-left: 0; margin-right: 0;
`;
}
ruleset += '}';
}
if ( options.blockStyles ) {
nodesWithStyles.forEach(
( {
selector,
duotoneSelector,
styles,
fallbackGapValue,
hasLayoutSupport,
featureSelectors,
styleVariationSelectors,
} ) => {
// Process styles for block support features with custom feature level
// CSS selectors set.
if ( featureSelectors ) {
const featureDeclarations = getFeatureDeclarations(
featureSelectors,
styles
);
Object.entries( featureDeclarations ).forEach(
( [ cssSelector, declarations ] ) => {
if ( declarations.length ) {
const rules = declarations.join( ';' );
ruleset += `:root :where(${ cssSelector }){${ rules };}`;
}
}
);
}
// Process duotone styles.
if ( duotoneSelector ) {
const duotoneStyles = {};
if ( styles?.filter ) {
duotoneStyles.filter = styles.filter;
delete styles.filter;
}
const duotoneDeclarations =
getStylesDeclarations( duotoneStyles );
if ( duotoneDeclarations.length ) {
ruleset += `${ duotoneSelector }{${ duotoneDeclarations.join(
';'
) };}`;
}
}
// Process blockGap and layout styles.
if (
! disableLayoutStyles &&
( ROOT_BLOCK_SELECTOR === selector || hasLayoutSupport )
) {
ruleset += getLayoutStyles( {
style: styles,
selector,
hasBlockGapSupport,
hasFallbackGapSupport,
fallbackGapValue,
} );
}
// Process the remaining block styles (they use either normal block class or __experimentalSelector).
const styleDeclarations = getStylesDeclarations(
styles,
selector,
useRootPaddingAlign,
tree,
disableRootPadding