-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathedit.js
801 lines (743 loc) · 18.8 KB
/
edit.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
/**
* External dependencies
*/
import classnames from 'classnames';
import FastAverageColor from 'fast-average-color';
import tinycolor from 'tinycolor2';
/**
* WordPress dependencies
*/
import { Fragment, useEffect, useRef, useState } from '@wordpress/element';
import {
BaseControl,
Button,
FocalPointPicker,
PanelBody,
PanelRow,
RangeControl,
ResizableBox,
Spinner,
ToggleControl,
withNotices,
ButtonGroup,
SelectControl,
__experimentalUnitControl as BaseUnitControl,
__experimentalBoxControl as BoxControl,
} from '@wordpress/components';
import { compose, withInstanceId, useInstanceId } from '@wordpress/compose';
import {
BlockControls,
BlockIcon,
InspectorControls,
MediaPlaceholder,
MediaReplaceFlow,
withColors,
ColorPalette,
useBlockProps,
__experimentalUseInnerBlocksProps as useInnerBlocksProps,
__experimentalUseGradient,
__experimentalPanelColorGradientSettings as PanelColorGradientSettings,
__experimentalUnitControl as UnitControl,
__experimentalBlockAlignmentMatrixToolbar as BlockAlignmentMatrixToolbar,
} from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { withDispatch } from '@wordpress/data';
import { cover as icon } from '@wordpress/icons';
import { isBlobURL } from '@wordpress/blob';
/**
* Internal dependencies
*/
import {
attributesFromMedia,
IMAGE_BACKGROUND_TYPE,
VIDEO_BACKGROUND_TYPE,
COVER_MIN_HEIGHT,
CSS_UNITS,
SIZE_OPTIONS,
backgroundImageStyles,
dimRatioToClass,
isContentPositionCenter,
getPositionClassName,
} from './shared';
/**
* Module Constants
*/
const ALLOWED_MEDIA_TYPES = [ 'image', 'video' ];
const INNER_BLOCKS_TEMPLATE = [
[
'core/paragraph',
{
align: 'center',
fontSize: 'large',
placeholder: __( 'Write title…' ),
},
],
];
const { __Visualizer: BoxControlVisualizer } = BoxControl;
function retrieveFastAverageColor() {
if ( ! retrieveFastAverageColor.fastAverageColor ) {
retrieveFastAverageColor.fastAverageColor = new FastAverageColor();
}
return retrieveFastAverageColor.fastAverageColor;
}
function CustomSizeControl( { value, onSelect } ) {
let initMode = value.search( /auto/ );
if ( initMode < 1 ) {
initMode = 'both';
} else if ( initMode === 0 ) {
initMode = 'width';
} else {
initMode = 'height';
}
const [ currentMode, setMode ] = useState( initMode );
const customUnits = [
{ value: 'px', label: 'px', default: 0 },
{ value: '%', label: '%', default: 10 },
];
// Split and pick up values + units from the CSS inline.
let wh =
value &&
value
.replace( /auto/, '50%' )
.split( /(\d+|%|px|auto)/ )
.filter( ( v ) => !! v && v !== ' ' );
// default values.
if ( wh.length < 2 ) {
wh = [ '50', '%', '50', '%' ];
}
function customSizeHandler( data ) {
const { mode, w, wu, h, hu } = data;
if ( mode ) {
setMode( mode );
}
let inlineStyle = '';
switch ( mode || currentMode ) {
case 'width':
inlineStyle = `${ w || wh[ 0 ] }${ wu || wh[ 1 ] } auto`;
break;
case 'height':
inlineStyle = `auto ${ h || wh[ 2 ] }${ hu || wh[ 3 ] }`;
break;
case 'both':
inlineStyle =
`${ w || wh[ 0 ] }${ wu || wh[ 1 ] } ` +
`${ h || wh[ 2 ] }${ hu || wh[ 3 ] }`;
break;
}
onSelect( inlineStyle );
}
return (
<Fragment>
<SelectControl
label={ __( 'Size mode' ) }
options={ [
{
value: 'width',
label: __( 'Width' ),
},
{
value: 'height',
label: __( 'Height' ),
},
{
value: 'both',
label: __( 'Width & Height' ),
},
] }
value={ currentMode }
onChange={ ( newMode ) =>
customSizeHandler( { mode: newMode } )
}
labelPosition="top"
/>
<div className="background-size-custom-options">
{ ( currentMode === 'width' || currentMode === 'both' ) && (
<CoverValueUnitInput
label={ __( 'Width' ) }
value={ wh[ 0 ] }
unit={ wh[ 1 ] }
units={ customUnits }
onChange={ ( w ) => customSizeHandler( { w } ) }
onUnitChange={ ( wu ) => customSizeHandler( { wu } ) }
customUnits={ false }
/>
) }
{ ( currentMode === 'height' || currentMode === 'both' ) && (
<CoverValueUnitInput
label={ __( 'Height' ) }
value={ wh[ 2 ] }
unit={ wh[ 3 ] }
units={ customUnits }
onChange={ ( h ) => customSizeHandler( { h } ) }
onUnitChange={ ( hu ) => customSizeHandler( { hu } ) }
customUnits={ false }
/>
) }
</div>
</Fragment>
);
}
/**
* Helper function to fetect if the given size is custom or not.
*
* @param {string} size - Background size
* @return {boolean} True if size is custom. Otherwise, False.
*/
export function isCustomSize( size ) {
return (
SIZE_OPTIONS.map( ( opt ) => opt.slug ).indexOf( size ) < 0 ||
size === 'custom'
);
}
function BackgroundSizeControl( { size = 'cover', onSelect } ) {
return (
<Fragment>
<BaseControl
label={ __( ' Background size' ) }
id={ 'background-size' }
>
<ButtonGroup
label={ __( 'Size' ) }
defaultChecked="size-content"
className="background-size-options"
>
{ SIZE_OPTIONS.map( ( { slug, label, icon: sizeIcon } ) => (
<Button
key={ slug }
icon={ sizeIcon }
label={ label }
isPressed={
slug === size ||
( slug === 'custom' && isCustomSize( size ) )
}
onClick={ () => onSelect( slug ) }
/>
) ) }
</ButtonGroup>
</BaseControl>
{ isCustomSize( size ) && (
<CustomSizeControl value={ size } onSelect={ onSelect } />
) }
</Fragment>
);
}
function CoverValueUnitInput( {
onChange,
onUnitChange,
unit = 'px',
value = '',
label,
units = CSS_UNITS,
customUnits = true,
} ) {
const [ temporaryInput, setTemporaryInput ] = useState( null );
const instanceId = useInstanceId( UnitControl );
const inputId = `block-cover-height-input-${ instanceId }`;
const isPx = unit === 'px';
const handleOnChange = ( unprocessedValue ) => {
const inputValue =
unprocessedValue !== ''
? parseInt( unprocessedValue, 10 )
: undefined;
if ( isNaN( inputValue ) && inputValue !== undefined ) {
setTemporaryInput( unprocessedValue );
return;
}
setTemporaryInput( null );
onChange( inputValue );
if ( inputValue === undefined ) {
onUnitChange();
}
};
const handleOnBlur = () => {
if ( temporaryInput !== null ) {
setTemporaryInput( null );
}
};
const inputValue = temporaryInput !== null ? temporaryInput : value;
const min = isPx ? COVER_MIN_HEIGHT : 0;
const controlUnitProps = {
id: inputId,
min,
onBlur: handleOnBlur,
onChange: handleOnChange,
onUnitChange,
step: '1',
style: { maxWidth: 80 },
unit,
units,
value: inputValue,
};
return (
<BaseControl label={ label } id={ inputId }>
{ customUnits ? (
<UnitControl isResetValueOnUnitChange { ...controlUnitProps } />
) : (
<BaseUnitControl
isResetValueOnUnitChange
{ ...controlUnitProps }
/>
) }
</BaseControl>
);
}
const RESIZABLE_BOX_ENABLE_OPTION = {
top: false,
right: false,
bottom: true,
left: false,
topRight: false,
bottomRight: false,
bottomLeft: false,
topLeft: false,
};
function ResizableCover( {
className,
onResizeStart,
onResize,
onResizeStop,
...props
} ) {
const [ isResizing, setIsResizing ] = useState( false );
return (
<ResizableBox
className={ classnames( className, {
'is-resizing': isResizing,
} ) }
enable={ RESIZABLE_BOX_ENABLE_OPTION }
onResizeStart={ ( _event, _direction, elt ) => {
onResizeStart( elt.clientHeight );
onResize( elt.clientHeight );
} }
onResize={ ( _event, _direction, elt ) => {
onResize( elt.clientHeight );
if ( ! isResizing ) {
setIsResizing( true );
}
} }
onResizeStop={ ( _event, _direction, elt ) => {
onResizeStop( elt.clientHeight );
setIsResizing( false );
} }
minHeight={ COVER_MIN_HEIGHT }
{ ...props }
/>
);
}
/**
* useCoverIsDark is a hook that returns a boolean variable specifying if the cover
* background is dark or not.
*
* @param {?string} url Url of the media background.
* @param {?number} dimRatio Transparency of the overlay color. If an image and
* color are set, dimRatio is used to decide what is used
* for background darkness checking purposes.
* @param {?string} overlayColor String containing the overlay color value if one exists.
* @param {?Object} elementRef If a media background is set, elementRef should contain a reference to a
* dom element that renders that media.
*
* @return {boolean} True if the cover background is considered "dark" and false otherwise.
*/
function useCoverIsDark( url, dimRatio = 50, overlayColor, elementRef ) {
const [ isDark, setIsDark ] = useState( false );
useEffect( () => {
// If opacity is lower than 50 the dominant color is the image or video color,
// so use that color for the dark mode computation.
if ( url && dimRatio <= 50 && elementRef.current ) {
retrieveFastAverageColor().getColorAsync(
elementRef.current,
( color ) => {
setIsDark( color.isDark );
}
);
}
}, [ url, url && dimRatio <= 50 && elementRef.current, setIsDark ] );
useEffect( () => {
// If opacity is greater than 50 the dominant color is the overlay color,
// so use that color for the dark mode computation.
if ( dimRatio > 50 || ! url ) {
if ( ! overlayColor ) {
// If no overlay color exists the overlay color is black (isDark )
setIsDark( true );
return;
}
setIsDark( tinycolor( overlayColor ).isDark() );
}
}, [ overlayColor, dimRatio > 50 || ! url, setIsDark ] );
useEffect( () => {
if ( ! url && ! overlayColor ) {
// Reset isDark
setIsDark( false );
}
}, [ ! url && ! overlayColor, setIsDark ] );
return isDark;
}
function CoverEdit( {
attributes,
setAttributes,
isSelected,
noticeUI,
overlayColor,
setOverlayColor,
toggleSelection,
noticeOperations,
} ) {
const {
contentPosition,
id,
backgroundType,
backgroundSize,
dimRatio,
focalPoint,
hasParallax,
isRepeated,
minHeight,
minHeightUnit,
style: styleAttribute,
url,
} = attributes;
const {
gradientClass,
gradientValue,
setGradient,
} = __experimentalUseGradient();
const onSelectMedia = attributesFromMedia( setAttributes );
const isBlogUrl = isBlobURL( url );
// Store the previous background custom size.
const [ prevBackgroundSize, setPrevbackgroundSize ] = useState();
useEffect( () => {
if ( ! isCustomSize( backgroundSize ) ) {
return;
}
setPrevbackgroundSize( backgroundSize );
}, [ backgroundSize ] );
const toggleParallax = () => {
setAttributes( {
hasParallax: ! hasParallax,
...( ! hasParallax ? { focalPoint: undefined } : {} ),
} );
};
const toggleIsRepeated = () => {
setAttributes( {
isRepeated: ! isRepeated,
} );
};
const isDarkElement = useRef();
const isDark = useCoverIsDark(
url,
dimRatio,
overlayColor.color,
isDarkElement
);
const isImageBackground = IMAGE_BACKGROUND_TYPE === backgroundType;
const isVideoBackground = VIDEO_BACKGROUND_TYPE === backgroundType;
const [ temporaryMinHeight, setTemporaryMinHeight ] = useState( null );
const { removeAllNotices, createErrorNotice } = noticeOperations;
const minHeightWithUnit = minHeightUnit
? `${ minHeight }${ minHeightUnit }`
: minHeight;
const style = {
...( isImageBackground ? backgroundImageStyles( url ) : {} ),
backgroundColor: overlayColor.color,
minHeight: temporaryMinHeight || minHeightWithUnit || undefined,
backgroundSize,
};
if ( gradientValue && ! url ) {
style.background = gradientValue;
}
let positionValue;
if ( focalPoint ) {
positionValue = `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`;
if ( isImageBackground ) {
style.backgroundPosition = positionValue;
}
}
const hasBackground = !! ( url || overlayColor.color || gradientValue );
const showFocalPointPicker =
isVideoBackground ||
( isImageBackground && ( ! hasParallax || isRepeated ) );
const controls = (
<>
<BlockControls>
{ hasBackground && (
<>
<BlockAlignmentMatrixToolbar
label={ __( 'Change content position' ) }
value={ contentPosition }
onChange={ ( nextPosition ) =>
setAttributes( {
contentPosition: nextPosition,
} )
}
/>
<MediaReplaceFlow
mediaId={ id }
mediaURL={ url }
allowedTypes={ ALLOWED_MEDIA_TYPES }
accept="image/*,video/*"
onSelect={ onSelectMedia }
/>
</>
) }
</BlockControls>
<InspectorControls>
{ !! url && (
<PanelBody title={ __( 'Media settings' ) }>
{ isImageBackground && (
<Fragment>
<ToggleControl
label={ __( 'Fixed background' ) }
checked={ hasParallax }
onChange={ toggleParallax }
/>
<ToggleControl
label={ __( 'Repeated background' ) }
checked={ isRepeated }
onChange={ toggleIsRepeated }
/>
<BackgroundSizeControl
size={ backgroundSize }
onSelect={ ( newSize ) => {
setAttributes( {
backgroundSize:
newSize === 'custom' &&
!! prevBackgroundSize
? prevBackgroundSize
: newSize,
} );
} }
/>
</Fragment>
) }
{ showFocalPointPicker && (
<FocalPointPicker
label={ __( 'Focal point picker' ) }
url={ url }
value={ focalPoint }
onChange={ ( newFocalPoint ) =>
setAttributes( {
focalPoint: newFocalPoint,
} )
}
/>
) }
<PanelRow>
<Button
isSecondary
isSmall
className="block-library-cover__reset-button"
onClick={ () =>
setAttributes( {
url: undefined,
id: undefined,
backgroundType: undefined,
dimRatio: undefined,
focalPoint: undefined,
hasParallax: undefined,
isRepeated: undefined,
} )
}
>
{ __( 'Clear Media' ) }
</Button>
</PanelRow>
</PanelBody>
) }
{ hasBackground && (
<>
<PanelBody title={ __( 'Dimensions' ) }>
<CoverValueUnitInput
value={ temporaryMinHeight || minHeight }
unit={ minHeightUnit }
onChange={ ( newMinHeight ) =>
setAttributes( { minHeight: newMinHeight } )
}
onUnitChange={ ( nextUnit ) => {
setAttributes( {
minHeightUnit: nextUnit,
} );
} }
label={ __( 'Minimum height of cover' ) }
/>
</PanelBody>
<PanelColorGradientSettings
title={ __( 'Overlay' ) }
initialOpen={ true }
settings={ [
{
colorValue: overlayColor.color,
gradientValue,
onColorChange: setOverlayColor,
onGradientChange: setGradient,
label: __( 'Color' ),
},
] }
>
{ !! url && (
<RangeControl
label={ __( 'Opacity' ) }
value={ dimRatio }
onChange={ ( newDimRation ) =>
setAttributes( {
dimRatio: newDimRation,
} )
}
min={ 0 }
max={ 100 }
step={ 10 }
required
/>
) }
</PanelColorGradientSettings>
</>
) }
</InspectorControls>
</>
);
const blockProps = useBlockProps();
const innerBlocksProps = useInnerBlocksProps(
{
className: 'wp-block-cover__inner-container',
},
{
template: INNER_BLOCKS_TEMPLATE,
templateInsertUpdatesSelection: true,
}
);
if ( ! hasBackground ) {
const placeholderIcon = <BlockIcon icon={ icon } />;
const label = __( 'Cover' );
return (
<>
{ controls }
<div
{ ...blockProps }
className={ classnames(
'is-placeholder',
blockProps.className
) }
>
<MediaPlaceholder
icon={ placeholderIcon }
labels={ {
title: label,
instructions: __(
'Upload an image or video file, or pick one from your media library.'
),
} }
onSelect={ onSelectMedia }
accept="image/*,video/*"
allowedTypes={ ALLOWED_MEDIA_TYPES }
notices={ noticeUI }
onError={ ( message ) => {
removeAllNotices();
createErrorNotice( message );
} }
>
<div className="wp-block-cover__placeholder-background-options">
<ColorPalette
disableCustomColors={ true }
value={ overlayColor.color }
onChange={ setOverlayColor }
clearable={ false }
/>
</div>
</MediaPlaceholder>
</div>
</>
);
}
const classes = classnames(
dimRatioToClass( dimRatio ),
{
'is-dark-theme': isDark,
'has-background-dim': dimRatio !== 0,
'is-transient': isBlogUrl,
'has-parallax': hasParallax,
'is-repeated': isRepeated,
[ overlayColor.class ]: overlayColor.class,
'has-background-gradient': gradientValue,
[ gradientClass ]: ! url && gradientClass,
'has-custom-content-position': ! isContentPositionCenter(
contentPosition
),
},
getPositionClassName( contentPosition )
);
return (
<>
{ controls }
<div
{ ...blockProps }
className={ classnames( classes, blockProps.className ) }
style={ { ...style, ...blockProps.style } }
data-url={ url }
>
<BoxControlVisualizer
values={ styleAttribute?.spacing?.padding }
showValues={ styleAttribute?.visualizers?.padding }
/>
<ResizableCover
className="block-library-cover__resize-container"
onResizeStart={ () => {
setAttributes( { minHeightUnit: 'px' } );
toggleSelection( false );
} }
onResize={ setTemporaryMinHeight }
onResizeStop={ ( newMinHeight ) => {
toggleSelection( true );
setAttributes( { minHeight: newMinHeight } );
setTemporaryMinHeight( null );
} }
showHandle={ isSelected }
/>
{ isImageBackground && (
// Used only to programmatically check if the image is dark or not
<img
ref={ isDarkElement }
aria-hidden
alt=""
style={ {
display: 'none',
} }
src={ url }
/>
) }
{ url && gradientValue && dimRatio !== 0 && (
<span
aria-hidden="true"
className={ classnames(
'wp-block-cover__gradient-background',
gradientClass
) }
style={ { background: gradientValue } }
/>
) }
{ isVideoBackground && (
<video
ref={ isDarkElement }
className="wp-block-cover__video-background"
autoPlay
muted
loop
src={ url }
style={ { objectPosition: positionValue } }
/>
) }
{ isBlogUrl && <Spinner /> }
<div { ...innerBlocksProps } />
</div>
</>
);
}
export default compose( [
withDispatch( ( dispatch ) => {
const { toggleSelection } = dispatch( 'core/block-editor' );
return {
toggleSelection,
};
} ),
withColors( { overlayColor: 'background-color' } ),
withNotices,
withInstanceId,
] )( CoverEdit );