| 1 |
/* eslint-disable no-nested-ternary */ |
| 2 |
|
| 3 |
import { useEffect, useState } from '@wordpress/element'; |
| 4 |
|
| 5 |
export default function useDimensionHandler( |
| 6 |
customHeight, |
| 7 |
customWidth, |
| 8 |
defaultHeight, |
| 9 |
defaultWidth, |
| 10 |
onChange |
| 11 |
) { |
| 12 |
const [ currentWidth, setCurrentWidth ] = useState( |
| 13 |
customWidth ? customWidth : defaultWidth ? defaultWidth : '' |
| 14 |
); |
| 15 |
const [ currentHeight, setCurrentHeight ] = useState( |
| 16 |
customHeight ? customHeight : defaultHeight ? defaultHeight : '' |
| 17 |
); |
| 18 |
|
| 19 |
// When an image is first inserted, the default dimensions are initially |
| 20 |
// undefined. This effect updates the dimensions when the default values |
| 21 |
// come through. |
| 22 |
useEffect( () => { |
| 23 |
if ( customWidth === undefined && defaultWidth !== undefined ) { |
| 24 |
setCurrentWidth( defaultWidth ); |
| 25 |
} |
| 26 |
if ( customHeight === undefined && defaultHeight !== undefined ) { |
| 27 |
setCurrentHeight( defaultHeight ); |
| 28 |
} |
| 29 |
}, [ defaultWidth, defaultHeight ] ); |
| 30 |
|
| 31 |
// If custom values change, it means an outsider has resized the image using some other method (eg resize box) |
| 32 |
// this keeps track of these values too. We need to parse before comparing; custom values can be strings. |
| 33 |
useEffect( () => { |
| 34 |
if ( |
| 35 |
customWidth !== undefined && |
| 36 |
Number.parseInt( customWidth ) !== Number.parseInt( currentWidth ) |
| 37 |
) { |
| 38 |
setCurrentWidth( customWidth ); |
| 39 |
} |
| 40 |
if ( |
| 41 |
customHeight !== undefined && |
| 42 |
Number.parseInt( customHeight ) !== Number.parseInt( currentHeight ) |
| 43 |
) { |
| 44 |
setCurrentHeight( customHeight ); |
| 45 |
} |
| 46 |
}, [ customWidth, customHeight ] ); |
| 47 |
|
| 48 |
const updateDimension = ( dimension, value ) => { |
| 49 |
if ( dimension === 'width' ) { |
| 50 |
setCurrentWidth( value ); |
| 51 |
} else { |
| 52 |
setCurrentHeight( value ); |
| 53 |
} |
| 54 |
onChange( { |
| 55 |
[ dimension ]: value === '' ? undefined : parseInt( value, 10 ), |
| 56 |
} ); |
| 57 |
}; |
| 58 |
|
| 59 |
const updateDimensions = ( nextHeight, nextWidth ) => { |
| 60 |
setCurrentHeight( nextHeight ? nextHeight : defaultHeight ? defaultHeight : '' ); |
| 61 |
setCurrentHeight( nextWidth ? nextWidth : defaultWidth ? defaultWidth : '' ); |
| 62 |
onChange( { height: nextHeight, width: nextWidth } ); |
| 63 |
}; |
| 64 |
|
| 65 |
return { |
| 66 |
currentHeight, |
| 67 |
currentWidth, |
| 68 |
updateDimension, |
| 69 |
updateDimensions, |
| 70 |
}; |
| 71 |
} |
| 72 |
|