All files loading_bar.js

97.14% Statements 34/35
100% Branches 13/13
50% Functions 1/2
100% Lines 34/34
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 1001x 1x   1x 1x 1x     39x     13x         13x       13x       6x 4x         13x 13x   13x 10x     13x       13x 13x   13x 1x 1x 1x 12x 11x     13x       33x       33x               33x 13x   20x     33x             1x             1x           1x          
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
 
export const UPDATE_TIME = 400
export const MAX_PROGRESS = 90
export const PROGRESS_INCREASE = 10
 
export class LoadingBar extends React.Component {
  constructor(props) {
    super(props)
 
    this.state = {
      percent: 0,
      interval: null,
    }
 
    this.onSimulateProgress = this.simulateProgress.bind(this)
  }
 
  componentWillMount() {
    this.launch()
  }
 
  componentWillReceiveProps(nextProps) {
    if (nextProps.loading > this.props.loading) {
      this.launch()
    }
  }
 
  launch() {
    let interval = this.state.interval
    const percent = this.state.percent
 
    if (!interval) {
      interval = setInterval(this.onSimulateProgress, UPDATE_TIME)
    }
 
    this.setState({ percent, interval })
  }
 
  simulateProgress() {
    let interval = this.state.interval
    let percent = this.state.percent
 
    if (this.props.loading === 0) {
      clearInterval(interval)
      interval = null
      percent = 0
    } else if (percent < MAX_PROGRESS) {
      percent = percent + PROGRESS_INCREASE
    }
 
    this.setState({ percent, interval })
  }
 
  shouldShow(percent) {
    return (percent > 0) && (percent <= 100) && (this.props.loading !== 0)
  }
 
  render() {
    let loadingStyle = {
      height: this.props.height,
      width: `${this.state.percent}%`,
      backgroundColor: this.props.color,
      transition: 'width 400ms ease-out, height 400ms linear',
      position: 'absolute',
    }
 
    if (this.shouldShow(this.state.percent)) {
      loadingStyle.display = 'block'
    } else {
      loadingStyle.display = 'none'
    }
 
    return (
      <div style={loadingStyle}>
      </div>
    )
  }
}
 
LoadingBar.propTypes = {
  color: PropTypes.string,
  height: PropTypes.string,
  actions: PropTypes.object,
  loading: PropTypes.number,
}
 
LoadingBar.defaultProps = {
  color: 'red',
  height: '3px',
  loading: 0,
}
 
const mapStateToProps = (state) => ({
  loading: state.loading,
})
 
export default connect(mapStateToProps)(LoadingBar)