aboutsummaryrefslogtreecommitdiff
path: root/public/javascripts/search.js
blob: c1e6158b99081c59b86bef02526016d8d159b71e (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
/* global USERS */

const EventEmitter = require('events')
const fuzzy = require('fuzzy')
const autocomplete = require('./autocomplete')

const self = new EventEmitter()

self._nodes = {
  search: document.querySelector('#search'),
  input: document.querySelector('input[type="search"]')
}

self.submit = function () {
  self._nodes.input.blur()

  const selectedItem = autocomplete.getSelectedItem()
  self._nodes.input.value = selectedItem.value

  autocomplete.removeAllItems()
  document.body.classList.add('searched')

  self.emit('search', selectedItem)
}

self._handleSubmit = function (event) {
  event.preventDefault()
  self.submit()
}

self._calculate = function (searchTerm) {
  const allResults = fuzzy.filter(searchTerm, USERS, {
    extract: item => item.value
  })
  const firstResults = allResults.slice(0, 7)

  const originalResults = firstResults.map(result => result.original)

  return originalResults
}

self._handleTextUpdate = function () {
  const results = self._calculate(self._nodes.input.value)

  autocomplete.removeAllItems()
  for (let i = 0; i < results.length; i++) {
    autocomplete.addItem(results[i])
  }
}

autocomplete.on('select', self.submit)

self._nodes.search.addEventListener('submit', self._handleSubmit)
self._nodes.input.addEventListener('input', self._handleTextUpdate)

module.exports = self