All files / select index.js

98.11% Statements 52/53
93.75% Branches 30/32
100% Functions 4/4
98.04% Lines 50/51
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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215  1x 1x 1x     1x 1x 1x 1x     1x                                                         8x     8x             4x     4x             12x 12x                       24x     24x     72x 36x 36x 36x 36x   36x 60x                         94x                                                                         8x     8x 8x   8x 3x 3x               1x 1x           128x 64x     64x   64x 64x   6x   58x       64x 58x   15x 43x   14x 29x   14x       64x         64x   124x       525x                              
 
import React from 'react'
import {Motion, spring} from 'react-motion'
import objectAssign from 'object-assign'
 
// CSS space
const PADDING_TOP = 12
const PADDING_TOP_WITH_LABEL = -12
const PADDING_LEFT = 16
const LIST_ITEM_HEIGHT = 48
 
// list length
const MAX_LIST_LENGTH = 5
 
/**
 * Select component
 */
export default class Select extends React.Component {
 
  static propTypes = {
    label: React.PropTypes.string,
    items: React.PropTypes.array,
    placeholder: React.PropTypes.string,
    onChange: React.PropTypes.func.isRequired,
    selectedIndex: React.PropTypes.number
  }
 
  static defaultProps = {
    items: ['one', 'two', 'three'],
    placeholder: 'Placeholder',
    selectedIndex: -1
  }
 
  state = {
    open: false
  }
 
  /**
   * Show list
   */
  open = () => {
    this.setState({
      open: true
    })
    document.addEventListener('click', this.close)
  }
 
  /**
   * Hide list
   */
  close = () => {
    this.setState({
      open: false
    })
    document.removeEventListener('click', this.close)
  }
 
  /**
   * Make dropdown list as wide as parent placeholder including caret
   */
  componentDidMount () {
    const selectRect = this.ref.getBoundingClientRect()
    this.setState({
      width: selectRect.width
    })
  }
 
  /**
   * Component should not update when it is open. In that case it should
   * only update when open state changes.
   * It should not update itself when list is open and value comes in again.
   * This would causes scrolling and that would irritate the user.
   */
  shouldComponentUpdate (nextProps, nextState) {
    Iif (this.state.open && (nextState.open === this.state.open)) {
      return false
    }
    return true
  }
 
  render () {
    const {selectedIndex, label} = this.props
    const {open} = this.state
    const empty = selectedIndex === -1
    const text = empty ? this.props.placeholder : this.props.items[selectedIndex]
 
    return (
      <div className='Select' ref={(c) => { this.ref = c }}>
        {label &&
          <span className='Select-label'>{this.props.label}</span>
        }
        <button className='Select-body' onClick={this.open}>
          <span className={empty ? 'Select-placeholder' : ''}>
            {text}
          </span>
          <span className='Select-caret' />
        </button>
        <Motion style={{
          opacity: spring(open ? 1 : 0)
        }}>
          {style =>
            open &&
              <List
                style={{
                  opacity: style.opacity
                }}
                hasLabel={!!this.props.label}
                items={this.props.items}
                selectedIndex={selectedIndex}
                onClick={this.props.onChange}
                width={this.state.width}
              />
          }
        </Motion>
      </div>
    )
  }
 
}
 
/**
 * List component
 */
class List extends React.Component {
 
  static propTypes = {
    hasLabel: React.PropTypes.bool,
    items: React.PropTypes.array.isRequired,
    selectedIndex: React.PropTypes.number.isRequired,
    onClick: React.PropTypes.func.isRequired,
    width: React.PropTypes.number
  }
 
  /**
   * Scroll to correct list item
   */
  componentDidMount () {
    const index = this.props.selectedIndex
 
    // create boolean helper variables
    const scrollable = this.props.items.length > MAX_LIST_LENGTH
    const indexWithinFirstTwoItems = index < 2
 
    if (scrollable && !indexWithinFirstTwoItems) {
      const scrollTop = (LIST_ITEM_HEIGHT * (index - 2))
      this.ref.scrollTop = scrollTop
    }
  }
 
  /**
   * Handle click on list item
   */
  onClick = (index, event) => {
    event.preventDefault()
    this.props.onClick(index)
  }
 
  /**
   * Render list component
   */
  render () {
    const {items, selectedIndex} = this.props
 
    // handle list absolute position top
    const paddingTop = this.props.hasLabel ? PADDING_TOP_WITH_LABEL : PADDING_TOP
 
    let top
    if (selectedIndex === -1) {
      // set position to first element, i.e. selectedIndex = 0
      top = -1 * paddingTop
    } else {
      top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * selectedIndex))
    }
 
    // handle scrollable lists with more than 5 list items
    if (items.length > MAX_LIST_LENGTH) {
      if (selectedIndex >= 2 && selectedIndex <= items.length - 3) {
        // handle "center" items => always set to third position
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 2))
      } else if (selectedIndex === items.length - 2) {
        // handle second last item
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 3))
      } else if (selectedIndex === items.length - 1) {
        // handle last item
        top = -1 * (paddingTop + (LIST_ITEM_HEIGHT * 4))
      }
    }
 
    const style = {
      top: top,
      width: this.props.width + (2 * PADDING_LEFT)
    }
 
    return (
      <ul
        ref={(c) => { this.ref = c }}
        className='Select-list'
        style={objectAssign(style, this.props.style)}
      >
        {items.map((item, i) =>
          <li key={i} className='Select-listItem'>
            <a href
              className='Select-listItemLink'
              onClick={this.onClick.bind(this, i)}
            >
              {item}
            </a>
          </li>
        )}
      </ul>
    )
  }
 
}