-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
image.js
565 lines (526 loc) · 14.7 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
/**
* External dependencies
*/
import { get, filter, map, pick, includes } from 'lodash';
/**
* WordPress dependencies
*/
import { isBlobURL } from '@wordpress/blob';
import {
ExternalLink,
PanelBody,
ResizableBox,
Spinner,
TextareaControl,
TextControl,
ToolbarButton,
} from '@wordpress/components';
import { useViewportMatch, usePrevious } from '@wordpress/compose';
import { useSelect, useDispatch } from '@wordpress/data';
import {
BlockControls,
InspectorControls,
RichText,
__experimentalImageSizeControl as ImageSizeControl,
__experimentalImageURLInputUI as ImageURLInputUI,
MediaReplaceFlow,
store as blockEditorStore,
BlockAlignmentControl,
__experimentalImageEditor as ImageEditor,
__experimentalImageEditingProvider as ImageEditingProvider,
} from '@wordpress/block-editor';
import { useEffect, useState, useRef } from '@wordpress/element';
import { __, sprintf, isRTL } from '@wordpress/i18n';
import { getFilename } from '@wordpress/url';
import { createBlock, switchToBlockType } 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 { createUpgradedEmbedBlock } from '../embed/util';
import useClientWidth from './use-client-width';
import { isExternalImage } from './edit';
/**
* Module constants
*/
import { MIN_SIZE, ALLOWED_MEDIA_TYPES } from './constants';
export default function Image( {
temporaryURL,
attributes: {
url = '',
alt,
caption,
align,
id,
href,
rel,
linkClass,
linkDestination,
title,
width,
height,
linkTarget,
sizeSlug,
},
setAttributes,
isSelected,
insertBlocksAfter,
onReplace,
onSelectImage,
onSelectURL,
onUploadError,
containerRef,
context,
clientId,
} ) {
const imageRef = useRef();
const captionRef = useRef();
const prevUrl = usePrevious( url );
const { allowResize = true } = context;
const { getBlock } = useSelect( blockEditorStore );
const { image, multiImageSelection } = useSelect(
( select ) => {
const { getMedia } = select( coreStore );
const { getMultiSelectedBlockClientIds, getBlockName } = select(
blockEditorStore
);
const multiSelectedClientIds = getMultiSelectedBlockClientIds();
return {
image: id && isSelected ? getMedia( id ) : null,
multiImageSelection:
multiSelectedClientIds.length &&
multiSelectedClientIds.every(
( _clientId ) =>
getBlockName( _clientId ) === 'core/image'
),
};
},
[ id, isSelected ]
);
const {
canInsertCover,
imageEditing,
imageSizes,
maxWidth,
mediaUpload,
} = useSelect(
( select ) => {
const {
getBlockRootClientId,
getSettings,
canInsertBlockType,
} = select( blockEditorStore );
const rootClientId = getBlockRootClientId( clientId );
const settings = pick( getSettings(), [
'imageEditing',
'imageSizes',
'maxWidth',
'mediaUpload',
] );
return {
...settings,
canInsertCover: canInsertBlockType(
'core/cover',
rootClientId
),
};
},
[ clientId ]
);
const { replaceBlocks, toggleSelection } = useDispatch( blockEditorStore );
const { createErrorNotice, createSuccessNotice } = useDispatch(
noticesStore
);
const isLargeViewport = useViewportMatch( 'medium' );
const isWideAligned = includes( [ 'wide', 'full' ], align );
const [ isEditingImage, setIsEditingImage ] = useState( false );
const [ externalBlob, setExternalBlob ] = useState();
const clientWidth = useClientWidth( containerRef, [ align ] );
const isResizable = allowResize && ! ( isWideAligned && isLargeViewport );
const imageSizeOptions = map(
filter( imageSizes, ( { slug } ) =>
get( image, [ 'media_details', 'sizes', slug, 'source_url' ] )
),
( { 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 ) || ! isSelected || externalBlob ) {
return;
}
window
.fetch( url )
.then( ( response ) => response.blob() )
.then( ( blob ) => setExternalBlob( blob ) )
// Do nothing, cannot upload.
.catch( () => {} );
}, [ id, url, isSelected, externalBlob ] );
// Focus the caption after inserting an image from the placeholder. This is
// done to preserve the behaviour of focussing the first tabbable element
// when a block is mounted. Previously, the image block would remount when
// the placeholder is removed. Maybe this behaviour could be removed.
useEffect( () => {
if ( url && ! prevUrl && isSelected ) {
captionRef.current.focus();
}
}, [ url, prevUrl ] );
function onResizeStart() {
toggleSelection( false );
}
function onResizeStop() {
toggleSelection( true );
}
function onImageError() {
// Check if there's an embed block that handles this URL.
const embedBlock = createUpgradedEmbedBlock( { attributes: { url } } );
if ( undefined !== embedBlock ) {
onReplace( embedBlock );
}
}
function onSetHref( props ) {
setAttributes( props );
}
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 = get( image, [
'media_details',
'sizes',
newSizeSlug,
'source_url',
] );
if ( ! newUrl ) {
return null;
}
setAttributes( {
url: newUrl,
width: undefined,
height: undefined,
sizeSlug: newSizeSlug,
} );
}
function uploadExternal() {
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' } );
},
} );
}
function updateAlignment( nextAlign ) {
const extraUpdatedAttributes = [ 'wide', 'full' ].includes( nextAlign )
? { width: undefined, height: undefined }
: {};
setAttributes( {
...extraUpdatedAttributes,
align: nextAlign,
} );
}
useEffect( () => {
if ( ! isSelected ) {
setIsEditingImage( false );
}
}, [ isSelected ] );
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' );
}
let img = (
// 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() }
ref={ imageRef }
/>
{ temporaryURL && <Spinner /> }
</>
/* eslint-enable jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/click-events-have-key-events */
);
let imageWidthWithinContainer;
let imageHeightWithinContainer;
const naturalWidth = imageRef.current?.naturalWidth;
const naturalHeight = imageRef.current?.naturalHeight;
const canEditImage = id && naturalWidth && naturalHeight && imageEditing;
const allowCrop = ! multiImageSelection && canEditImage && ! isEditingImage;
function switchToCover() {
replaceBlocks(
clientId,
switchToBlockType( getBlock( clientId ), 'core/cover' )
);
}
const controls = (
<>
<BlockControls group="block">
<BlockAlignmentControl
value={ align }
onChange={ updateAlignment }
/>
{ ! multiImageSelection && ! isEditingImage && (
<ImageURLInputUI
url={ href || '' }
onChangeUrl={ onSetHref }
linkDestination={ linkDestination }
mediaUrl={ ( image && image.source_url ) || url }
mediaLink={ image && image.link }
linkTarget={ linkTarget }
linkClass={ linkClass }
rel={ rel }
/>
) }
{ allowCrop && (
<ToolbarButton
onClick={ () => setIsEditingImage( true ) }
icon={ crop }
label={ __( 'Crop' ) }
/>
) }
{ externalBlob && (
<ToolbarButton
onClick={ uploadExternal }
icon={ upload }
label={ __( 'Upload external image' ) }
/>
) }
{ ! multiImageSelection && canInsertCover && (
<ToolbarButton
icon={ overlayText }
label={ __( 'Add text over image' ) }
onClick={ switchToCover }
/>
) }
</BlockControls>
{ ! multiImageSelection && ! isEditingImage && (
<BlockControls group="other">
<MediaReplaceFlow
mediaId={ id }
mediaURL={ url }
allowedTypes={ ALLOWED_MEDIA_TYPES }
accept="image/*"
onSelect={ onSelectImage }
onSelectURL={ onSelectURL }
onError={ onUploadError }
/>
</BlockControls>
) }
<InspectorControls>
<PanelBody title={ __( 'Image settings' ) }>
{ ! multiImageSelection && (
<TextareaControl
label={ __( 'Alt text (alternative text)' ) }
value={ alt }
onChange={ updateAlt }
help={
<>
<ExternalLink href="https://www.w3.org/WAI/tutorials/images/decision-tree">
{ __(
'Describe the purpose of the image'
) }
</ExternalLink>
{ __(
'Leave empty if the image is purely decorative.'
) }
</>
}
/>
) }
<ImageSizeControl
onChangeImage={ updateImage }
onChange={ ( value ) => setAttributes( value ) }
slug={ sizeSlug }
width={ width }
height={ height }
imageSizeOptions={ imageSizeOptions }
isResizable={ isResizable }
imageWidth={ naturalWidth }
imageHeight={ naturalHeight }
/>
</PanelBody>
</InspectorControls>
<InspectorControls __experimentalGroup="advanced">
<TextControl
label={ __( 'Title attribute' ) }
value={ title || '' }
onChange={ onSetTitle }
help={
<>
{ __(
'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>
</>
);
if ( clientWidth && naturalWidth && naturalHeight ) {
const exceedMaxWidth = naturalWidth > clientWidth;
const ratio = naturalHeight / naturalWidth;
imageWidthWithinContainer = exceedMaxWidth ? clientWidth : naturalWidth;
imageHeightWithinContainer = exceedMaxWidth
? clientWidth * ratio
: naturalHeight;
}
if ( canEditImage && isEditingImage ) {
img = (
<ImageEditor
url={ url }
width={ width }
height={ height }
clientWidth={ clientWidth }
naturalHeight={ naturalHeight }
naturalWidth={ naturalWidth }
/>
);
} else if ( ! isResizable || ! imageWidthWithinContainer ) {
img = <div style={ { width, height } }>{ img }</div>;
} else {
const currentWidth = width || imageWidthWithinContainer;
const currentHeight = height || imageHeightWithinContainer;
const ratio = naturalWidth / naturalHeight;
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;
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
size={ {
width: width ?? 'auto',
height: height ?? 'auto',
} }
showHandle={ isSelected }
minWidth={ minWidth }
maxWidth={ maxWidthBuffer }
minHeight={ minHeight }
maxHeight={ maxWidthBuffer / ratio }
lockAspectRatio
enable={ {
top: false,
right: showRightHandle,
bottom: true,
left: showLeftHandle,
} }
onResizeStart={ onResizeStart }
onResizeStop={ ( event, direction, elt, delta ) => {
onResizeStop();
setAttributes( {
width: parseInt( currentWidth + delta.width, 10 ),
height: parseInt( currentHeight + delta.height, 10 ),
} );
} }
>
{ img }
</ResizableBox>
);
}
return (
<ImageEditingProvider
id={ id }
url={ url }
naturalWidth={ naturalWidth }
naturalHeight={ naturalHeight }
clientWidth={ clientWidth }
onSaveImage={ ( imageAttributes ) =>
setAttributes( imageAttributes )
}
isEditing={ isEditingImage }
onFinishEditing={ () => setIsEditingImage( false ) }
>
{ /* Hide controls during upload to avoid component remount,
which causes duplicated image upload. */ }
{ ! temporaryURL && controls }
{ img }
{ ( ! RichText.isEmpty( caption ) || isSelected ) && (
<RichText
ref={ captionRef }
tagName="figcaption"
aria-label={ __( 'Image caption text' ) }
placeholder={ __( 'Add caption' ) }
value={ caption }
onChange={ ( value ) =>
setAttributes( { caption: value } )
}
inlineToolbar
__unstableOnSplitAtEnd={ () =>
insertBlocksAfter( createBlock( 'core/paragraph' ) )
}
/>
) }
</ImageEditingProvider>
);
}