| 1 |
import { FocalPointPicker } from '@wordpress/components'; |
| 2 |
|
| 3 |
const imgCache = {}; |
| 4 |
|
| 5 |
/** |
| 6 |
* Convert background size tp focal point object value |
| 7 |
* |
| 8 |
* @param {string} size - background size. |
| 9 |
* |
| 10 |
* @return {Object} background size object. |
| 11 |
*/ |
| 12 |
function sizeToPoint(size) { |
| 13 |
const sizes = size.split(' '); |
| 14 |
const result = { |
| 15 |
x: 0.5, |
| 16 |
y: 0.5, |
| 17 |
}; |
| 18 |
|
| 19 |
if (!sizes[0]) { |
| 20 |
return result; |
| 21 |
} |
| 22 |
|
| 23 |
if (!sizes[1]) { |
| 24 |
sizes.push(sizes[0]); |
| 25 |
} |
| 26 |
|
| 27 |
result.x = Math.max(Math.min(parseFloat(sizes[0]) / 100, 1), 0); |
| 28 |
result.y = Math.max(Math.min(parseFloat(sizes[1]) / 100, 1), 0); |
| 29 |
|
| 30 |
return result; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Parse string with image tag and retreive image src. |
| 35 |
* |
| 36 |
* @param {string} image - image tag in string |
| 37 |
* |
| 38 |
* @return {string} - image src |
| 39 |
*/ |
| 40 |
function parseImageUrl(image) { |
| 41 |
if (typeof imgCache[image] !== 'undefined') { |
| 42 |
return imgCache[image]; |
| 43 |
} |
| 44 |
|
| 45 |
// <img> tag |
| 46 |
let src = /<img\s[^>]*?src\s*=\s*['"]([^'"]*?)['"][^>]*?>/g.exec(image); |
| 47 |
|
| 48 |
if (src && src[1]) { |
| 49 |
imgCache[image] = src[1]; |
| 50 |
return src[1]; |
| 51 |
} |
| 52 |
|
| 53 |
// <div> tag with background image style. |
| 54 |
const style = /<div\s[^>]*?style\s*=\s*['"]([^'"]*?)['"][^>]*?>/g.exec( |
| 55 |
image |
| 56 |
); |
| 57 |
|
| 58 |
if (style && style[1]) { |
| 59 |
src = style[1] |
| 60 |
.replace('background-image: url("', '') |
| 61 |
.replace('background-image: url("', '') |
| 62 |
.replace('");', '') |
| 63 |
.replace('");', ''); |
| 64 |
|
| 65 |
if (src) { |
| 66 |
imgCache[image] = src; |
| 67 |
return src; |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
imgCache[image] = false; |
| 72 |
return false; |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* Component Class. |
| 77 |
* |
| 78 |
* @param props |
| 79 |
*/ |
| 80 |
export default function CustomFocalPointPicker(props) { |
| 81 |
const { value, onChange, label, image } = props; |
| 82 |
|
| 83 |
let imageUrl = ''; |
| 84 |
|
| 85 |
if (!image) { |
| 86 |
return null; |
| 87 |
} |
| 88 |
|
| 89 |
imageUrl = parseImageUrl(image); |
| 90 |
|
| 91 |
if (!imageUrl) { |
| 92 |
return null; |
| 93 |
} |
| 94 |
|
| 95 |
const focalPointValue = sizeToPoint(value); |
| 96 |
|
| 97 |
return ( |
| 98 |
<FocalPointPicker |
| 99 |
label={label} |
| 100 |
url={imageUrl} |
| 101 |
value={focalPointValue} |
| 102 |
onChange={(val) => { |
| 103 |
onChange( |
| 104 |
`${parseInt(100 * val.x, 10)}% ${parseInt( |
| 105 |
100 * val.y, |
| 106 |
10 |
| 107 |
)}%` |
| 108 |
); |
| 109 |
}} |
| 110 |
/> |
| 111 |
); |
| 112 |
} |
| 113 |
|