|
| 1 | + |
| 2 | +import React from 'react'; |
| 3 | + |
| 4 | +const grey = '#CCC'; |
| 5 | +const offBackground = { |
| 6 | + top: 0, |
| 7 | + boxShadow: `inset 0 0 0px 1px ${grey}`, |
| 8 | + height: 0.6, |
| 9 | + width: 1 |
| 10 | +} |
| 11 | + |
| 12 | +const onBackground = { |
| 13 | + top: 0, |
| 14 | + height: 0.6 |
| 15 | +} |
| 16 | + |
| 17 | +const buttonStyle = { |
| 18 | + height: 0.6, |
| 19 | + width: 0.6, |
| 20 | + top: 0 |
| 21 | +} |
| 22 | + |
| 23 | +const commonStyles = { |
| 24 | + position: 'absolute', |
| 25 | + borderRadius: 0.3, |
| 26 | + transition: '0.1s ease-in-out' |
| 27 | +} |
| 28 | + |
| 29 | +export default class OnOff extends React.Component { |
| 30 | + constructor(props) { |
| 31 | + super(props); |
| 32 | + this.state = { |
| 33 | + on: !!props.on, // false if not set |
| 34 | + width: props.with || 100, |
| 35 | + buttonColor: props.buttonColor || '#FFFFFF', |
| 36 | + passiveColor: props.passiveColor || '#FFFFFF', |
| 37 | + activeColor: props.activeColor || '#13BF11' |
| 38 | + }; |
| 39 | + this.handleChange = this.handleChange.bind(this); |
| 40 | + this.onChange = props.onChange || (() => {}); |
| 41 | + } |
| 42 | + |
| 43 | + handleChange() { |
| 44 | + this.setState( |
| 45 | + {on: !this.state.on}, |
| 46 | + () => this.onChange(this.state.on) // callback to parent Component |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + setStyles(obj){ |
| 51 | + const styles = { |
| 52 | + ...obj, |
| 53 | + ...commonStyles |
| 54 | + } |
| 55 | + for (var key in styles) { |
| 56 | + if (typeof styles[key] == 'number') styles[key] = this.state.width * styles[key] + 'px'; |
| 57 | + } |
| 58 | + return styles; |
| 59 | + } |
| 60 | + |
| 61 | + render() { |
| 62 | + const on = this.state.on; |
| 63 | + |
| 64 | + const active = this.setStyles({ |
| 65 | + ...onBackground, |
| 66 | + width: on ? 1 : 0.6, |
| 67 | + background: this.state.activeColor |
| 68 | + }); |
| 69 | + const passive = this.setStyles({ |
| 70 | + ...offBackground, |
| 71 | + width: on ? 0.6 : 1, |
| 72 | + left: on ? 0.4 : 0, |
| 73 | + background: this.state.passiveColor |
| 74 | + }); |
| 75 | + const button = this.setStyles({ |
| 76 | + ...buttonStyle, |
| 77 | + background: this.state.buttonColor, |
| 78 | + left: on ? 0.4 : 0, |
| 79 | + boxShadow: `inset 0 0 0 1px ${on ? this.state.activeColor : grey}, 0 2px 4px ${grey}` |
| 80 | + }); |
| 81 | + |
| 82 | + return ( |
| 83 | + <div onClick={this.handleChange} style={{position: 'relative', height: 0.6 * this.state.width}}> |
| 84 | + <div style={active}/> |
| 85 | + <div style={passive} /> |
| 86 | + <div style={button}/> |
| 87 | + </div> |
| 88 | + ) |
| 89 | + } |
| 90 | +} |
0 commit comments