-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathuse-global-styles-output.js
537 lines (480 loc) · 14.2 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
/**
* External dependencies
*/
import {
first,
forEach,
get,
isEmpty,
kebabCase,
pickBy,
reduce,
set,
startsWith,
} from 'lodash';
/**
* WordPress dependencies
*/
import {
__EXPERIMENTAL_STYLE_PROPERTY as STYLE_PROPERTY,
__EXPERIMENTAL_ELEMENTS as ELEMENTS,
getBlockTypes,
} from '@wordpress/blocks';
import { useEffect, useState, useContext } from '@wordpress/element';
import { getCSSRules } from '@wordpress/style-engine';
import { __unstablePresetDuotoneFilter as PresetDuotoneFilter } from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import { PRESET_METADATA, ROOT_BLOCK_SELECTOR } from './utils';
import { GlobalStylesContext } from './context';
import { useSetting } from './hooks';
function compileStyleValue( uncompiledValue ) {
const VARIABLE_REFERENCE_PREFIX = 'var:';
const VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE = '|';
const VARIABLE_PATH_SEPARATOR_TOKEN_STYLE = '--';
if ( startsWith( uncompiledValue, 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
*
* @return {Array} An array of style declarations.
*/
function getPresetsDeclarations( blockPresets = {} ) {
return reduce(
PRESET_METADATA,
( declarations, { path, valueKey, valueFunc, cssVarInfix } ) => {
const presetByOrigin = get( blockPresets, path, [] );
[ 'default', 'theme', 'custom' ].forEach( ( origin ) => {
if ( presetByOrigin[ origin ] ) {
presetByOrigin[ origin ].forEach( ( value ) => {
if ( valueKey ) {
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 ) }`
);
}
} );
}
} );
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 reduce(
PRESET_METADATA,
( declarations, { path, cssVarInfix, classes } ) => {
if ( ! classes ) {
return declarations;
}
const presetByOrigin = get( 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 = get( blockPresets, metadata.path, {} );
return [ 'default', 'theme' ]
.filter( ( origin ) => presetByOrigin[ origin ] )
.flatMap( ( origin ) =>
presetByOrigin[ origin ].map( ( preset ) => (
<PresetDuotoneFilter
preset={ preset }
key={ preset.slug }
/>
) )
);
} );
}
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;
}
/**
* Transform given style tree into a set of style declarations.
*
* @param {Object} blockStyles Block styles.
*
* @return {Array} An array of style declarations.
*/
function getStylesDeclarations( blockStyles = {} ) {
const output = reduce(
STYLE_PROPERTY,
( declarations, { value, properties, useEngine }, key ) => {
const pathToValue = value;
if ( first( pathToValue ) === 'elements' || useEngine ) {
return declarations;
}
const styleValue = get( blockStyles, pathToValue );
if ( !! properties && typeof styleValue !== 'string' ) {
Object.entries( properties ).forEach( ( entry ) => {
const [ name, prop ] = entry;
if ( ! get( styleValue, [ prop ], false ) ) {
// Do not create a declaration
// for sub-properties that don't have any value.
return;
}
const cssProperty = kebabCase( name );
declarations.push(
`${ cssProperty }: ${ compileStyleValue(
get( styleValue, [ prop ] )
) }`
);
} );
} else if ( get( blockStyles, pathToValue, false ) ) {
const cssProperty = key.startsWith( '--' )
? key
: kebabCase( key );
declarations.push(
`${ cssProperty }: ${ compileStyleValue(
get( 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 ) => {
const cssProperty = rule.key.startsWith( '--' )
? rule.key
: kebabCase( rule.key );
output.push( `${ cssProperty }: ${ compileStyleValue( rule.value ) }` );
} );
return output;
}
export const getNodesWithStyles = ( tree, blockSelectors ) => {
const nodes = [];
if ( ! tree?.styles ) {
return nodes;
}
const pickStyleKeys = ( treeToPickFrom ) =>
pickBy( treeToPickFrom, ( value, key ) =>
[ 'border', 'color', 'spacing', 'typography', 'filter' ].includes(
key
)
);
// Top-level.
const styles = pickStyleKeys( tree.styles );
if ( !! styles ) {
nodes.push( {
styles,
selector: ROOT_BLOCK_SELECTOR,
} );
}
forEach( tree.styles?.elements, ( value, key ) => {
if ( !! value && !! ELEMENTS[ key ] ) {
nodes.push( {
styles: value,
selector: ELEMENTS[ key ],
} );
}
} );
// Iterate over blocks: they can have styles & elements.
forEach( tree.styles?.blocks, ( node, blockName ) => {
const blockStyles = pickStyleKeys( node );
if ( !! blockStyles && !! blockSelectors?.[ blockName ]?.selector ) {
nodes.push( {
styles: blockStyles,
selector: blockSelectors[ blockName ].selector,
duotoneSelector: blockSelectors[ blockName ].duotoneSelector,
} );
}
forEach( node?.elements, ( value, elementName ) => {
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 ) => {
const presets = {};
PRESET_METADATA.forEach( ( { path } ) => {
const value = get( treeToPickFrom, path, false );
if ( value !== false ) {
set( presets, path, value );
}
} );
return presets;
};
// Top-level.
const presets = pickPresets( tree.settings );
const custom = tree.settings?.custom;
if ( ! isEmpty( presets ) || !! custom ) {
nodes.push( {
presets,
custom,
selector: ROOT_BLOCK_SELECTOR,
} );
}
// Blocks.
forEach( tree.settings?.blocks, ( node, blockName ) => {
const blockPresets = pickPresets( node );
const blockCustom = node.custom;
if ( ! isEmpty( blockPresets ) || !! 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 );
const customProps = flattenTree( custom, '--wp--custom--', '--' );
if ( customProps.length > 0 ) {
declarations.push( ...customProps );
}
if ( declarations.length > 0 ) {
ruleset = ruleset + `${ selector }{${ declarations.join( ';' ) };}`;
}
} );
return ruleset;
};
export const toStyles = ( tree, blockSelectors, hasBlockGapSupport ) => {
const nodesWithStyles = getNodesWithStyles( tree, blockSelectors );
const nodesWithSettings = getNodesWithSettings( tree, blockSelectors );
/*
* 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.
*/
let ruleset = 'body {margin: 0;}';
nodesWithStyles.forEach( ( { selector, duotoneSelector, styles } ) => {
const duotoneStyles = {};
if ( styles?.filter ) {
duotoneStyles.filter = styles.filter;
delete styles.filter;
}
// Process duotone styles (they use color.__experimentalDuotone selector).
if ( duotoneSelector ) {
const duotoneDeclarations = getStylesDeclarations( duotoneStyles );
if ( duotoneDeclarations.length === 0 ) {
return;
}
ruleset =
ruleset +
`${ duotoneSelector }{${ duotoneDeclarations.join( ';' ) };}`;
}
// Process the remaning block styles (they use either normal block class or __experimentalSelector).
const declarations = getStylesDeclarations( styles );
if ( declarations?.length ) {
ruleset = ruleset + `${ selector }{${ declarations.join( ';' ) };}`;
}
// Check for pseudo selector in `styles` and handle separately.
const psuedoSelectorStyles = Object.entries( styles ).filter(
( [ key ] ) => key.startsWith( ':' )
);
if ( psuedoSelectorStyles?.length ) {
psuedoSelectorStyles.forEach( ( [ pseudoKey, pseudoRule ] ) => {
const pseudoDeclarations = getStylesDeclarations( pseudoRule );
if ( ! pseudoDeclarations?.length ) {
return;
}
// `selector` maybe provided in a form
// where block level selectors have sub element
// selectors appended to them as a comma seperated
// string.
// e.g. `h1 a,h2 a,h3 a,h4 a,h5 a,h6 a`;
// Split and append pseudo selector to create
// the proper rules to target the elements.
const _selector = selector
.split( ',' )
.map( ( sel ) => sel + pseudoKey )
.join( ',' );
const psuedoRule = `${ _selector }{${ pseudoDeclarations.join(
';'
) };}`;
ruleset = ruleset + psuedoRule;
} );
}
} );
/* Add alignment / layout styles */
ruleset =
ruleset +
'.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
ruleset =
ruleset +
'.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
ruleset =
ruleset +
'.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
if ( hasBlockGapSupport ) {
ruleset =
ruleset +
'.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }';
ruleset =
ruleset +
'.wp-site-blocks > * + * { margin-block-start: var( --wp--style--block-gap ); }';
}
nodesWithSettings.forEach( ( { selector, presets } ) => {
if ( ROOT_BLOCK_SELECTOR === selector ) {
// Do not add extra specificity for top-level classes.
selector = '';
}
const classes = getPresetsClasses( selector, presets );
if ( ! isEmpty( classes ) ) {
ruleset = ruleset + classes;
}
} );
return ruleset;
};
export function toSvgFilters( tree, blockSelectors ) {
const nodesWithSettings = getNodesWithSettings( tree, blockSelectors );
return nodesWithSettings.flatMap( ( { presets } ) => {
return getPresetsSvgFilters( presets );
} );
}
const getBlockSelectors = ( blockTypes ) => {
const result = {};
blockTypes.forEach( ( blockType ) => {
const name = blockType.name;
const selector =
blockType?.supports?.__experimentalSelector ??
'.wp-block-' + name.replace( 'core/', '' ).replace( '/', '-' );
const duotoneSelector =
blockType?.supports?.color?.__experimentalDuotone ?? null;
result[ name ] = {
name,
selector,
duotoneSelector,
};
} );
return result;
};
export function useGlobalStylesOutput() {
const [ stylesheets, setStylesheets ] = useState( [] );
const [ settings, setSettings ] = useState( {} );
const [ svgFilters, setSvgFilters ] = useState( {} );
const { merged: mergedConfig } = useContext( GlobalStylesContext );
const [ blockGap ] = useSetting( 'spacing.blockGap' );
const hasBlockGapSupport = blockGap !== null;
useEffect( () => {
if ( ! mergedConfig?.styles || ! mergedConfig?.settings ) {
return;
}
const blockSelectors = getBlockSelectors( getBlockTypes() );
const customProperties = toCustomProperties(
mergedConfig,
blockSelectors
);
const globalStyles = toStyles(
mergedConfig,
blockSelectors,
hasBlockGapSupport
);
const filters = toSvgFilters( mergedConfig, blockSelectors );
setStylesheets( [
{
css: customProperties,
isGlobalStyles: true,
},
{
css: globalStyles,
isGlobalStyles: true,
},
] );
setSettings( mergedConfig.settings );
setSvgFilters( filters );
}, [ mergedConfig ] );
return [ stylesheets, settings, svgFilters, hasBlockGapSupport ];
}