|
| 1 | +import React from 'react'; |
| 2 | +import {throttle} from 'lodash' |
| 3 | +import {Motion, spring} from 'react-motion' |
| 4 | + |
| 5 | +let CardScroll = React.createClass({ |
| 6 | + getInitialState(){ |
| 7 | + return {currentLeft: 0, currentCard: 0} |
| 8 | + }, |
| 9 | + |
| 10 | + componentDidMount() { |
| 11 | + window.addEventListener('resize', throttle(() => this.scrollCards({number: 0}))); |
| 12 | + }, |
| 13 | + |
| 14 | + render() { |
| 15 | + const {currentLeft} = this.state |
| 16 | + const updateRow = c => { |
| 17 | + if (c) { |
| 18 | + this._row = c |
| 19 | + } |
| 20 | + } |
| 21 | + return ( |
| 22 | + <div className="scroll-container flex-item"> |
| 23 | + <div style={{position: "fixed", left: 0, top: "50%", zIndex: 1}} |
| 24 | + onClick={this.scrollCardsWrap({toLeft: true})}>{"<"}</div> |
| 25 | + <div style={{position: "fixed", right: 0, top: "50%", zIndex: 1}} |
| 26 | + onClick={this.scrollCardsWrap()}>{">"}</div> |
| 27 | + <Motion style={{left: spring(currentLeft)}}> |
| 28 | + {value => { |
| 29 | + Object.assign(value, { |
| 30 | + flexWrap: "nowrap", |
| 31 | + position: "relative" |
| 32 | + }) |
| 33 | + return ( |
| 34 | + <div className="row" |
| 35 | + style={value} |
| 36 | + ref={c => updateRow(c)}> |
| 37 | + {this.props.children} |
| 38 | + </div>) |
| 39 | + } |
| 40 | + } |
| 41 | + </Motion> |
| 42 | + </div> |
| 43 | + ) |
| 44 | + }, |
| 45 | + |
| 46 | + scrollCardsWrap(params){ |
| 47 | + return () => { |
| 48 | + this.scrollCards(params) |
| 49 | + } |
| 50 | + }, |
| 51 | + //TODO write TESTS!!! |
| 52 | + scrollCards({toLeft=false, number=1}={}){ |
| 53 | + if (toLeft && this.state.currentCard - number < 0) { |
| 54 | + // gonna scroll too much to the left so just scroll to the first card |
| 55 | + number = this.state.currentCard |
| 56 | + } |
| 57 | + const cardWidth = this.props.getCardWidth() |
| 58 | + const visibleCardCount = Math.floor(this._row.clientWidth / cardWidth) |
| 59 | + const cardCount = this.props.getCardCount() |
| 60 | + if (!toLeft && this.state.currentCard + visibleCardCount + number > cardCount) { |
| 61 | + // gonna scroll too much to the right so scroll so the last card is at the right |
| 62 | + number = -this.state.currentCard + cardCount - visibleCardCount |
| 63 | + } |
| 64 | + let currentCard = this.state.currentCard + (toLeft ? -number : number) |
| 65 | + if (currentCard < 0) { |
| 66 | + // case where we wanna display last card at the right but not enough cards |
| 67 | + currentCard = 0 |
| 68 | + } |
| 69 | + const currentLeft = -currentCard * cardWidth |
| 70 | + this.setState({currentLeft, currentCard}) |
| 71 | + } |
| 72 | +}) |
| 73 | + |
| 74 | +export default CardScroll; |
0 commit comments