-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
625 lines (556 loc) · 16.1 KB
/
index.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
/**
* External dependencies
*/
import clsx from 'clsx';
/**
* WordPress dependencies
*/
import { useEntityProp, store as coreStore } from '@wordpress/core-data';
import { useEffect, useMemo, useRef } from '@wordpress/element';
import { Placeholder, Spinner } from '@wordpress/components';
import { compose, useResizeObserver } from '@wordpress/compose';
import {
withColors,
ColorPalette,
useBlockProps,
useSettings,
useInnerBlocksProps,
__experimentalUseGradient,
store as blockEditorStore,
useBlockEditingMode,
} from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
import { isBlobURL } from '@wordpress/blob';
import { store as noticesStore } from '@wordpress/notices';
/**
* Internal dependencies
*/
import {
attributesFromMedia,
IMAGE_BACKGROUND_TYPE,
VIDEO_BACKGROUND_TYPE,
dimRatioToClass,
isContentPositionCenter,
getPositionClassName,
mediaPosition,
} from '../shared';
import CoverInspectorControls from './inspector-controls';
import CoverBlockControls from './block-controls';
import CoverPlaceholder from './cover-placeholder';
import ResizableCoverPopover from './resizable-cover-popover';
import {
getMediaColor,
compositeIsDark,
DEFAULT_BACKGROUND_COLOR,
DEFAULT_OVERLAY_COLOR,
} from './color-utils';
import { DEFAULT_MEDIA_SIZE_SLUG } from '../constants';
function getInnerBlocksTemplate( attributes ) {
return [
[
'core/paragraph',
{
align: 'center',
placeholder: __( 'Write title…' ),
...attributes,
},
],
];
}
/**
* Is the URL a temporary blob URL? A blob URL is one that is used temporarily while
* the media (image or video) is being uploaded and will not have an id allocated yet.
*
* @param {number} id The id of the media.
* @param {string} url The url of the media.
*
* @return {boolean} Is the URL a Blob URL.
*/
const isTemporaryMedia = ( id, url ) => ! id && isBlobURL( url );
function CoverEdit( {
attributes,
clientId,
isSelected,
overlayColor,
setAttributes,
setOverlayColor,
toggleSelection,
context: { postId, postType },
} ) {
const {
contentPosition,
id,
url: originalUrl,
backgroundType: originalBackgroundType,
useFeaturedImage,
dimRatio,
focalPoint,
hasParallax,
isDark,
isRepeated,
minHeight,
minHeightUnit,
alt,
allowedBlocks,
templateLock,
tagName: TagName = 'div',
isUserOverlayColor,
sizeSlug,
} = attributes;
const [ featuredImage ] = useEntityProp(
'postType',
postType,
'featured_media',
postId
);
const { getSettings } = useSelect( blockEditorStore );
const { __unstableMarkNextChangeAsNotPersistent } =
useDispatch( blockEditorStore );
const media = useSelect(
( select ) =>
featuredImage &&
select( coreStore ).getMedia( featuredImage, { context: 'view' } ),
[ featuredImage ]
);
const mediaUrl = media?.source_url;
// User can change the featured image outside of the block, but we still
// need to update the block when that happens. This effect should only
// run when the featured image changes in that case. All other cases are
// handled in their respective callbacks.
useEffect( () => {
( async () => {
if ( ! useFeaturedImage ) {
return;
}
const averageBackgroundColor = await getMediaColor( mediaUrl );
let newOverlayColor = overlayColor.color;
if ( ! isUserOverlayColor ) {
newOverlayColor = averageBackgroundColor;
__unstableMarkNextChangeAsNotPersistent();
setOverlayColor( newOverlayColor );
}
const newIsDark = compositeIsDark(
dimRatio,
newOverlayColor,
averageBackgroundColor
);
__unstableMarkNextChangeAsNotPersistent();
setAttributes( {
isDark: newIsDark,
isUserOverlayColor: isUserOverlayColor || false,
} );
} )();
// Update the block only when the featured image changes.
}, [ mediaUrl ] );
// instead of destructuring the attributes
// we define the url and background type
// depending on the value of the useFeaturedImage flag
// to preview in edit the dynamic featured image
const url = useFeaturedImage
? mediaUrl
: // Ensure the url is not malformed due to sanitization through `wp_kses`.
originalUrl?.replaceAll( '&', '&' );
const backgroundType = useFeaturedImage
? IMAGE_BACKGROUND_TYPE
: originalBackgroundType;
const { createErrorNotice } = useDispatch( noticesStore );
const { gradientClass, gradientValue } = __experimentalUseGradient();
const onSelectMedia = async ( newMedia ) => {
const mediaAttributes = attributesFromMedia( newMedia );
const isImage = [ newMedia?.type, newMedia?.media_type ].includes(
IMAGE_BACKGROUND_TYPE
);
const averageBackgroundColor = await getMediaColor(
isImage ? newMedia?.url : undefined
);
let newOverlayColor = overlayColor.color;
if ( ! isUserOverlayColor ) {
newOverlayColor = averageBackgroundColor;
setOverlayColor( newOverlayColor );
// Make undo revert the next setAttributes and the previous setOverlayColor.
__unstableMarkNextChangeAsNotPersistent();
}
// Only set a new dimRatio if there was no previous media selected
// to avoid resetting to 50 if it has been explicitly set to 100.
// See issue #52835 for context.
const newDimRatio =
originalUrl === undefined && dimRatio === 100 ? 50 : dimRatio;
const newIsDark = compositeIsDark(
newDimRatio,
newOverlayColor,
averageBackgroundColor
);
if ( backgroundType === IMAGE_BACKGROUND_TYPE && mediaAttributes.id ) {
const { imageDefaultSize } = getSettings();
// Try to use the previous selected image size if it's available
// otherwise try the default image size or fallback to full size.
if (
sizeSlug &&
( newMedia?.sizes?.[ sizeSlug ] ||
newMedia?.media_details?.sizes?.[ sizeSlug ] )
) {
mediaAttributes.sizeSlug = sizeSlug;
mediaAttributes.url =
newMedia?.sizes?.[ sizeSlug ]?.url ||
newMedia?.media_details?.sizes?.[ sizeSlug ]?.source_url;
} else if (
newMedia?.sizes?.[ imageDefaultSize ] ||
newMedia?.media_details?.sizes?.[ imageDefaultSize ]
) {
mediaAttributes.sizeSlug = imageDefaultSize;
mediaAttributes.url =
newMedia?.sizes?.[ imageDefaultSize ]?.url ||
newMedia?.media_details?.sizes?.[ imageDefaultSize ]
?.source_url;
} else {
mediaAttributes.sizeSlug = DEFAULT_MEDIA_SIZE_SLUG;
}
}
setAttributes( {
...mediaAttributes,
focalPoint: undefined,
useFeaturedImage: undefined,
dimRatio: newDimRatio,
isDark: newIsDark,
isUserOverlayColor: isUserOverlayColor || false,
} );
};
const onClearMedia = () => {
let newOverlayColor = overlayColor.color;
if ( ! isUserOverlayColor ) {
newOverlayColor = DEFAULT_OVERLAY_COLOR;
setOverlayColor( undefined );
// Make undo revert the next setAttributes and the previous setOverlayColor.
__unstableMarkNextChangeAsNotPersistent();
}
const newIsDark = compositeIsDark(
dimRatio,
newOverlayColor,
DEFAULT_BACKGROUND_COLOR
);
setAttributes( {
url: undefined,
id: undefined,
backgroundType: undefined,
focalPoint: undefined,
hasParallax: undefined,
isRepeated: undefined,
useFeaturedImage: undefined,
isDark: newIsDark,
} );
};
const onSetOverlayColor = async ( newOverlayColor ) => {
const averageBackgroundColor = await getMediaColor( url );
const newIsDark = compositeIsDark(
dimRatio,
newOverlayColor,
averageBackgroundColor
);
setOverlayColor( newOverlayColor );
// Make undo revert the next setAttributes and the previous setOverlayColor.
__unstableMarkNextChangeAsNotPersistent();
setAttributes( {
isUserOverlayColor: true,
isDark: newIsDark,
} );
};
const onUpdateDimRatio = async ( newDimRatio ) => {
const averageBackgroundColor = await getMediaColor( url );
const newIsDark = compositeIsDark(
newDimRatio,
overlayColor.color,
averageBackgroundColor
);
setAttributes( {
dimRatio: newDimRatio,
isDark: newIsDark,
} );
};
const onUploadError = ( message ) => {
createErrorNotice( message, { type: 'snackbar' } );
};
const isUploadingMedia = isTemporaryMedia( id, url );
const isImageBackground = IMAGE_BACKGROUND_TYPE === backgroundType;
const isVideoBackground = VIDEO_BACKGROUND_TYPE === backgroundType;
const blockEditingMode = useBlockEditingMode();
const hasNonContentControls = blockEditingMode === 'default';
const [ resizeListener, { height, width } ] = useResizeObserver();
const resizableBoxDimensions = useMemo( () => {
return {
height: minHeightUnit === 'px' ? minHeight : 'auto',
width: 'auto',
};
}, [ minHeight, minHeightUnit ] );
const minHeightWithUnit =
minHeight && minHeightUnit
? `${ minHeight }${ minHeightUnit }`
: minHeight;
const isImgElement = ! ( hasParallax || isRepeated );
const style = {
minHeight: minHeightWithUnit || undefined,
};
const backgroundImage = url ? `url(${ url })` : undefined;
const backgroundPosition = mediaPosition( focalPoint );
const bgStyle = { backgroundColor: overlayColor.color };
const mediaStyle = {
objectPosition:
focalPoint && isImgElement
? mediaPosition( focalPoint )
: undefined,
};
const hasBackground = !! ( url || overlayColor.color || gradientValue );
const hasInnerBlocks = useSelect(
( select ) =>
select( blockEditorStore ).getBlock( clientId ).innerBlocks.length >
0,
[ clientId ]
);
const ref = useRef();
const blockProps = useBlockProps( { ref } );
// Check for fontSize support before we pass a fontSize attribute to the innerBlocks.
const [ fontSizes ] = useSettings( 'typography.fontSizes' );
const hasFontSizes = fontSizes?.length > 0;
const innerBlocksTemplate = getInnerBlocksTemplate( {
fontSize: hasFontSizes ? 'large' : undefined,
} );
const innerBlocksProps = useInnerBlocksProps(
{
className: 'wp-block-cover__inner-container',
},
{
// Avoid template sync when the `templateLock` value is `all` or `contentOnly`.
// See: https://github.com/WordPress/gutenberg/pull/45632
template: ! hasInnerBlocks ? innerBlocksTemplate : undefined,
templateInsertUpdatesSelection: true,
allowedBlocks,
templateLock,
dropZoneElement: ref.current,
}
);
const mediaElement = useRef();
const currentSettings = {
isVideoBackground,
isImageBackground,
mediaElement,
hasInnerBlocks,
url,
isImgElement,
overlayColor,
};
const toggleUseFeaturedImage = async () => {
const newUseFeaturedImage = ! useFeaturedImage;
const averageBackgroundColor = newUseFeaturedImage
? await getMediaColor( mediaUrl )
: DEFAULT_BACKGROUND_COLOR;
const newOverlayColor = ! isUserOverlayColor
? averageBackgroundColor
: overlayColor.color;
if ( ! isUserOverlayColor ) {
if ( newUseFeaturedImage ) {
setOverlayColor( newOverlayColor );
} else {
setOverlayColor( undefined );
}
// Make undo revert the next setAttributes and the previous setOverlayColor.
__unstableMarkNextChangeAsNotPersistent();
}
const newDimRatio = dimRatio === 100 ? 50 : dimRatio;
const newIsDark = compositeIsDark(
newDimRatio,
newOverlayColor,
averageBackgroundColor
);
setAttributes( {
id: undefined,
url: undefined,
useFeaturedImage: newUseFeaturedImage,
dimRatio: newDimRatio,
backgroundType: useFeaturedImage
? IMAGE_BACKGROUND_TYPE
: undefined,
isDark: newIsDark,
} );
};
const blockControls = (
<CoverBlockControls
attributes={ attributes }
setAttributes={ setAttributes }
onSelectMedia={ onSelectMedia }
currentSettings={ currentSettings }
toggleUseFeaturedImage={ toggleUseFeaturedImage }
onClearMedia={ onClearMedia }
/>
);
const inspectorControls = (
<CoverInspectorControls
attributes={ attributes }
setAttributes={ setAttributes }
clientId={ clientId }
setOverlayColor={ onSetOverlayColor }
coverRef={ ref }
currentSettings={ currentSettings }
toggleUseFeaturedImage={ toggleUseFeaturedImage }
updateDimRatio={ onUpdateDimRatio }
onClearMedia={ onClearMedia }
/>
);
const resizableCoverProps = {
className: 'block-library-cover__resize-container',
clientId,
height,
minHeight: minHeightWithUnit,
onResizeStart: () => {
setAttributes( { minHeightUnit: 'px' } );
toggleSelection( false );
},
onResize: ( value ) => {
setAttributes( { minHeight: value } );
},
onResizeStop: ( newMinHeight ) => {
toggleSelection( true );
setAttributes( { minHeight: newMinHeight } );
},
// Hide the resize handle if an aspect ratio is set, as the aspect ratio takes precedence.
showHandle: ! attributes.style?.dimensions?.aspectRatio,
size: resizableBoxDimensions,
width,
};
if ( ! useFeaturedImage && ! hasInnerBlocks && ! hasBackground ) {
return (
<>
{ blockControls }
{ inspectorControls }
{ hasNonContentControls && isSelected && (
<ResizableCoverPopover { ...resizableCoverProps } />
) }
<TagName
{ ...blockProps }
className={ clsx( 'is-placeholder', blockProps.className ) }
style={ {
...blockProps.style,
minHeight: minHeightWithUnit || undefined,
} }
>
{ resizeListener }
<CoverPlaceholder
onSelectMedia={ onSelectMedia }
onError={ onUploadError }
toggleUseFeaturedImage={ toggleUseFeaturedImage }
>
<div className="wp-block-cover__placeholder-background-options">
<ColorPalette
disableCustomColors
value={ overlayColor.color }
onChange={ onSetOverlayColor }
clearable={ false }
/>
</div>
</CoverPlaceholder>
</TagName>
</>
);
}
const classes = clsx(
{
'is-dark-theme': isDark,
'is-light': ! isDark,
'is-transient': isUploadingMedia,
'has-parallax': hasParallax,
'is-repeated': isRepeated,
'has-custom-content-position':
! isContentPositionCenter( contentPosition ),
},
getPositionClassName( contentPosition )
);
const showOverlay =
url || ! useFeaturedImage || ( useFeaturedImage && ! url );
return (
<>
{ blockControls }
{ inspectorControls }
<TagName
{ ...blockProps }
className={ clsx( classes, blockProps.className ) }
style={ { ...style, ...blockProps.style } }
data-url={ url }
>
{ resizeListener }
{ ! url && useFeaturedImage && (
<Placeholder
className="wp-block-cover__image--placeholder-image"
withIllustration
/>
) }
{ url &&
isImageBackground &&
( isImgElement ? (
<img
ref={ mediaElement }
className="wp-block-cover__image-background"
alt={ alt }
src={ url }
style={ mediaStyle }
/>
) : (
<div
ref={ mediaElement }
role={ alt ? 'img' : undefined }
aria-label={ alt ? alt : undefined }
className={ clsx(
classes,
'wp-block-cover__image-background'
) }
style={ { backgroundImage, backgroundPosition } }
/>
) ) }
{ url && isVideoBackground && (
<video
ref={ mediaElement }
className="wp-block-cover__video-background"
autoPlay
muted
loop
src={ url }
style={ mediaStyle }
/>
) }
{ showOverlay && (
<span
aria-hidden="true"
className={ clsx(
'wp-block-cover__background',
dimRatioToClass( dimRatio ),
{
[ overlayColor.class ]: overlayColor.class,
'has-background-dim': dimRatio !== undefined,
// For backwards compatibility. Former versions of the Cover Block applied
// `.wp-block-cover__gradient-background` in the presence of
// media, a gradient and a dim.
'wp-block-cover__gradient-background':
url && gradientValue && dimRatio !== 0,
'has-background-gradient': gradientValue,
[ gradientClass ]: gradientClass,
}
) }
style={ { backgroundImage: gradientValue, ...bgStyle } }
/>
) }
{ isUploadingMedia && <Spinner /> }
<CoverPlaceholder
disableMediaButtons
onSelectMedia={ onSelectMedia }
onError={ onUploadError }
toggleUseFeaturedImage={ toggleUseFeaturedImage }
/>
<div { ...innerBlocksProps } />
</TagName>
{ hasNonContentControls && isSelected && (
<ResizableCoverPopover { ...resizableCoverProps } />
) }
</>
);
}
export default compose( [
withColors( { overlayColor: 'background-color' } ),
] )( CoverEdit );