| 1 |
import React, { Component, Fragment } from 'react'; |
| 2 |
|
| 3 |
export default class PropertySize extends Component { |
| 4 |
constructor(props) { |
| 5 |
super(props); |
| 6 |
|
| 7 |
this.state = { |
| 8 |
number: '', |
| 9 |
unit: '', |
| 10 |
}; |
| 11 |
} |
| 12 |
|
| 13 |
changeNumber(number) { |
| 14 |
if ( number !== this.state.number ) { |
| 15 |
this.props.onValueChange(`${number}${this.state.unit}`); |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
changeUnit(unit) { |
| 20 |
if ( unit !== this.state.unit ) { |
| 21 |
this.props.onValueChange(`${this.state.number}${unit}`); |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
componentDidMount() { |
| 26 |
this.checkNumber(); |
| 27 |
} |
| 28 |
|
| 29 |
componentDidUpdate() { |
| 30 |
this.checkNumber(); |
| 31 |
} |
| 32 |
|
| 33 |
checkNumber() { |
| 34 |
const split = this.props.value.match(/([+-]?\d*\.?\d*)\s*([^;]*)/); |
| 35 |
|
| 36 |
const number = split ? split[1] : ''; |
| 37 |
const unit = split ? split[2] : ''; |
| 38 |
|
| 39 |
if ( number !== this.state.number || unit !== this.state.unit ) { |
| 40 |
this.setState({ |
| 41 |
number, |
| 42 |
unit, |
| 43 |
}); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
render() { |
| 48 |
let unitOptions = ['px', 'em']; |
| 49 |
|
| 50 |
if ( this.state.unit && ! unitOptions.includes(this.state.unit) ) { |
| 51 |
unitOptions.push(this.state.unit); |
| 52 |
} |
| 53 |
|
| 54 |
return ( |
| 55 |
<Fragment> |
| 56 |
<input |
| 57 |
className="wpupg-template-property-input" |
| 58 |
type="number" |
| 59 |
step={ 'px' === this.state.unit ? '1' : '0.1' } |
| 60 |
value={this.state.number} |
| 61 |
onChange={(e) => this.changeNumber(e.target.value)} |
| 62 |
/> |
| 63 |
{ |
| 64 |
unitOptions.map((unit, index) => ( |
| 65 |
<span |
| 66 |
className={ unit === this.state.unit ? 'wpupg-template-property-value-size-unit wpupg-template-property-value-size-unit-selected' : 'wpupg-template-property-value-size-unit' } |
| 67 |
onClick={() => this.changeUnit(unit)} |
| 68 |
key={index} |
| 69 |
>{unit}</span> |
| 70 |
)) |
| 71 |
} |
| 72 |
</Fragment> |
| 73 |
); |
| 74 |
} |
| 75 |
} |