summaryrefslogtreecommitdiff
path: root/scraper/client/common/autocomplete.component.js
blob: 67dc78c969aca59e5e7c1a51fb407894f85caabd (plain)
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
216
217
218
219
220
221
222
223
224
225
226
227
228
import React, { Component } from 'react'
// import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

function formatLabel(label, value) {
  if (!value) {
    return label
  }
  let len = 0
  return (
    <span>
    {
      label.split(new RegExp(value.replace(/[-\[\]\(\)\+\*\\\^\$\{\}\.\?\&\|\<\>]/g, ''), "i")) // eslint-disable-line
        .reduce((prev, current, i) => {
          if (!i) {
            len += current.length
            return [current]
          }
          const ret = prev.concat(<b key={i}>{label.substr(len, value.length)}</b>, current)
          len += value.length + current.length
          return ret
        }, [])
    }
    </span>
  )
}

function sanitizeForAutocomplete(s) {
  return (s || "")
    .toLowerCase()
    .replace(/[^a-zA-Z0-9 ]/g, '')
    .trim()
    .replace(/\\/g, '')
}

class Autocomplete extends Component {
  constructor(props) {
    super()
    this.state = {
      q: props.q || "",
      selected: 0,
      matches: []
    }
    this.handleKeyDown = this.handleKeyDown.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
  }

  componentDidMount() {
    // build index based on what's in the hierarchy
    if (!this.props.institutions.loading) this.buildIndex()
  }
  
  buildIndex() {
    const { entities, lookup } = this.props.institutions
    let index = []
    this.index = index
    Object.keys(entities).forEach(name => {
      if (!name) return
      index.push([sanitizeForAutocomplete(name), name])
    })
    Object.keys(lookup).forEach(name => {
      if (!name) return
      index.push([sanitizeForAutocomplete(name), lookup[name]])
    })
    // console.log(index)
    // node.synonyms
    //   .split("\n")
    //   .map(word => word = word.trim())
    //   .filter(word => !!word)
    //   .forEach(word => index.push([prefixName, name, node.id]))
  }

  componentDidUpdate(oldProps) {
    if (oldProps.institutions.loading && !this.props.institutions.loading) {
      this.buildIndex()
    }
    if (this.props.vetting !== oldProps.vetting) {
      this.handleChange({ target: { value: this.props.vetting } })
    } else if (this.props.value !== oldProps.value) {
      this.setState({ q: '' })
    }
  }

  handleKeyDown(e) {
    let name
    console.log(e.keyCode)
    switch (e.keyCode) {
      case 27: // escape
        e.preventDefault()
        this.handleCancel()
        break
      case 38: // up
        e.preventDefault()
        this.setState({
          selected: (this.state.matches.length + this.state.selected - 1) % this.state.matches.length
        })
        return false
      case 40: // down
        e.preventDefault()
        this.setState({
          selected: (this.state.selected + 1) % this.state.matches.length
        })
        return false
      case 13: // enter - select from the list
        name = this.state.matches[this.state.selected]
        e.preventDefault()
        this.handleSelect(name, true)
        return false
      case 9: // tab - keep the unverified text
        name = this.state.matches[this.state.selected]
        if (name === this.state.q) {
          this.handleSelect(this.state.q, true)
        } else {
          this.handleSelect(this.state.q, false)
        }
        return false
      default:
        break
    }
    return null
  }

  handleChange(e) {
    // search for the given string in our index
    const q = e.target.value
    let value = sanitizeForAutocomplete(q)
    if (!value.length) {
      this.setState({
        q,
        selected: 0,
        matches: [],
      })
      return
    }
    let seen = {}
    value.split(' ').forEach(word => {
      const re = new RegExp(word)
      this.index.forEach(([synonym, term]) => {
        if (synonym.match(re)) {
          if (synonym.indexOf(value) === 0) {
            if (term in seen) {
              seen[term] += 4
            } else {
              seen[term] = 4
            }
          } else if (term in seen) {
            seen[term] += 1
          } else {
            seen[term] = 1
          }
        }
      })
    })
    let matches = Object.keys(seen)
      .map(term => [seen[term], term])
      .sort((a, b) => {
        return b[0] - a[0]
      })
      .slice(0, 100)
      .map(pair => pair[1])
    this.setState({
      q,
      selected: 0,
      matches,
    })
  }

  handleSelect(name, valid) {
    console.log('select', name, valid)
    if (this.props.onSelect) this.props.onSelect(name, valid)
    this.setState({ q: name, selected: 0, matches: [] })
  }

  handleCancel() {
    if (this.props.onCancel) this.props.onCancel()
    this.setState({ q: '', selected: 0, matches: [] })
  }

  render() {
    const { q, selected } = this.state
    const matches = this.state.matches.map((match, i) => {
      const label = formatLabel(match, q)
      return (
        <div
          key={i}
          className={selected === i ? 'selected' : ''}
          onClick={() => this.handleSelect(match, true)}
          onMouseEnter={() => this.setState({ selected: i })}
        >
          {label}
        </div>
      )
    })
    return (
      <div className="autocomplete">
        <input
          type="text"
          name="q"
          value={this.state.q || this.props.value}
          onKeyDown={this.handleKeyDown}
          onChange={this.handleChange}
          autoFocus={this.props.autoFocus}
          autoCapitalize="off"
          autoComplete="off"
          placeholder={this.props.placeholder}
          ref={ref => this._el = ref}
        />
        {!!matches.length &&
          <div className="matches">
            {matches}
          </div>
        }
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
  onSelect: ownProps.onSelect,
  institutions: state.api.institutions,
})

const mapDispatchToProps = (dispatch) => ({
})

export default connect(mapStateToProps, mapDispatchToProps)(Autocomplete)