Skip to content

Instantly share code, notes, and snippets.

@Polyrhythm
Created August 16, 2016 21:53
Show Gist options
  • Save Polyrhythm/2c13bea9ef69cdd8c704db459107e7d3 to your computer and use it in GitHub Desktop.
Save Polyrhythm/2c13bea9ef69cdd8c704db459107e7d3 to your computer and use it in GitHub Desktop.
import React, { Component, PropTypes } from 'react';
import { Motion, spring } from 'react-motion';
import { isGesture } from 'shared/util/gesture';
const styles = {
spring: {
strength: 150,
damping: 10,
},
button: {
minScale: 0.75,
}
};
export default class PressButton extends Component {
static propTypes = {
isPressed: PropTypes.bool,
onTouch: PropTypes.func,
style: PropTypes.object,
children: PropTypes.element,
};
static defaultProps = {
style: {},
};
constructor(props) {
super(props);
this.state = {
isPressed: false,
touch: null,
};
}
handleTouchStart(e) {
e.stopPropagation();
const { clientX, clientY } = e.touches[0];
this.setState({
isPressed: true,
touch: { clientX, clientY },
});
}
handleTouchEnd(e) {
e.preventDefault();
const { clientX, clientY } = e.changedTouches[0];
const startTouch = this.state.touch || { clientX: 0, clientY: 0 };
if (!isGesture(startTouch.clientX, clientX, startTouch.clientY, clientY)) {
this.props.onTouch();
}
this.setState({ isPressed: false, touch: null });
}
render() {
const springScale = this.state.isPressed ? styles.button.minScale : 1;
const motionStyle = { scale: spring(springScale, [styles.spring.strength, styles.spring.damping]) };
return <Motion
defaultStyle={{scale: 1}}
style={motionStyle}>
{({ scale }) => <button
className={this.props.className}
onTouchStart={this.handleTouchStart.bind(this)}
onTouchEnd={this.handleTouchEnd.bind(this)}
style={{
transform: `scale(${scale})`,
WebkitTransform: `scale(${scale})`,
...this.props.style,
}}>
{this.props.children}
</button>}
</Motion>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment