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

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

const self = new EventEmitter()

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

self.submit = function () {
  const selectedItem = autocomplete.getSelectedItem()
  if (selectedItem == null) return

  console.log(selectedItem)

  self._nodes.input.blur()
  document.body.classList.remove('week-selector-not-visible') // Safari bug

  self.emit('search', selectedItem)
}

self.updateDom = function (selectedItem) {
  if (selectedItem == null) {
    self._nodes.input.value = ''
    autocomplete.removeAllItems()
    document.body.classList.add('no-input')
    document.body.classList.remove('searched')
  } else {
    self._nodes.input.value = selectedItem.value
    autocomplete.removeAllItems()
    document.body.classList.remove('no-input')
    document.body.classList.add('searched')
  }
}

self.focus = function () {
  self._nodes.input.focus()
}

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

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

  const originalResults = firstResults.map(function (result) {
    return 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])
  }
}

self._handleFocus = function () {
  self._nodes.input.select()
}

self._handleBlur = function () {
  // this will removed the selection without drawing focus on it (safari)
  // this will removed selection even when focusing an iframe (chrome)
  const oldValue = self._nodes.value
  self._nodes.value = ''
  self._nodes.value = oldValue

  // this will hide the keyboard (iOS safari)
  document.activeElement.blur()
}

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

self._nodes.search.addEventListener('submit', self._handleSubmit)
self._nodes.input.addEventListener('focus', self._handleFocus)
self._nodes.input.addEventListener('blur', self._handleBlur)
self._nodes.input.addEventListener(browserFixToolkit.inputEvent,
                                   self._handleTextUpdate)

module.exports = self