-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathimage.js
1056 lines (992 loc) · 28.4 KB
/
image.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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* WordPress dependencies
*/
import { isBlobURL } from '@wordpress/blob';
import {
ExternalLink,
ResizableBox,
Spinner,
TextareaControl,
TextControl,
ToolbarButton,
ToolbarGroup,
Dropdown,
__experimentalToolsPanel as ToolsPanel,
__experimentalToolsPanelItem as ToolsPanelItem,
__experimentalUseCustomUnits as useCustomUnits,
Placeholder,
} from '@wordpress/components';
import { useViewportMatch } from '@wordpress/compose';
import { useSelect, useDispatch } from '@wordpress/data';
import {
BlockControls,
InspectorControls,
__experimentalImageURLInputUI as ImageURLInputUI,
MediaReplaceFlow,
store as blockEditorStore,
useSettings,
__experimentalImageEditor as ImageEditor,
__experimentalUseBorderProps as useBorderProps,
__experimentalGetShadowClassesAndStyles as getShadowClassesAndStyles,
privateApis as blockEditorPrivateApis,
} from '@wordpress/block-editor';
import { useEffect, useMemo, useState, useRef } from '@wordpress/element';
import { __, _x, sprintf, isRTL } from '@wordpress/i18n';
import { DOWN } from '@wordpress/keycodes';
import { getFilename } from '@wordpress/url';
import { switchToBlockType, store as blocksStore } from '@wordpress/blocks';
import { crop, overlayText, upload } from '@wordpress/icons';
import { store as noticesStore } from '@wordpress/notices';
import { store as coreStore } from '@wordpress/core-data';
/**
* Internal dependencies
*/
import { unlock } from '../lock-unlock';
import { createUpgradedEmbedBlock } from '../embed/util';
import { isExternalImage } from './edit';
import { Caption } from '../utils/caption';
/**
* Module constants
*/
import { useToolsPanelDropdownMenuProps } from '../utils/hooks';
import { MIN_SIZE, ALLOWED_MEDIA_TYPES } from './constants';
import { evalAspectRatio } from './utils';
const { DimensionsTool, ResolutionTool } = unlock( blockEditorPrivateApis );
const scaleOptions = [
{
value: 'cover',
label: _x( 'Cover', 'Scale option for dimensions control' ),
help: __( 'Image covers the space evenly.' ),
},
{
value: 'contain',
label: _x( 'Contain', 'Scale option for dimensions control' ),
help: __( 'Image is contained without distortion.' ),
},
];
// If the image has a href, wrap in an <a /> tag to trigger any inherited link element styles.
const ImageWrapper = ( { href, children } ) => {
if ( ! href ) {
return children;
}
return (
<a
href={ href }
onClick={ ( event ) => event.preventDefault() }
aria-disabled
style={ {
// When the Image block is linked,
// it's wrapped with a disabled <a /> tag.
// Restore cursor style so it doesn't appear 'clickable'
// and remove pointer events. Safari needs the display property.
pointerEvents: 'none',
cursor: 'default',
display: 'inline',
} }
>
{ children }
</a>
);
};
export default function Image( {
temporaryURL,
attributes,
setAttributes,
isSingleSelected,
insertBlocksAfter,
onReplace,
onSelectImage,
onSelectURL,
onUploadError,
context,
clientId,
blockEditingMode,
parentLayoutType,
containerWidth,
} ) {
const {
url = '',
alt,
align,
id,
href,
rel,
linkClass,
linkDestination,
title,
width,
height,
aspectRatio,
scale,
linkTarget,
sizeSlug,
lightbox,
metadata,
} = attributes;
// The only supported unit is px, so we can parseInt to strip the px here.
const numericWidth = width ? parseInt( width, 10 ) : undefined;
const numericHeight = height ? parseInt( height, 10 ) : undefined;
const imageRef = useRef();
const { allowResize = true } = context;
const { getBlock, getSettings } = useSelect( blockEditorStore );
const image = useSelect(
( select ) =>
id && isSingleSelected
? select( coreStore ).getMedia( id, { context: 'view' } )
: null,
[ id, isSingleSelected ]
);
const { canInsertCover, imageEditing, imageSizes, maxWidth } = useSelect(
( select ) => {
const { getBlockRootClientId, canInsertBlockType } =
select( blockEditorStore );
const rootClientId = getBlockRootClientId( clientId );
const settings = getSettings();
return {
imageEditing: settings.imageEditing,
imageSizes: settings.imageSizes,
maxWidth: settings.maxWidth,
canInsertCover: canInsertBlockType(
'core/cover',
rootClientId
),
};
},
[ clientId ]
);
const { replaceBlocks, toggleSelection } = useDispatch( blockEditorStore );
const { createErrorNotice, createSuccessNotice } =
useDispatch( noticesStore );
const isLargeViewport = useViewportMatch( 'medium' );
const isWideAligned = [ 'wide', 'full' ].includes( align );
const [
{ loadedNaturalWidth, loadedNaturalHeight },
setLoadedNaturalSize,
] = useState( {} );
const [ isEditingImage, setIsEditingImage ] = useState( false );
const [ externalBlob, setExternalBlob ] = useState();
const [ hasImageErrored, setHasImageErrored ] = useState( false );
const hasNonContentControls = blockEditingMode === 'default';
const isContentOnlyMode = blockEditingMode === 'contentOnly';
const isResizable =
allowResize &&
hasNonContentControls &&
! isWideAligned &&
isLargeViewport;
const imageSizeOptions = imageSizes
.filter(
( { slug } ) => image?.media_details?.sizes?.[ slug ]?.source_url
)
.map( ( { name, slug } ) => ( { value: slug, label: name } ) );
// If an image is externally hosted, try to fetch the image data. This may
// fail if the image host doesn't allow CORS with the domain. If it works,
// we can enable a button in the toolbar to upload the image.
useEffect( () => {
if (
! isExternalImage( id, url ) ||
! isSingleSelected ||
! getSettings().mediaUpload
) {
setExternalBlob();
return;
}
if ( externalBlob ) {
return;
}
window
// Avoid cache, which seems to help avoid CORS problems.
.fetch( url.includes( '?' ) ? url : url + '?' )
.then( ( response ) => response.blob() )
.then( ( blob ) => setExternalBlob( blob ) )
// Do nothing, cannot upload.
.catch( () => {} );
}, [ id, url, isSingleSelected, externalBlob ] );
// Get naturalWidth and naturalHeight from image ref, and fall back to loaded natural
// width and height. This resolves an issue in Safari where the loaded natural
// width and height is otherwise lost when switching between alignments.
// See: https://github.com/WordPress/gutenberg/pull/37210.
const { naturalWidth, naturalHeight } = useMemo( () => {
return {
naturalWidth:
imageRef.current?.naturalWidth ||
loadedNaturalWidth ||
undefined,
naturalHeight:
imageRef.current?.naturalHeight ||
loadedNaturalHeight ||
undefined,
};
}, [
loadedNaturalWidth,
loadedNaturalHeight,
imageRef.current?.complete,
] );
function onResizeStart() {
toggleSelection( false );
}
function onResizeStop() {
toggleSelection( true );
}
function onImageError() {
setHasImageErrored( true );
// Check if there's an embed block that handles this URL, e.g., instagram URL.
// See: https://github.com/WordPress/gutenberg/pull/11472
const embedBlock = createUpgradedEmbedBlock( { attributes: { url } } );
if ( undefined !== embedBlock ) {
onReplace( embedBlock );
}
}
function onImageLoad( event ) {
setHasImageErrored( false );
setLoadedNaturalSize( {
loadedNaturalWidth: event.target?.naturalWidth,
loadedNaturalHeight: event.target?.naturalHeight,
} );
}
function onSetHref( props ) {
setAttributes( props );
}
function onSetLightbox( enable ) {
if ( enable && ! lightboxSetting?.enabled ) {
setAttributes( {
lightbox: { enabled: true },
} );
} else if ( ! enable && lightboxSetting?.enabled ) {
setAttributes( {
lightbox: { enabled: false },
} );
} else {
setAttributes( {
lightbox: undefined,
} );
}
}
function resetLightbox() {
// When deleting a link from an image while lightbox settings
// are enabled by default, we should disable the lightbox,
// otherwise the resulting UX looks like a mistake.
// See https://github.com/WordPress/gutenberg/pull/59890/files#r1532286123.
if ( lightboxSetting?.enabled && lightboxSetting?.allowEditing ) {
setAttributes( {
lightbox: { enabled: false },
} );
} else {
setAttributes( {
lightbox: undefined,
} );
}
}
function onSetTitle( value ) {
// This is the HTML title attribute, separate from the media object
// title.
setAttributes( { title: value } );
}
function updateAlt( newAlt ) {
setAttributes( { alt: newAlt } );
}
function updateImage( newSizeSlug ) {
const newUrl = image?.media_details?.sizes?.[ newSizeSlug ]?.source_url;
if ( ! newUrl ) {
return null;
}
setAttributes( {
url: newUrl,
sizeSlug: newSizeSlug,
} );
}
function uploadExternal() {
const { mediaUpload } = getSettings();
if ( ! mediaUpload ) {
return;
}
mediaUpload( {
filesList: [ externalBlob ],
onFileChange( [ img ] ) {
onSelectImage( img );
if ( isBlobURL( img.url ) ) {
return;
}
setExternalBlob();
createSuccessNotice( __( 'Image uploaded.' ), {
type: 'snackbar',
} );
},
allowedTypes: ALLOWED_MEDIA_TYPES,
onError( message ) {
createErrorNotice( message, { type: 'snackbar' } );
},
} );
}
useEffect( () => {
if ( ! isSingleSelected ) {
setIsEditingImage( false );
}
}, [ isSingleSelected ] );
const canEditImage = id && naturalWidth && naturalHeight && imageEditing;
const allowCrop =
isSingleSelected &&
canEditImage &&
! isEditingImage &&
! isContentOnlyMode;
function switchToCover() {
replaceBlocks(
clientId,
switchToBlockType( getBlock( clientId ), 'core/cover' )
);
}
// TODO: Can allow more units after figuring out how they should interact
// with the ResizableBox and ImageEditor components. Calculations later on
// for those components are currently assuming px units.
const dimensionsUnitsOptions = useCustomUnits( {
availableUnits: [ 'px' ],
} );
const [ lightboxSetting ] = useSettings( 'lightbox' );
const showLightboxSetting =
// If a block-level override is set, we should give users the option to
// remove that override, even if the lightbox UI is disabled in the settings.
( !! lightbox && lightbox?.enabled !== lightboxSetting?.enabled ) ||
lightboxSetting?.allowEditing;
const lightboxChecked =
!! lightbox?.enabled || ( ! lightbox && !! lightboxSetting?.enabled );
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const dimensionsControl = (
<DimensionsTool
value={ { width, height, scale, aspectRatio } }
onChange={ ( {
width: newWidth,
height: newHeight,
scale: newScale,
aspectRatio: newAspectRatio,
} ) => {
// Rebuilding the object forces setting `undefined`
// for values that are removed since setAttributes
// doesn't do anything with keys that aren't set.
setAttributes( {
// CSS includes `height: auto`, but we need
// `width: auto` to fix the aspect ratio when
// only height is set due to the width and
// height attributes set via the server.
width: ! newWidth && newHeight ? 'auto' : newWidth,
height: newHeight,
scale: newScale,
aspectRatio: newAspectRatio,
} );
} }
defaultScale="cover"
defaultAspectRatio="auto"
scaleOptions={ scaleOptions }
unitsOptions={ dimensionsUnitsOptions }
/>
);
const aspectRatioControl = (
<DimensionsTool
value={ { aspectRatio } }
onChange={ ( { aspectRatio: newAspectRatio } ) => {
setAttributes( {
aspectRatio: newAspectRatio,
scale: 'cover',
} );
} }
defaultAspectRatio="auto"
tools={ [ 'aspectRatio' ] }
/>
);
const resetAll = () => {
setAttributes( {
alt: undefined,
width: undefined,
height: undefined,
scale: undefined,
aspectRatio: undefined,
lightbox: undefined,
} );
};
const sizeControls = (
<InspectorControls>
<ToolsPanel
label={ __( 'Settings' ) }
resetAll={ resetAll }
dropdownMenuProps={ dropdownMenuProps }
>
{ isResizable &&
( parentLayoutType === 'grid'
? aspectRatioControl
: dimensionsControl ) }
</ToolsPanel>
</InspectorControls>
);
const arePatternOverridesEnabled =
metadata?.bindings?.__default?.source === 'core/pattern-overrides';
const {
lockUrlControls = false,
lockHrefControls = false,
lockAltControls = false,
lockAltControlsMessage,
lockTitleControls = false,
lockTitleControlsMessage,
lockCaption = false,
} = useSelect(
( select ) => {
if ( ! isSingleSelected ) {
return {};
}
const { getBlockBindingsSource } = unlock( select( blocksStore ) );
const {
url: urlBinding,
alt: altBinding,
title: titleBinding,
} = metadata?.bindings || {};
const hasParentPattern = !! context[ 'pattern/overrides' ];
const urlBindingSource = getBlockBindingsSource(
urlBinding?.source
);
const altBindingSource = getBlockBindingsSource(
altBinding?.source
);
const titleBindingSource = getBlockBindingsSource(
titleBinding?.source
);
return {
lockUrlControls:
!! urlBinding &&
! urlBindingSource?.canUserEditValue?.( {
select,
context,
args: urlBinding?.args,
} ),
lockHrefControls:
// Disable editing the link of the URL if the image is inside a pattern instance.
// This is a temporary solution until we support overriding the link on the frontend.
hasParentPattern || arePatternOverridesEnabled,
lockCaption:
// Disable editing the caption if the image is inside a pattern instance.
// This is a temporary solution until we support overriding the caption on the frontend.
hasParentPattern,
lockAltControls:
!! altBinding &&
! altBindingSource?.canUserEditValue?.( {
select,
context,
args: altBinding?.args,
} ),
lockAltControlsMessage: altBindingSource?.label
? sprintf(
/* translators: %s: Label of the bindings source. */
__( 'Connected to %s' ),
altBindingSource.label
)
: __( 'Connected to dynamic data' ),
lockTitleControls:
!! titleBinding &&
! titleBindingSource?.canUserEditValue?.( {
select,
context,
args: titleBinding?.args,
} ),
lockTitleControlsMessage: titleBindingSource?.label
? sprintf(
/* translators: %s: Label of the bindings source. */
__( 'Connected to %s' ),
titleBindingSource.label
)
: __( 'Connected to dynamic data' ),
};
},
[
arePatternOverridesEnabled,
context,
isSingleSelected,
metadata?.bindings,
]
);
const showUrlInput =
isSingleSelected &&
! isEditingImage &&
! lockHrefControls &&
! lockUrlControls;
const showCoverControls = isSingleSelected && canInsertCover;
const showBlockControls = showUrlInput || allowCrop || showCoverControls;
const controls = (
<>
{ showBlockControls && (
<BlockControls group="block">
{ showUrlInput && (
<ImageURLInputUI
url={ href || '' }
onChangeUrl={ onSetHref }
linkDestination={ linkDestination }
mediaUrl={ ( image && image.source_url ) || url }
mediaLink={ image && image.link }
linkTarget={ linkTarget }
linkClass={ linkClass }
rel={ rel }
showLightboxSetting={ showLightboxSetting }
lightboxEnabled={ lightboxChecked }
onSetLightbox={ onSetLightbox }
resetLightbox={ resetLightbox }
/>
) }
{ allowCrop && (
<ToolbarButton
onClick={ () => setIsEditingImage( true ) }
icon={ crop }
label={ __( 'Crop' ) }
/>
) }
{ showCoverControls && (
<ToolbarButton
icon={ overlayText }
label={ __( 'Add text over image' ) }
onClick={ switchToCover }
/>
) }
</BlockControls>
) }
{ isSingleSelected && ! isEditingImage && ! lockUrlControls && (
<BlockControls group="other">
<MediaReplaceFlow
mediaId={ id }
mediaURL={ url }
allowedTypes={ ALLOWED_MEDIA_TYPES }
accept="image/*"
onSelect={ onSelectImage }
onSelectURL={ onSelectURL }
onError={ onUploadError }
onReset={ () => onSelectImage( undefined ) }
/>
</BlockControls>
) }
{ isSingleSelected && externalBlob && (
<BlockControls>
<ToolbarGroup>
<ToolbarButton
onClick={ uploadExternal }
icon={ upload }
label={ __( 'Upload to Media Library' ) }
/>
</ToolbarGroup>
</BlockControls>
) }
{ isContentOnlyMode && (
// Add some extra controls for content attributes when content only mode is active.
// With content only mode active, the inspector is hidden, so users need another way
// to edit these attributes.
<BlockControls group="other">
<Dropdown
popoverProps={ { position: 'bottom right' } }
renderToggle={ ( { isOpen, onToggle } ) => (
<ToolbarButton
onClick={ onToggle }
aria-haspopup="true"
aria-expanded={ isOpen }
onKeyDown={ ( event ) => {
if ( ! isOpen && event.keyCode === DOWN ) {
event.preventDefault();
onToggle();
}
} }
>
{ _x(
'Alternative text',
'Alternative text for an image. Block toolbar label, a low character count is preferred.'
) }
</ToolbarButton>
) }
renderContent={ () => (
<TextareaControl
className="wp-block-image__toolbar_content_textarea"
label={ __( 'Alternative text' ) }
value={ alt || '' }
onChange={ updateAlt }
disabled={ lockAltControls }
help={
lockAltControls ? (
<>{ lockAltControlsMessage }</>
) : (
<>
<ExternalLink
href={
// translators: Localized tutorial, if one exists. W3C Web Accessibility Initiative link has list of existing translations.
__(
'https://www.w3.org/WAI/tutorials/images/decision-tree/'
)
}
>
{ __(
'Describe the purpose of the image.'
) }
</ExternalLink>
<br />
{ __(
'Leave empty if decorative.'
) }
</>
)
}
__nextHasNoMarginBottom
/>
) }
/>
{ title && (
<Dropdown
popoverProps={ { position: 'bottom right' } }
renderToggle={ ( { isOpen, onToggle } ) => (
<ToolbarButton
onClick={ onToggle }
aria-haspopup="true"
aria-expanded={ isOpen }
onKeyDown={ ( event ) => {
if (
! isOpen &&
event.keyCode === DOWN
) {
event.preventDefault();
onToggle();
}
} }
>
{ __( 'Title' ) }
</ToolbarButton>
) }
renderContent={ () => (
<TextControl
__next40pxDefaultSize
className="wp-block-image__toolbar_content_textarea"
__nextHasNoMarginBottom
label={ __( 'Title attribute' ) }
value={ title || '' }
onChange={ onSetTitle }
disabled={ lockTitleControls }
help={
lockTitleControls ? (
<>{ lockTitleControlsMessage }</>
) : (
<>
{ __(
'Describe the role of this image on the page.'
) }
<ExternalLink href="https://www.w3.org/TR/html52/dom.html#the-title-attribute">
{ __(
'(Note: many devices and browsers do not display this text.)'
) }
</ExternalLink>
</>
)
}
/>
) }
/>
) }
</BlockControls>
) }
<InspectorControls>
<ToolsPanel
label={ __( 'Settings' ) }
resetAll={ resetAll }
dropdownMenuProps={ dropdownMenuProps }
>
{ isSingleSelected && (
<ToolsPanelItem
label={ __( 'Alternative text' ) }
isShownByDefault
hasValue={ () => !! alt }
onDeselect={ () =>
setAttributes( { alt: undefined } )
}
>
<TextareaControl
label={ __( 'Alternative text' ) }
value={ alt || '' }
onChange={ updateAlt }
readOnly={ lockAltControls }
help={
lockAltControls ? (
<>{ lockAltControlsMessage }</>
) : (
<>
<ExternalLink
href={
// translators: Localized tutorial, if one exists. W3C Web Accessibility Initiative link has list of existing translations.
__(
'https://www.w3.org/WAI/tutorials/images/decision-tree/'
)
}
>
{ __(
'Describe the purpose of the image.'
) }
</ExternalLink>
<br />
{ __(
'Leave empty if decorative.'
) }
</>
)
}
__nextHasNoMarginBottom
/>
</ToolsPanelItem>
) }
{ isResizable &&
( parentLayoutType === 'grid'
? aspectRatioControl
: dimensionsControl ) }
{ !! imageSizeOptions.length && (
<ResolutionTool
value={ sizeSlug }
onChange={ updateImage }
options={ imageSizeOptions }
/>
) }
</ToolsPanel>
</InspectorControls>
<InspectorControls group="advanced">
<TextControl
__nextHasNoMarginBottom
__next40pxDefaultSize
label={ __( 'Title attribute' ) }
value={ title || '' }
onChange={ onSetTitle }
readOnly={ lockTitleControls }
help={
lockTitleControls ? (
<>{ lockTitleControlsMessage }</>
) : (
<>
{ __(
'Describe the role of this image on the page.'
) }
<ExternalLink href="https://www.w3.org/TR/html52/dom.html#the-title-attribute">
{ __(
'(Note: many devices and browsers do not display this text.)'
) }
</ExternalLink>
</>
)
}
/>
</InspectorControls>
</>
);
const filename = getFilename( url );
let defaultedAlt;
if ( alt ) {
defaultedAlt = alt;
} else if ( filename ) {
defaultedAlt = sprintf(
/* translators: %s: file name */
__( 'This image has an empty alt attribute; its file name is %s' ),
filename
);
} else {
defaultedAlt = __( 'This image has an empty alt attribute' );
}
const borderProps = useBorderProps( attributes );
const shadowProps = getShadowClassesAndStyles( attributes );
const isRounded = attributes.className?.includes( 'is-style-rounded' );
let img =
temporaryURL && hasImageErrored ? (
// Show a placeholder during upload when the blob URL can't be loaded. This can
// happen when the user uploads a HEIC image in a browser that doesn't support them.
<Placeholder
className="wp-block-image__placeholder"
withIllustration
>
<Spinner />
</Placeholder>
) : (
// Disable reason: Image itself is not meant to be interactive, but
// should direct focus to block.
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/click-events-have-key-events */
<>
<img
src={ temporaryURL || url }
alt={ defaultedAlt }
onError={ onImageError }
onLoad={ onImageLoad }
ref={ imageRef }
className={ borderProps.className }
style={ {
width:
( width && height ) || aspectRatio
? '100%'
: undefined,
height:
( width && height ) || aspectRatio
? '100%'
: undefined,
objectFit: scale,
...borderProps.style,
...shadowProps.style,
} }
/>
{ temporaryURL && <Spinner /> }
</>
/* eslint-enable jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/click-events-have-key-events */
);
if ( canEditImage && isEditingImage ) {
img = (
<ImageWrapper href={ href }>
<ImageEditor
id={ id }
url={ url }
width={ numericWidth }
height={ numericHeight }
naturalHeight={ naturalHeight }
naturalWidth={ naturalWidth }
onSaveImage={ ( imageAttributes ) =>
setAttributes( imageAttributes )
}
onFinishEditing={ () => {
setIsEditingImage( false );
} }
borderProps={ isRounded ? undefined : borderProps }
/>
</ImageWrapper>
);
} else if ( ! isResizable || parentLayoutType === 'grid' ) {
img = (
<div style={ { width, height, aspectRatio } }>
<ImageWrapper href={ href }>{ img }</ImageWrapper>
</div>
);
} else {
const numericRatio = aspectRatio && evalAspectRatio( aspectRatio );
const customRatio = numericWidth / numericHeight;
const naturalRatio = naturalWidth / naturalHeight;
const ratio = numericRatio || customRatio || naturalRatio || 1;
const currentWidth =
! numericWidth && numericHeight
? numericHeight * ratio
: numericWidth;
const currentHeight =
! numericHeight && numericWidth
? numericWidth / ratio
: numericHeight;
const minWidth =
naturalWidth < naturalHeight ? MIN_SIZE : MIN_SIZE * ratio;
const minHeight =
naturalHeight < naturalWidth ? MIN_SIZE : MIN_SIZE / ratio;
// With the current implementation of ResizableBox, an image needs an
// explicit pixel value for the max-width. In absence of being able to
// set the content-width, this max-width is currently dictated by the
// vanilla editor style. The following variable adds a buffer to this
// vanilla style, so 3rd party themes have some wiggleroom. This does,
// in most cases, allow you to scale the image beyond the width of the
// main column, though not infinitely.
// @todo It would be good to revisit this once a content-width variable
// becomes available.
const maxWidthBuffer = maxWidth * 2.5;
const maxContentWidth = containerWidth || maxWidthBuffer;
let showRightHandle = false;
let showLeftHandle = false;
/* eslint-disable no-lonely-if */
// See https://github.com/WordPress/gutenberg/issues/7584.
if ( align === 'center' ) {
// When the image is centered, show both handles.
showRightHandle = true;
showLeftHandle = true;
} else if ( isRTL() ) {
// In RTL mode the image is on the right by default.
// Show the right handle and hide the left handle only when it is
// aligned left. Otherwise always show the left handle.
if ( align === 'left' ) {
showRightHandle = true;
} else {
showLeftHandle = true;
}
} else {
// Show the left handle and hide the right handle only when the
// image is aligned right. Otherwise always show the right handle.
if ( align === 'right' ) {
showLeftHandle = true;
} else {
showRightHandle = true;
}
}
/* eslint-enable no-lonely-if */
img = (
<ResizableBox
style={ {
display: 'block',
objectFit: scale,
aspectRatio:
! width && ! height && aspectRatio
? aspectRatio
: undefined,
} }
size={ {
width: currentWidth ?? 'auto',
height: currentHeight ?? 'auto',
} }
showHandle={ isSingleSelected }
minWidth={ minWidth }
maxWidth={ maxContentWidth }
minHeight={ minHeight }
maxHeight={ maxContentWidth / ratio }
lockAspectRatio={ ratio }
enable={ {
top: false,
right: showRightHandle,
bottom: true,
left: showLeftHandle,
} }
onResizeStart={ onResizeStart }
onResizeStop={ ( event, direction, elt ) => {
onResizeStop();
// Clear hardcoded width if the resized width is close to the max-content width.
if (
// Only do this if the image is bigger than the container to prevent it from being squished.
// TODO: Remove this check if the image support setting 100% width.