-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
style.js
408 lines (367 loc) · 10.6 KB
/
style.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
/**
* External dependencies
*/
import {
first,
forEach,
get,
has,
isEmpty,
isString,
kebabCase,
map,
omit,
startsWith,
} from 'lodash';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useContext, createPortal } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
import {
getBlockSupport,
hasBlockSupport,
__EXPERIMENTAL_STYLE_PROPERTY as STYLE_PROPERTY,
__EXPERIMENTAL_ELEMENTS as ELEMENTS,
} from '@wordpress/blocks';
import { createHigherOrderComponent, useInstanceId } from '@wordpress/compose';
import { getCSSRules } from '@wordpress/style-engine';
/**
* Internal dependencies
*/
import BlockList from '../components/block-list';
import { BORDER_SUPPORT_KEY, BorderPanel } from './border';
import { COLOR_SUPPORT_KEY, ColorEdit } from './color';
import {
TypographyPanel,
TYPOGRAPHY_SUPPORT_KEY,
TYPOGRAPHY_SUPPORT_KEYS,
} from './typography';
import { SPACING_SUPPORT_KEY, DimensionsPanel } from './dimensions';
import useDisplayBlockControls from '../components/use-display-block-controls';
import { shouldSkipSerialization } from './utils';
const styleSupportKeys = [
...TYPOGRAPHY_SUPPORT_KEYS,
BORDER_SUPPORT_KEY,
COLOR_SUPPORT_KEY,
SPACING_SUPPORT_KEY,
];
const hasStyleSupport = ( blockType ) =>
styleSupportKeys.some( ( key ) => hasBlockSupport( blockType, key ) );
const VARIABLE_REFERENCE_PREFIX = 'var:';
const VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE = '|';
const VARIABLE_PATH_SEPARATOR_TOKEN_STYLE = '--';
function compileStyleValue( uncompiledValue ) {
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;
}
/**
* Returns the inline styles to add depending on the style object
*
* @param {Object} styles Styles configuration.
*
* @return {Object} Flattened CSS variables declaration.
*/
export function getInlineStyles( styles = {} ) {
const ignoredStyles = [ 'spacing.blockGap' ];
const output = {};
Object.keys( STYLE_PROPERTY ).forEach( ( propKey ) => {
const path = STYLE_PROPERTY[ propKey ].value;
const subPaths = STYLE_PROPERTY[ propKey ].properties;
// Ignore styles on elements because they are handled on the server.
if ( has( styles, path ) && 'elements' !== first( path ) ) {
// Checking if style value is a string allows for shorthand css
// option and backwards compatibility for border radius support.
const styleValue = get( styles, path );
if ( ! STYLE_PROPERTY[ propKey ].useEngine ) {
if ( !! subPaths && ! isString( styleValue ) ) {
Object.entries( subPaths ).forEach( ( entry ) => {
const [ name, subPath ] = entry;
const value = get( styleValue, [ subPath ] );
if ( value ) {
output[ name ] = compileStyleValue( value );
}
} );
} else if ( ! ignoredStyles.includes( path.join( '.' ) ) ) {
output[ propKey ] = compileStyleValue(
get( styles, path )
);
}
}
}
} );
// 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( styles );
extraRules.forEach( ( rule ) => {
output[ rule.key ] = rule.value;
} );
return output;
}
function compileElementsStyles( selector, elements = {} ) {
return map( elements, ( styles, element ) => {
const elementStyles = getInlineStyles( styles );
if ( ! isEmpty( elementStyles ) ) {
// The .editor-styles-wrapper selector is required on elements styles. As it is
// added to all other editor styles, not providing it causes reset and global
// styles to override element styles because of higher specificity.
return [
`.editor-styles-wrapper .${ selector } ${ ELEMENTS[ element ] }{`,
...map(
elementStyles,
( value, property ) =>
`\t${ kebabCase( property ) }: ${ value };`
),
'}',
].join( '\n' );
}
return '';
} ).join( '\n' );
}
/**
* Filters registered block settings, extending attributes to include `style` attribute.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function addAttribute( settings ) {
if ( ! hasStyleSupport( settings ) ) {
return settings;
}
// Allow blocks to specify their own attribute definition with default values if needed.
if ( ! settings.attributes.style ) {
Object.assign( settings.attributes, {
style: {
type: 'object',
},
} );
}
return settings;
}
/**
* A dictionary of paths to flag skipping block support serialization as the key,
* with values providing the style paths to be omitted from serialization.
*
* @constant
* @type {Record<string, string[]>}
*/
const skipSerializationPathsEdit = {
[ `${ BORDER_SUPPORT_KEY }.__experimentalSkipSerialization` ]: [ 'border' ],
[ `${ COLOR_SUPPORT_KEY }.__experimentalSkipSerialization` ]: [
COLOR_SUPPORT_KEY,
],
[ `${ TYPOGRAPHY_SUPPORT_KEY }.__experimentalSkipSerialization` ]: [
TYPOGRAPHY_SUPPORT_KEY,
],
[ `${ SPACING_SUPPORT_KEY }.__experimentalSkipSerialization` ]: [
'spacing',
],
};
/**
* A dictionary of paths to flag skipping block support serialization as the key,
* with values providing the style paths to be omitted from serialization.
*
* Extends the Edit skip paths to enable skipping additional paths in just
* the Save component. This allows a block support to be serialized within the
* editor, while using an alternate approach, such as server-side rendering, when
* the support is saved.
*
* @constant
* @type {Record<string, string[]>}
*/
const skipSerializationPathsSave = {
...skipSerializationPathsEdit,
[ `${ SPACING_SUPPORT_KEY }` ]: [ 'spacing.blockGap' ],
};
/**
* A dictionary used to normalize feature names between support flags, style
* object properties and __experimentSkipSerialization configuration arrays.
*
* This allows not having to provide a migration for a support flag and possible
* backwards compatibility bridges, while still achieving consistency between
* the support flag and the skip serialization array.
*
* @constant
* @type {Record<string, string>}
*/
const renamedFeatures = { gradients: 'gradient' };
/**
* Override props assigned to save component to inject the CSS variables definition.
*
* @param {Object} props Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
* @param {?Record<string, string[]>} skipPaths An object of keys and paths to skip serialization.
*
* @return {Object} Filtered props applied to save element.
*/
export function addSaveProps(
props,
blockType,
attributes,
skipPaths = skipSerializationPathsSave
) {
if ( ! hasStyleSupport( blockType ) ) {
return props;
}
let { style } = attributes;
forEach( skipPaths, ( path, indicator ) => {
const skipSerialization = getBlockSupport( blockType, indicator );
if ( skipSerialization === true ) {
style = omit( style, path );
}
if ( Array.isArray( skipSerialization ) ) {
skipSerialization.forEach( ( featureName ) => {
const feature = renamedFeatures[ featureName ] || featureName;
style = omit( style, [ [ ...path, feature ] ] );
} );
}
} );
props.style = {
...getInlineStyles( style ),
...props.style,
};
return props;
}
/**
* Filters registered block settings to extend the block edit wrapper
* to apply the desired styles and classnames properly.
*
* @param {Object} settings Original block settings.
*
* @return {Object}.Filtered block settings.
*/
export function addEditProps( settings ) {
if ( ! hasStyleSupport( settings ) ) {
return settings;
}
const existingGetEditWrapperProps = settings.getEditWrapperProps;
settings.getEditWrapperProps = ( attributes ) => {
let props = {};
if ( existingGetEditWrapperProps ) {
props = existingGetEditWrapperProps( attributes );
}
return addSaveProps(
props,
settings,
attributes,
skipSerializationPathsEdit
);
};
return settings;
}
/**
* Override the default edit UI to include new inspector controls for
* all the custom styles configs.
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
export const withBlockControls = createHigherOrderComponent(
( BlockEdit ) => ( props ) => {
const shouldDisplayControls = useDisplayBlockControls();
return (
<>
{ shouldDisplayControls && (
<>
<ColorEdit { ...props } />
<TypographyPanel { ...props } />
<BorderPanel { ...props } />
<DimensionsPanel { ...props } />
</>
) }
<BlockEdit { ...props } />
</>
);
},
'withToolbarControls'
);
/**
* Override the default block element to include duotone styles.
*
* @param {Function} BlockListBlock Original component
* @return {Function} Wrapped component
*/
const withElementsStyles = createHigherOrderComponent(
( BlockListBlock ) => ( props ) => {
const blockElementsContainerIdentifier = `wp-elements-${ useInstanceId(
BlockListBlock
) }`;
const skipLinkColorSerialization = shouldSkipSerialization(
props.name,
COLOR_SUPPORT_KEY,
'link'
);
// The Elements API only supports link colors for now,
// hence the specific omission of `link` in the elements styles.
// This might need to be refactored or removed if the Elements API
// changes or `link` supports styles beyond `color`.
const elements = skipLinkColorSerialization
? omit( props.attributes.style?.elements, [ 'link' ] )
: props.attributes.style?.elements;
const styles = compileElementsStyles(
blockElementsContainerIdentifier,
elements
);
const element = useContext( BlockList.__unstableElementContext );
return (
<>
{ elements &&
element &&
createPortal(
<style
dangerouslySetInnerHTML={ {
__html: styles,
} }
/>,
element
) }
<BlockListBlock
{ ...props }
className={
elements
? classnames(
props.className,
blockElementsContainerIdentifier
)
: props.className
}
/>
</>
);
}
);
addFilter(
'blocks.registerBlockType',
'core/style/addAttribute',
addAttribute
);
addFilter(
'blocks.getSaveContent.extraProps',
'core/style/addSaveProps',
addSaveProps
);
addFilter(
'blocks.registerBlockType',
'core/style/addEditProps',
addEditProps
);
addFilter(
'editor.BlockEdit',
'core/style/with-block-controls',
withBlockControls
);
addFilter(
'editor.BlockListBlock',
'core/editor/with-elements-styles',
withElementsStyles
);