Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@idmontie
Created April 8, 2018 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idmontie/edc2dcc56e3e9d9d7cc604a95364bfa8 to your computer and use it in GitHub Desktop.
Save idmontie/edc2dcc56e3e9d9d7cc604a95364bfa8 to your computer and use it in GitHub Desktop.
const tween = ({ tween, duration = 1000, defaultStart, end }) => (BaseComponent) => {
return class Tween extends Component {
constructor(props) {
super(props);
this.state = {
timeStart: +new Date(),
start: defaultStart(props) || 0,
current: defaultStart(props) || 0,
};
this.calculate = this._calculate.bind(this);
}
componentDidMount() {
this.timer = setInterval(this.calculate, 1000 / 60);
}
componentWillUnmount() {
if (this.timer) {
clearInterval(this.timer);
}
}
componentWillReceiveProps(nextProps) {
if (end(nextProps) !== end(this.props)) {
this.setState((state) => ({
timeStart: +new Date(),
start: state.current,
}));
}
}
_calculate() {
const { timeStart, start } = this.state;
const time = +new Date() - timeStart;
if (time > duration) {
this.setState(() => ({
current: end(this.props),
}));
return;
}
const currentPosition = tween(time, start, end(this.props) - start, duration);
this.setState(() => ({
current: currentPosition,
}));
}
render() {
const { current } = this.state;
return <BaseComponent {...this.props} current={current} />
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment