|
| 1 | +import React, { PropTypes } from 'react'; |
| 2 | + |
| 3 | +const noop = () => {}; |
| 4 | + |
| 5 | +export default class Keyframes extends React.Component { |
| 6 | + constructor (props) { |
| 7 | + super(props); |
| 8 | + this.state = { frameNum: -1 }; |
| 9 | + this.delayTimer = null; |
| 10 | + } |
| 11 | + |
| 12 | + shouldComponentUpdate (nextProps, nextState) { |
| 13 | + const { frameNum } = nextState; |
| 14 | + if (this.state.frameNum === frameNum) return false; |
| 15 | + return 0 <= frameNum && frameNum < this.props.children.length; |
| 16 | + } |
| 17 | + |
| 18 | + componentWillMount () { |
| 19 | + const frameNum = this.state.frameNum + 1; |
| 20 | + const frame = this.getFrame(frameNum); |
| 21 | + |
| 22 | + // render the first frame if it has no delay |
| 23 | + if (frame && !frame.props.delay) { |
| 24 | + this.setState({ frameNum }); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + componentDidMount () { |
| 29 | + this.requestNextFrame(); |
| 30 | + } |
| 31 | + |
| 32 | + componentDidUpdate () { |
| 33 | + this.requestNextFrame(); |
| 34 | + } |
| 35 | + |
| 36 | + componentWillUnmount () { |
| 37 | + clearTimeout(this.delayTimer); |
| 38 | + } |
| 39 | + |
| 40 | + render () { |
| 41 | + const frame = this.getFrame(); |
| 42 | + if (!frame) return null; |
| 43 | + |
| 44 | + const component = frame.props.component || this.props.component; |
| 45 | + return React.cloneElement(frame, { component }); |
| 46 | + } |
| 47 | + |
| 48 | + requestNextFrame () { |
| 49 | + const frameNum = this.state.frameNum + 1; |
| 50 | + const frame = this.getFrame(frameNum); |
| 51 | + if (!frame) { |
| 52 | + this.props.onEnd(); |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + const { delay } = frame.props; |
| 57 | + |
| 58 | + clearTimeout(this.delayTimer); |
| 59 | + this.delayTimer = setTimeout(() => { |
| 60 | + if (0 === frameNum) { |
| 61 | + this.props.onStart(); |
| 62 | + } |
| 63 | + this.setState({ frameNum }); |
| 64 | + }, delay); |
| 65 | + } |
| 66 | + |
| 67 | + getFrame (frameNum = this.state.frameNum) { |
| 68 | + return this.props.children[frameNum]; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +Keyframes.propTypes = { |
| 73 | + children: PropTypes.element.isRequired, |
| 74 | + component: PropTypes.string, |
| 75 | + onStart: PropTypes.func, |
| 76 | + onEnd: PropTypes.func |
| 77 | +}; |
| 78 | + |
| 79 | +Keyframes.defaultProps = { |
| 80 | + component: 'span', |
| 81 | + onStart: noop, |
| 82 | + onEnd: noop |
| 83 | +}; |
0 commit comments