/
use-global-styles-output.js
392 lines (348 loc) · 9.57 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
/**
* External dependencies
*/
import {
first,
forEach,
get,
isEmpty,
isString,
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';
/**
* Internal dependencies
*/
/**
* Internal dependencies
*/
import { PRESET_METADATA, ROOT_BLOCK_SELECTOR } from './utils';
import { GlobalStylesContext } from './context';
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, cssVarInfix } ) => {
const presetByOrigin = get( blockPresets, path, [] );
[ 'default', 'theme', 'user' ].forEach( ( origin ) => {
if ( presetByOrigin[ origin ] ) {
presetByOrigin[ origin ].forEach( ( value ) => {
declarations.push(
`--wp--preset--${ cssVarInfix }--${ kebabCase(
value.slug
) }: ${ value[ valueKey ] }`
);
} );
}
} );
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', 'user' ].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 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 = {} ) {
return reduce(
STYLE_PROPERTY,
( declarations, { value, properties }, key ) => {
const pathToValue = value;
if ( first( pathToValue ) === 'elements' ) {
return declarations;
}
const styleValue = get( blockStyles, pathToValue );
if ( !! properties && ! isString( styleValue ) ) {
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;
},
[]
);
}
export const getNodesWithStyles = ( tree, blockSelectors ) => {
const nodes = [];
if ( ! tree?.styles ) {
return nodes;
}
const pickStyleKeys = ( treeToPickFrom ) =>
pickBy( treeToPickFrom, ( value, key ) =>
[ 'border', 'color', 'spacing', 'typography' ].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,
} );
}
forEach( node?.elements, ( value, elementName ) => {
if (
!! value &&
!! blockSelectors?.[ blockName ] &&
!! ELEMENTS?.[ elementName ]
) {
nodes.push( {
styles: value,
selector: blockSelectors[ blockName ].selector
.split( ',' )
.map( ( sel ) => sel + ' ' + ELEMENTS[ elementName ] )
.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 ) => {
const nodesWithStyles = getNodesWithStyles( tree, blockSelectors );
const nodesWithSettings = getNodesWithSettings( tree, blockSelectors );
let ruleset =
'.wp-site-blocks > * { margin-top: 0; margin-bottom: 0; }.wp-site-blocks > * + * { margin-top: var( --wp--style--block-gap ); }';
nodesWithStyles.forEach( ( { selector, styles } ) => {
const declarations = getStylesDeclarations( styles );
if ( declarations.length === 0 ) {
return;
}
ruleset = ruleset + `${ selector }{${ declarations.join( ';' ) };}`;
} );
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;
};
const getBlockSelectors = ( blockTypes ) => {
const result = {};
blockTypes.forEach( ( blockType ) => {
const name = blockType.name;
const selector =
blockType?.supports?.__experimentalSelector ??
'.wp-block-' + name.replace( 'core/', '' ).replace( '/', '-' );
result[ name ] = {
name,
selector,
};
} );
return result;
};
export function useGlobalStylesOutput() {
const [ stylesheets, setStylesheets ] = useState( [] );
const [ settings, setSettings ] = useState( {} );
const { merged: mergedConfig } = useContext( GlobalStylesContext );
useEffect( () => {
if ( ! mergedConfig?.styles || ! mergedConfig?.settings ) {
return;
}
const blockSelectors = getBlockSelectors( getBlockTypes() );
const customProperties = toCustomProperties(
mergedConfig,
blockSelectors
);
const globalStyles = toStyles( mergedConfig, blockSelectors );
setStylesheets( [
{
css: customProperties,
isGlobalStyles: true,
__experimentalNoWrapper: true,
},
{
css: globalStyles,
isGlobalStyles: true,
},
] );
setSettings( mergedConfig.settings );
}, [ mergedConfig ] );
return [ stylesheets, settings ];
}