All files index.js

68.37% Statements 67/98
34.78% Branches 16/46
66.67% Functions 14/21
55.1% Lines 27/49
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 2071x 1x 1x 1x 1x 1x 12x   1x   6x                                                                                                                             10x 10x                       1x 1x                 1x           1x     1x 1x       1x 1x     1x 1x 1x                                                                                                                               3x 10x     2x                                   10x     1x  
import stableStringify from 'json-stable-stringify'
import {autocomplete as mapzenAutocomplete, reverse as reverseSearch} from 'isomorphic-mapzen-search'
import isEqual from 'lodash/isEqual'
import throttle from 'lodash/throttle'
import PropTypes from 'prop-types'
import React, {Component} from 'react'
import Select from 'react-select'
 
const GEOLOCATE_VALUE = 'geolocate'
 
class Geocoder extends Component {
  static propTypes = {
    apiKey: PropTypes.string.isRequired,
    boundary: PropTypes.object,
    featureToLabel: PropTypes.func,
    featureToValue: PropTypes.func,
    findingLocationText: PropTypes.string,
    focusPoint: PropTypes.any,
    geolocate: PropTypes.bool,
    onChange: PropTypes.func,
    placeholder: PropTypes.string,
    rateLimit: PropTypes.number,
    reverseSearch: PropTypes.func,
    search: PropTypes.func,
    useLocationText: PropTypes.string,
    value: PropTypes.object
  }
 
  static defaultProps = {
    featureToLabel: (feature) => feature.properties.label,
    featureToValue: (feature) => `${feature.properties.label}-${feature.geometry.coordinates.join(',')}`,
    findingLocationText: 'Locating you...',
    reverseSearch,
    search: mapzenAutocomplete,
    useLocationText: 'Use Current Location'
  }
 
  autocompleteCache = {}
 
  options = {}
 
  state = {
    options: this.defaultOptions(),
    value: this.props.value || null
  }
 
  cacheOptions (options) {
    options.forEach((o) => {
      this.options[o.value] = o.feature
    })
  }
 
  componentWillMount () {
    this._throttledLoadOptions = throttle(this.loadOptions, this.props.rateLimit || 500)
  }
 
  componentWillReceiveProps (nextProps) {
    if (!isEqual(nextProps.value, this.props.value)) {
      this.setState({value: nextProps.value})
    }
 
    if (this.props.rateLimit !== nextProps.rateLimit) {
      this._throttledLoadOptions = throttle(this.loadOptions, this.props.rateLimit || 500)
    }
  }
 
  defaultOptions () {
    return this.props.geolocate && 'geolocation' in navigator
      ? [{label: this.props.useLocationText, value: GEOLOCATE_VALUE}]
      : []
  }
 
  featureToOption = (feature) => {
    const {featureToLabel, featureToValue} = this.props
    return {
      feature,
      label: featureToLabel(feature),
      value: featureToValue(feature)
    }
  }
 
  focus () {
    this.select.focus()
  }
 
  loadOptions = (input, callback) => {
    const {apiKey, boundary, focusPoint, geolocate, search} = this.props
    ifI (!input) {
      if (geolocate && 'geolocation' in navigator) {
        callback(null, {
          options: this.defaultOptions()
        })
      } else {
        callback(null)
      }
    } else {
      const autocompleteQuery = {
        apiKey,
        boundary,
        focusPoint,
        text: input
      }
      const autocompleteQueryKey = stableStringify(autocompleteQuery)
 
      // check if autocomplete query has been made before
      const cacheValue = this.autocompleteCache[autocompleteQueryKey]
      ifI (cacheValue) {
        return callback(null, cacheValue)
      }
 
      search(autocompleteQuery).then((geojson) => {
        const options = geojson && geojson.features
          ? geojson.features.map(this.featureToOption)
          : []
        this.cacheOptions(options)
        this.autocompleteCache[autocompleteQueryKey] = {options}
        callback(null, {options})
      }).catch((error) => {
        callback(error)
      })
    }
  }
 
  _onChange = (value) => {
    const {apiKey, findingLocationText, onChange, reverseSearch} = this.props
    if (value && value.value === GEOLOCATE_VALUE) {
      this.setState({
        ...this.state,
        value: {
          label: findingLocationText
        }
      })
      window.navigator.geolocation.getCurrentPosition((position) => {
        reverseSearch({
          apiKey,
          point: position.coords
        }).then((geojson) => {
          const value = this.featureToOption(geojson.features[0])
          this.setState({
            ...this.state,
            value
          })
          onChange && onChange(value)
        }).catch((err) => {
          console.error('Error during reverse lookup of', position)
          console.error(err)
          const value = this.featureToOption({
            type: 'Feature',
            properties: {
              label: `${position.longitude}, ${position.latitude}`
            },
            geometry: {
              type: 'Point',
              coordinates: [
                position.longitude,
                position.latitude
              ]
            }
          })
          this.setState({
            ...this.state,
            value
          })
          onChange && onChange(value)
        })
      })
    } else {
      if (!value) {
        this.setState({
          options: this.defaultOptions(),
          value
        })
      } else {
        this.setState({value})
      }
      this.props.onChange && this.props.onChange(value && this.options[value.value])
    }
  }
 
  _saveRef = (select) => {
    this.select = select
  }
 
  render () {
    return (
      <Select.Async
        autoBlur
        autoload={false}
        cache={false}
        filterOptions={false}
        ignoreAccents={false}
        ignoreCase={false}
        loadOptions={this._throttledLoadOptions}
        minimumInput={3}
        options={this.state.options}
        {...this.props}
        onChange={this._onChange}
        ref={this._saveRef}
        value={this.state.value}
        onBlurResetsInput={false}
        />
    )
  }
}
 
module.exports = Geocoder