-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathduotone.js
407 lines (361 loc) · 11.3 KB
/
duotone.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
/**
* External dependencies
*/
import classnames from 'classnames';
import { extend } from 'colord';
import namesPlugin from 'colord/plugins/names';
/**
* WordPress dependencies
*/
import {
getBlockSupport,
getBlockType,
hasBlockSupport,
} from '@wordpress/blocks';
import { createHigherOrderComponent, useInstanceId } from '@wordpress/compose';
import { addFilter } from '@wordpress/hooks';
import { useMemo, useEffect } from '@wordpress/element';
import { useDispatch } from '@wordpress/data';
/**
* Internal dependencies
*/
import {
BlockControls,
InspectorControls,
__experimentalDuotoneControl as DuotoneControl,
useSetting,
} from '../components';
import {
getDuotoneFilter,
getDuotoneStylesheet,
getDuotoneUnsetStylesheet,
} from '../components/duotone/utils';
import { getBlockCSSSelector } from '../components/global-styles/get-block-css-selector';
import { scopeSelector } from '../components/global-styles/utils';
import { useBlockSettings } from './utils';
import { default as StylesFiltersPanel } from '../components/global-styles/filters-panel';
import { useBlockEditingMode } from '../components/block-editing-mode';
import { store as blockEditorStore } from '../store';
import { unlock } from '../lock-unlock';
const EMPTY_ARRAY = [];
extend( [ namesPlugin ] );
function useMultiOriginPresets( { presetSetting, defaultSetting } ) {
const disableDefault = ! useSetting( defaultSetting );
const userPresets =
useSetting( `${ presetSetting }.custom` ) || EMPTY_ARRAY;
const themePresets =
useSetting( `${ presetSetting }.theme` ) || EMPTY_ARRAY;
const defaultPresets =
useSetting( `${ presetSetting }.default` ) || EMPTY_ARRAY;
return useMemo(
() => [
...userPresets,
...themePresets,
...( disableDefault ? EMPTY_ARRAY : defaultPresets ),
],
[ disableDefault, userPresets, themePresets, defaultPresets ]
);
}
export function getColorsFromDuotonePreset( duotone, duotonePalette ) {
if ( ! duotone ) {
return;
}
const preset = duotonePalette?.find( ( { slug } ) => {
return duotone === `var:preset|duotone|${ slug }`;
} );
return preset ? preset.colors : undefined;
}
export function getDuotonePresetFromColors( colors, duotonePalette ) {
if ( ! colors || ! Array.isArray( colors ) ) {
return;
}
const preset = duotonePalette?.find( ( duotonePreset ) => {
return duotonePreset?.colors?.every(
( val, index ) => val === colors[ index ]
);
} );
return preset ? `var:preset|duotone|${ preset.slug }` : undefined;
}
function DuotonePanel( { attributes, setAttributes, name } ) {
const style = attributes?.style;
const duotoneStyle = style?.color?.duotone;
const settings = useBlockSettings( name );
const duotonePalette = useMultiOriginPresets( {
presetSetting: 'color.duotone',
defaultSetting: 'color.defaultDuotone',
} );
const colorPalette = useMultiOriginPresets( {
presetSetting: 'color.palette',
defaultSetting: 'color.defaultPalette',
} );
const disableCustomColors = ! useSetting( 'color.custom' );
const disableCustomDuotone =
! useSetting( 'color.customDuotone' ) ||
( colorPalette?.length === 0 && disableCustomColors );
if ( duotonePalette?.length === 0 && disableCustomDuotone ) {
return null;
}
const duotonePresetOrColors = ! Array.isArray( duotoneStyle )
? getColorsFromDuotonePreset( duotoneStyle, duotonePalette )
: duotoneStyle;
return (
<>
<InspectorControls group="filter">
<StylesFiltersPanel
value={ { filter: { duotone: duotonePresetOrColors } } }
onChange={ ( newDuotone ) => {
const newStyle = {
...style,
color: {
...newDuotone?.filter,
},
};
setAttributes( { style: newStyle } );
} }
settings={ settings }
/>
</InspectorControls>
<BlockControls group="block" __experimentalShareWithChildBlocks>
<DuotoneControl
duotonePalette={ duotonePalette }
colorPalette={ colorPalette }
disableCustomDuotone={ disableCustomDuotone }
disableCustomColors={ disableCustomColors }
value={ duotonePresetOrColors }
onChange={ ( newDuotone ) => {
const maybePreset = getDuotonePresetFromColors(
newDuotone,
duotonePalette
);
const newStyle = {
...style,
color: {
...style?.color,
duotone: maybePreset ?? newDuotone, // use preset or fallback to custom colors.
},
};
setAttributes( { style: newStyle } );
} }
settings={ settings }
/>
</BlockControls>
</>
);
}
/**
* Filters registered block settings, extending attributes to include
* the `duotone` attribute.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function addDuotoneAttributes( settings ) {
// Previous `color.__experimentalDuotone` support flag is migrated via
// block_type_metadata_settings filter in `lib/block-supports/duotone.php`.
if ( ! hasBlockSupport( settings, 'filter.duotone' ) ) {
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;
}
/**
* Override the default edit UI to include toolbar controls for duotone if the
* block supports duotone.
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
const withDuotoneControls = createHigherOrderComponent(
( BlockEdit ) => ( props ) => {
// Previous `color.__experimentalDuotone` support flag is migrated via
// block_type_metadata_settings filter in `lib/block-supports/duotone.php`.
const hasDuotoneSupport = hasBlockSupport(
props.name,
'filter.duotone'
);
const blockEditingMode = useBlockEditingMode();
// CAUTION: code added before this line will be executed
// for all blocks, not just those that support duotone. Code added
// above this line should be carefully evaluated for its impact on
// performance.
return (
<>
{ hasDuotoneSupport && blockEditingMode === 'default' && (
<DuotonePanel { ...props } />
) }
<BlockEdit { ...props } />
</>
);
},
'withDuotoneControls'
);
function DuotoneStyles( {
id: filterId,
selector: duotoneSelector,
attribute: duotoneAttr,
} ) {
const duotonePalette = useMultiOriginPresets( {
presetSetting: 'color.duotone',
defaultSetting: 'color.defaultDuotone',
} );
// Possible values for duotone attribute:
// 1. Array of colors - e.g. ['#000000', '#ffffff'].
// 2. Variable for an existing Duotone preset - e.g. 'var:preset|duotone|green-blue' or 'var(--wp--preset--duotone--green-blue)''
// 3. A CSS string - e.g. 'unset' to remove globally applied duotone.
const isCustom = Array.isArray( duotoneAttr );
const duotonePreset = isCustom
? undefined
: getColorsFromDuotonePreset( duotoneAttr, duotonePalette );
const isPreset = typeof duotoneAttr === 'string' && duotonePreset;
const isCSS = typeof duotoneAttr === 'string' && ! isPreset;
// Match the structure of WP_Duotone_Gutenberg::render_duotone_support() in PHP.
let colors = null;
if ( isPreset ) {
// Array of colors.
colors = duotonePreset;
} else if ( isCSS ) {
// CSS filter property string (e.g. 'unset').
colors = duotoneAttr;
} else if ( isCustom ) {
// Array of colors.
colors = duotoneAttr;
}
// Build the CSS selectors to which the filter will be applied.
const selectors = duotoneSelector.split( ',' );
const selectorsScoped = selectors.map( ( selectorPart ) => {
// Extra .editor-styles-wrapper specificity is needed in the editor
// since we're not using inline styles to apply the filter. We need to
// override duotone applied by global styles and theme.json.
// Assuming the selector part is a subclass selector (not a tag name)
// so we can prepend the filter id class. If we want to support elements
// such as `img` or namespaces, we'll need to add a case for that here.
return `.${ filterId }${ selectorPart.trim() }`;
} );
const selector = selectorsScoped.join( ', ' );
const isValidFilter = Array.isArray( colors ) || colors === 'unset';
const { setStyleOverride, deleteStyleOverride } = unlock(
useDispatch( blockEditorStore )
);
useEffect( () => {
if ( ! isValidFilter ) return;
setStyleOverride( filterId, {
css:
colors !== 'unset'
? getDuotoneStylesheet( selector, filterId )
: getDuotoneUnsetStylesheet( selector ),
__unstableType: 'presets',
} );
setStyleOverride( `duotone-${ filterId }`, {
assets:
colors !== 'unset' ? getDuotoneFilter( filterId, colors ) : '',
__unstableType: 'svgs',
} );
return () => {
deleteStyleOverride( filterId );
deleteStyleOverride( `duotone-${ filterId }` );
};
}, [
isValidFilter,
colors,
selector,
filterId,
setStyleOverride,
deleteStyleOverride,
] );
return null;
}
/**
* Override the default block element to include duotone styles.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withDuotoneStyles = createHigherOrderComponent(
( BlockListBlock ) => ( props ) => {
const id = useInstanceId( BlockListBlock );
const selector = useMemo( () => {
const blockType = getBlockType( props.name );
if ( blockType ) {
// Backwards compatibility for `supports.color.__experimentalDuotone`
// is provided via the `block_type_metadata_settings` filter. If
// `supports.filter.duotone` has not been set and the
// experimental property has been, the experimental property
// value is copied into `supports.filter.duotone`.
const duotoneSupport = getBlockSupport(
blockType,
'filter.duotone',
false
);
if ( ! duotoneSupport ) {
return null;
}
// If the experimental duotone support was set, that value is
// to be treated as a selector and requires scoping.
const experimentalDuotone = getBlockSupport(
blockType,
'color.__experimentalDuotone',
false
);
if ( experimentalDuotone ) {
const rootSelector = getBlockCSSSelector( blockType );
return typeof experimentalDuotone === 'string'
? scopeSelector( rootSelector, experimentalDuotone )
: rootSelector;
}
// Regular filter.duotone support uses filter.duotone selectors with fallbacks.
return getBlockCSSSelector( blockType, 'filter.duotone', {
fallback: true,
} );
}
}, [ props.name ] );
const attribute = props?.attributes?.style?.color?.duotone;
const filterClass = `wp-duotone-${ id }`;
const shouldRender = selector && attribute;
const className = shouldRender
? classnames( props?.className, filterClass )
: props?.className;
// CAUTION: code added before this line will be executed
// for all blocks, not just those that support duotone. Code added
// above this line should be carefully evaluated for its impact on
// performance.
return (
<>
{ shouldRender && (
<DuotoneStyles
id={ filterClass }
selector={ selector }
attribute={ attribute }
/>
) }
<BlockListBlock { ...props } className={ className } />
</>
);
},
'withDuotoneStyles'
);
addFilter(
'blocks.registerBlockType',
'core/editor/duotone/add-attributes',
addDuotoneAttributes
);
addFilter(
'editor.BlockEdit',
'core/editor/duotone/with-editor-controls',
withDuotoneControls
);
addFilter(
'editor.BlockListBlock',
'core/editor/duotone/with-styles',
withDuotoneStyles
);