Last active
November 19, 2015 17:50
-
-
Save souporserious/373fde69183228f92a30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Slide extends Component { | |
render() { | |
const { children, isCurrent, isOutgoing } = this.props | |
const child = Children.only(children) | |
let style = { | |
position: 'absolute', | |
top: 0, | |
left: 0 | |
} | |
if (isOutgoing) { | |
style.transform = 'translateX(-100%)' | |
} | |
if (isCurrent) { | |
style.position = '' | |
} | |
const dest = isCurrent ? 0 : 100 | |
return createElement( | |
Motion, | |
{ | |
style: { | |
x: spring(dest) | |
} | |
}, | |
({x}) => { | |
if (isOutgoing && x === dest) { | |
this.props.onSlideEnd() | |
} | |
return cloneElement(child, {style}) | |
} | |
) | |
} | |
} | |
class Slider extends Component { | |
static defaultProps = { | |
component: 'div' | |
} | |
state = { | |
current: 0, | |
outgoing: [] | |
} | |
next() { | |
this.slide('next') | |
} | |
slide(direction) { | |
const { current, outgoing } = this.state | |
direction = (direction === 'prev') ? -1 : 1 | |
this.setState({ | |
current: current + direction, | |
outgoing: outgoing.concat([current]) | |
}) | |
} | |
_handleSlideEnd(index) { | |
const outgoing = this.state.outgoing.slice(0) | |
const pos = outgoing.indexOf(index) | |
if (pos > -1) { | |
outgoing.splice(pos, 1) | |
this.setState({outgoing}) | |
} | |
} | |
render() { | |
const { component, children } = this.props | |
const { current, outgoing } = this.state | |
const childrenToRender = Children.map(children, (child, i) => { | |
const isCurrent = (current === i) | |
const isOutgoing = (outgoing.indexOf(i) > -1) | |
return ( | |
(isCurrent || isOutgoing) && | |
createElement( | |
Slide, | |
{ | |
isCurrent, | |
isOutgoing, | |
onSlideEnd: this._handleSlideEnd.bind(this, i) | |
}, | |
child | |
) | |
) | |
}) | |
return createElement( | |
component, | |
{ | |
className: 'slider' | |
}, | |
childrenToRender | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment