-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathimage.js
More file actions
551 lines (486 loc) · 15.6 KB
/
image.js
File metadata and controls
551 lines (486 loc) · 15.6 KB
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
/**
* This component is meant to replace the ImageUploadPlaceholder and Image
*/
import getSnapSizes from './get-snap-sizes'
/**
* External dependencies
*/
import { useDeviceType, useWithShift } from '~stackable/hooks'
import classnames from 'classnames'
import striptags from 'striptags'
import { clamp } from 'lodash'
import { useDynamicContent } from '~stackable/components/dynamic-content-control'
import { ResizerTooltip } from '~stackable/components'
/**
* WordPress dependencies
*/
import {
MediaUpload, RichText, useBlockEditContext,
} from '@wordpress/block-editor'
import {
Button, Dashicon, ResizableBox,
} from '@wordpress/components'
import {
useState, useEffect, memo, useRef, useMemo,
} from '@wordpress/element'
import { select } from '@wordpress/data'
import { applyFilters } from '@wordpress/hooks'
const formSize = ( size = '', unit = '%', usePx = false, usePct = true ) => {
if ( size === 'auto' ) {
return size
}
if ( ! size && size !== 0 ) {
return unit === '%' ? ( usePct ? '100%' : 100 ) : ( usePx ? '150px' : 150 )
}
return unit === '%' ? ( usePct ? `${ size }%` : size ) : ( usePx ? `${ size }px` : size )
}
const getImageWrapperClasses = props => {
return classnames( [
props.className,
'stk-img-wrapper',
], {
// Shape.
'stk-img--shape': props.shape,
// Firefox doesn't do stretching via SVG attribute and needs to be done via CSS.
'stk-image--shape-stretch': props.shapeStretch,
// Shadow is only available when there is no shape.
[ `stk--shadow-${ props.shadow }` ]: ! props.shape && props.shadow,
'stk-img--gradient-overlay': props.hasGradientOverlay,
'stk--has-lightbox': props.hasLightbox,
} )
}
const getImageClasses = props => {
return classnames( [
'stk-img',
], {
// Image props Id
[ `wp-image-${ props.imageId }` ]: props.imageId,
} )
}
const Image = memo( props => {
const { isSelected } = useBlockEditContext()
const [ neverResized, setNeverResized ] = useState( true )
const [ isResizing, setIsResizing ] = useState( false )
const [ lockAspectRatio, setLockAspectRatio ] = useState( false )
const [ initialHeight, setInitialHeight ] = useState()
const [ initialWidth, setInitialWidth ] = useState()
const [ parentHeight, setParentHeight ] = useState()
const [ parentWidth, setParentWidth ] = useState()
const [ hasImageError, setHasImageError ] = useState( false )
const [ currentHeight, setCurrentHeight ] = useState()
const [ currentWidth, setCurrentWidth ] = useState()
const [ imageWidthIsTooSmall, setImageWidthIsTooSmall ] = useState( false )
const imageRef = useRef()
const wrapperRef = useRef()
const { clientId } = useBlockEditContext()
const isImageBlock = useMemo( () => {
return select( 'core/block-editor' ).getBlockName( clientId ) === 'stackable/image'
}, [ clientId ] )
// Used to fix issue with Resizable where height in % doesn't show while resizing.
// @see https://github.com/bokuweb/re-resizable/issues/442
const [ tempStyle, setTempStyle ] = useState( null )
const [ snap, setSnap ] = useState( null )
const src = useDynamicContent( props.src )
const isShiftKey = useWithShift()
useEffect( () => {
setSnap( null )
}, [ isShiftKey ] )
const imageWrapperClasses = classnames( [
getImageWrapperClasses( props ),
'stk-img-resizer',
], {
'stk-img-placeholder': ! src || hasImageError,
'stk--never-resized': ( ! src || hasImageError ) && neverResized,
'stk--is-resizing': isResizing,
'stk--no-click-to-edit': ! props.enableClickToEdit,
// If the image is too small, hide the size tooltip.
'stk--too-small': imageWidthIsTooSmall,
} )
// Observe the size of the image, if it's too small, we shouldn't show the
// size tooltip.
useEffect( () => {
if ( imageRef.current ) {
const resizeObserver = new ResizeObserver( entries => { // eslint-disable-line compat/compat
for ( const entry of entries ) {
setImageWidthIsTooSmall( entry.contentRect.width < 140 )
}
} )
resizeObserver.observe( imageRef.current )
return () => resizeObserver.disconnect()
}
}, [ imageRef.current ] )
const imageClasses = getImageClasses( props )
return (
<ResizableBox
className={ imageWrapperClasses }
enable={ {
top: props.showHandles && props.heightResizePosition === 'top' ? props.enableHeight : false,
bottom: props.showHandles && props.heightResizePosition === 'bottom' ? props.enableHeight : false,
right: props.showHandles && props.widthResizePosition === 'right' ? props.enableWidth : false,
left: props.showHandles && props.widthResizePosition === 'left' ? props.enableWidth : false,
topRight: false,
bottomRight: props.showHandles && props.enableDiagonal,
bottomLeft: false,
topLeft: false,
} }
size={ {
width: formSize( currentWidth || props.width, props.widthUnit ),
height: formSize( currentHeight || props.height, props.heightUnit ),
} }
// Resizing is a bit slow when the image is centered, make it a bit faster.
resizeRatio={ 1.2 }
// Lock aspect ratio when resizing via the corner handler
lockAspectRatio={ lockAspectRatio }
snap={ snap }
snapGap={ 10 }
onResizeStart={ ( _event, _direction, elt ) => {
// Lock the aspect ratio when changing diagonally.
setLockAspectRatio( _direction === 'bottomRight' )
// Get the current size of the image.
let currentHeight = props.height ? parseFloat( props.height ) : 0
if ( props.heightUnit === '%' ) {
const parentHeight = elt.parentElement.getBoundingClientRect().height
setParentHeight( parentHeight )
currentHeight = ( props.height || 100 ) / 100 * parentHeight
} else if ( ! props.height || props.height === 'auto' ) {
currentHeight = parseInt( elt.getBoundingClientRect().height, 10 )
}
setInitialHeight( currentHeight || 0 )
let currentWidth = props.width ? parseFloat( props.width ) : 0
if ( props.widthUnit === '%' ) {
const parentWidth = elt.parentElement.getBoundingClientRect().width
setParentWidth( parentWidth )
currentWidth = ( props.width || 100 ) / 100 * parentWidth
} else if ( ! props.width || props.width === 'auto' ) {
currentWidth = parseInt( elt.getBoundingClientRect().width, 10 )
}
setInitialWidth( currentWidth || 0 )
setNeverResized( false )
setIsResizing( true )
setSnap( null )
} }
onResize={ ( _event, _direction, elt, delta ) => {
// Get the new size of the image when dragging.
let currentHeight, currentWidth
if ( props.heightUnit === '%' ) {
currentHeight = clamp( Math.round( ( initialHeight + delta.height ) / parentHeight * 100 ), 0, 100 )
// This is to make percentage heights work, see comment above about the issue in ResizableBox.
setTempStyle( `.stk--is-resizing { height: ${ currentHeight }% !important; }` )
} else {
currentHeight = initialHeight + delta.height
}
setCurrentHeight( currentHeight )
if ( props.widthUnit === '%' ) {
currentWidth = clamp( Math.round( ( initialWidth + delta.width ) / parentWidth * 100 ), 0, 100 )
} else {
currentWidth = initialWidth + delta.width
}
setCurrentWidth( currentWidth )
// Adjust the snapping of the image size.
if ( ! snap ) {
setSnap( getSnapSizes( parentWidth, parentHeight, props.widthUnit, props.heightUnit, _direction, isShiftKey ) )
}
} }
onResizeStop={ () => {
props.onChangeSize( {
width: currentWidth,
widthUnit: props.widthUnit,
height: currentHeight,
heightUnit: props.heightUnit,
} )
setIsResizing( false )
setCurrentWidth( null )
setCurrentHeight( null )
setTempStyle( null )
setSnap( null )
} }
>
{ src && props.onRemove && props.hasRemove && props.showTooltips && (
<button
className="stk-img-upload-remove"
onClick={ ev => {
props.onRemove()
ev.stopPropagation()
} }
>
<Dashicon icon="no" />
</button>
) }
{ props.hasTooltip && props.showTooltips && (
<ResizerTooltip
enableHeight={ props.enableHeight || props.enableDiagonal }
enableWidth={ props.enableWidth || props.enableDiagonal }
height={ formSize( currentHeight || props.height, props.heightUnit, false, false ) }
width={ formSize( currentWidth || props.width, props.widthUnit, false, false ) }
widthUnits={ props.widthUnits }
heightUnits={ props.heightUnits }
heightUnit={ props.heightUnit }
widthUnit={ props.widthUnit }
allowReset={ props.allowReset }
defaultWidth={ props.defaultWidth }
defaultHeight={ props.defaultHeight }
onChangeHeight={ ( { value, unit } ) => {
const size = {}
if ( typeof value !== 'undefined' ) {
size.height = value
}
if ( typeof unit !== 'undefined' ) {
size.heightUnit = unit
}
props.onChangeSize( size )
} }
onChangeWidth={ ( { value, unit } ) => {
const size = {}
if ( typeof value !== 'undefined' ) {
size.width = value
}
if ( typeof unit !== 'undefined' ) {
size.widthUnit = unit
}
props.onChangeSize( size )
} }
/>
) }
<div className="stk-img-resizer-wrapper" ref={ wrapperRef }>
<img
ref={ imageRef }
onLoad={ () => setHasImageError( false ) }
onError={ () => setHasImageError( true ) }
className={ imageClasses }
src={ src || undefined }
alt={ striptags( props.alt || undefined ) }
title={ striptags( props.title || undefined ) }
width={ props.width || undefined }
height={ props.height || undefined }
draggable="false"
/>
</div>
{ /* This is to make percentage heights work, see comment above about the issue in ResizableBox */ }
{ isResizing && tempStyle && <style>{ tempStyle }</style> }
{ ( isSelected && props.enableClickToEdit ) && (
<MediaUpload
onSelect={ image => {
// If image size is provided, return the URL of that size.
let {
url, width, height,
} = image
const currentSelectedSize = props.size || 'full'
if ( image.sizes && image.sizes[ currentSelectedSize ] ) {
url = image.sizes[ currentSelectedSize ].url
width = image.sizes[ currentSelectedSize ].width
height = image.sizes[ currentSelectedSize ].height
}
// If the image being selected is smaller than the
// current width of the image block, don't use 100%
// because the image will look blurry, instead use the
// actual width.
if ( isImageBlock && imageRef.current && ! props.hasManuallyChangedDimensions ) {
// When the image gets reset, we need to also reset
// the width unit to '' so that when we add another
// image, the image would not be small
props.onChangeSize( {
width: '',
widthUnit: '%',
} )
// We need the width of the image block to compare
const imageBlockWidth = wrapperRef.current.parentElement?.parentElement?.clientWidth ||
wrapperRef.current.clientWidth
if ( width < imageBlockWidth ) {
props.onChangeSize( {
width,
widthUnit: 'px',
} )
}
}
props.onChange( {
...image,
url,
width,
height,
} )
} }
allowedTypes={ props.allowedTypes }
value={ props.imageID }
render={ obj => {
// Show an invisible button on top of the image.
return (
<Button
className="stk-img-media-manager-button"
onClick={ () => obj.open() }
/>
)
} }
/>
) }
{ props.children }
</ResizableBox>
)
} )
Image.defaultProps = {
imageId: '',
enableClickToEdit: true,
showHandles: true,
showTooltips: true,
alt: '',
title: '',
src: '',
size: 'full',
width: '',
height: '',
widthUnit: '%',
heightUnit: 'px',
widthUnits: [ 'px', '%', 'vw' ],
heightUnits: [ 'px', '%', 'vh' ],
shape: '',
shapeStretch: false,
shadow: '',
allowedTypes: [ 'image' ],
// Resizers.
enableWidth: true,
enableHeight: true,
enableDiagonal: true,
widthResizePosition: 'right',
heightResizePosition: 'bottom',
allowReset: true,
hasGradientOverlay: false,
hasRemove: true,
hasTooltip: true,
onChange: () => {},
onRemove: () => {},
onChangeSize: () => {},
}
// Support responsive options.
const ImageResponsive = props => {
const deviceType = useDeviceType()
const isDesktop = deviceType === 'Desktop'
const isMobile = deviceType === 'Mobile'
let width = props.width
let widthUnit = props.widthUnit || '%'
if ( ! isDesktop && props.widthTablet !== '' ) {
width = props.widthTablet
widthUnit = props.widthUnitTablet
}
if ( isMobile && props.widthMobile !== '' ) {
width = props.widthMobile
widthUnit = props.widthUnitMobile
}
let height = props.height
let heightUnit = props.heightUnit || 'px'
if ( ! isDesktop && props.heightTablet !== '' ) {
height = props.heightTablet
if ( props.heightUnitTablet !== '' ) {
heightUnit = props.heightUnitTablet
}
}
if ( isMobile && props.heightMobile !== '' ) {
height = props.heightMobile
if ( props.heightUnitMobile !== '' ) {
heightUnit = props.heightUnitMobile
}
}
return (
<Image
{ ...props }
width={ width }
widthUnit={ widthUnit }
height={ height }
heightUnit={ heightUnit }
onChangeSize={ value => {
props[ `onChangeSize${ deviceType }` ]( value )
} }
/>
)
}
ImageResponsive.defaultProps = {
...Image.defaultProps,
widthTablet: '',
heightTablet: '',
widthUnitTablet: '',
heightUnitTablet: '',
widthMobile: '',
heightMobile: '',
widthUnitMobile: '',
heightUnitMobile: '',
onChangeSizeDesktop: () => {},
onChangeSizeTablet: () => {},
onChangeSizeMobile: () => {},
defaultWidth: '',
defaultHeight: '',
}
const ImageContent = props => {
const imageWrapperClasses = getImageWrapperClasses( props )
const imageClasses = getImageClasses( props )
const width = props.width || props.width === 0
? ( props.widthUnit === '%' ? `${ props.width }%` : props.width )
: undefined
const height = props.height || props.height === 0
? ( props.heightUnit === '%' ? `${ props.height }%` : props.height )
: undefined
const propsToPass = {}
const alt = striptags( props.alt || undefined )
if ( alt ) {
propsToPass.alt = alt
}
const title = striptags( props.title || undefined )
if ( title ) {
propsToPass.title = title
}
const figcaptionClassnames = classnames(
props.figcaptionClassnames,
'stk-img-figcaption'
)
// Allow a custom wrapper, mostly used to turn the image into an anchor
// link.
const Wrapper = props.customWrapper
const ConditionalWrapper = ( {
condition, children,
} ) =>
condition ? ( <Wrapper>{ children }</Wrapper> ) : children
let image = (
<img // eslint-disable-line jsx-a11y/alt-text
className={ imageClasses }
src={ props.src || undefined }
width={ width || undefined }
height={ height || undefined }
{ ...propsToPass }
/>
)
image = ! props.hasWrapper ? image : (
<span className={ imageWrapperClasses }>
{ image }
</span>
)
return (
applyFilters( 'stackable.image.save.wrapper',
( <figure className={ props.hasWrapper ? undefined : imageWrapperClasses }>
<ConditionalWrapper
condition={ !! props.customWrapper }
children={ image }
/>
{ props.figcaptionShow && props.src && <RichText.Content tagName="figcaption" className={ figcaptionClassnames } value={ props.figcaption } /> }
{ props.children }
</figure> ), props, imageWrapperClasses, image, figcaptionClassnames
)
)
}
ImageContent.defaultProps = {
imageId: '',
hasWrapper: false,
alt: '',
title: '',
src: '',
size: 'full',
width: '',
height: '',
widthUnit: 'px',
heightUnit: 'px',
shape: '',
shapeStretch: false,
shadow: '',
hasGradientOverlay: false,
customWrapper: null,
figcaptionShow: false,
figcaption: '',
}
ImageResponsive.Content = ImageContent
export default ImageResponsive