import { createElement, Component, useState } from '@wordpress/element' import { __ } from 'ct-i18n' import InputWithOnlyNumbers from '../components/InputWithOnlyNumbers' import cls from 'classnames' import OutsideClickHandler from './react-outside-click-handler' const Spacing = ({ value, option, onChange }) => { const [isOpen, setIsOpen] = useState(false) const units = [ { unit: 'px' }, { unit: '%' }, { unit: 'em' }, { unit: 'rem' }, { unit: 'pt' } ] const withDefault = (currentUnit, defaultUnit) => units.find(({ unit }) => unit === currentUnit) ? currentUnit : currentUnit || units[0].unit const getLinkedLeader = () => ['top', 'right', 'bottom', 'left'].find(v => value[v] !== 'auto') const getCurrentUnit = () => withDefault( value[getLinkedLeader()] .toString() .replace(/[0-9]/g, '') .replace(/\./g, '') ) const getNumericValue = (value, unit = '') => { if (value === 'auto') { return value } return `${parseFloat(value) === 0 ? 0 : parseFloat(value) || ''}${unit}` } const handleChange = (futureValue, position) => { if (value.linked) { onChange({ ...value, top: value.top === 'auto' ? value.top : getNumericValue(futureValue, getCurrentUnit()), left: value.left === 'auto' ? value.left : getNumericValue(futureValue, getCurrentUnit()), right: value.right === 'auto' ? value.right : getNumericValue(futureValue, getCurrentUnit()), bottom: value.bottom === 'auto' ? value.bottom : getNumericValue(futureValue, getCurrentUnit()) }) return } onChange({ ...value, [position]: getNumericValue(futureValue, getCurrentUnit()) }) } return (
{['top', 'right', 'bottom', 'left'].map(side => ( handleChange(v, side)} {...{ placeholder: '', ...option.inputAttr }} /> { { top: __('Top', 'blocksy'), bottom: __('Bottom', 'blocksy'), left: __('Left', 'blocksy'), right: __('Right', 'blocksy') }[side] } ))}
{ e.preventDefault() if (value.linked) { onChange({ ...value, linked: false }) return } const futureValue = value[getLinkedLeader()] onChange({ ...value, top: value.top !== 'auto' ? futureValue : value.top, left: value.left !== 'auto' ? futureValue : value.left, bottom: value.bottom !== 'auto' ? futureValue : value.bottom, right: value.right !== 'auto' ? futureValue : value.right, linked: true }) }}> {value.linked ? ( ) : ( )}
setIsOpen(!isOpen)} className="ct-current-value"> {getCurrentUnit() || '―'}
{ if (!isOpen) { return } setIsOpen(false) }}>
    {units .filter(({ unit }) => unit !== getCurrentUnit()) .reduce( (current, el, index) => [ ...current.slice( 0, index % 2 === 0 ? undefined : -1 ), ...(index % 2 === 0 ? [[el]] : [ [ current[ current.length - 1 ][0], el ] ]) ], [] ) .map(group => (
  • {group.map(({ unit }) => ( { onChange({ ...value, top: getNumericValue( value.top, unit ), left: getNumericValue( value.left, unit ), right: getNumericValue( value.right, unit ), bottom: getNumericValue( value.bottom, unit ) }) setIsOpen(false) }}> {unit || '―'} ))}
  • ))}
) } export default Spacing