aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/components/dropdowns/simple-dropdown.js
blob: bba088ed1d285ce40c4f3f56e3d52cfd85f58308 (plain) (blame)
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
const { Component } = require('react')
const PropTypes = require('prop-types')
const h = require('react-hyperscript')
const classnames = require('classnames')
const R = require('ramda')

class SimpleDropdown extends Component {
  constructor (props) {
    super(props)
    this.state = {
      isOpen: false,
    }
  }

  getDisplayValue () {
    const { selectedOption, options } = this.props
    const matchesOption = option => option.value === selectedOption
    const matchingOption = R.find(matchesOption)(options)
    return matchingOption
      ? matchingOption.displayValue || matchingOption.value
      : selectedOption
  }

  handleClose () {
    this.setState({ isOpen: false })
  }

  toggleOpen () {
    const { isOpen } = this.state
    this.setState({ isOpen: !isOpen })
  }

  renderOptions () {
    const { options, onSelect, selectedOption } = this.props

    return h('div', [
      h('div.simple-dropdown__close-area', {
        onClick: event => {
          event.stopPropagation()
          this.handleClose()
        },
      }),
      h('div.simple-dropdown__options', [
        ...options.map(option => {
          return h(
            'div.simple-dropdown__option',
            {
              className: classnames({
                'simple-dropdown__option--selected': option.value === selectedOption,
              }),
              key: option.value,
              onClick: () => {
                if (option.value !== selectedOption) {
                  onSelect(option.value)
                }

                this.handleClose()
              },
            },
            option.displayValue || option.value,
          )
        }),
      ]),
    ])
  }

  render () {
    const { placeholder } = this.props
    const { isOpen } = this.state

    return h(
      'div.simple-dropdown',
      {
        onClick: () => this.toggleOpen(),
      },
      [
        h('div.simple-dropdown__selected', this.getDisplayValue() || placeholder || 'Select'),
        h('i.fa.fa-caret-down.fa-lg.simple-dropdown__caret'),
        isOpen && this.renderOptions(),
      ]
    )
  }
}

SimpleDropdown.propTypes = {
  options: PropTypes.array.isRequired,
  placeholder: PropTypes.string,
  onSelect: PropTypes.func,
  selectedOption: PropTypes.string,
}

module.exports = SimpleDropdown