bootstrap-typeahead.js 8.12 KB
Newer Older
Jacob Thornton's avatar
Jacob Thornton committed
1
/* =============================================================
Mark Otto's avatar
Mark Otto committed
2
 * bootstrap-typeahead.js v2.2.3
Jon Stevens's avatar
Jon Stevens committed
3
 * http://twitter.github.com/bootstrap/javascript.html#typeahead
Jacob Thornton's avatar
Jacob Thornton committed
4
 * =============================================================
Mark Otto's avatar
Mark Otto committed
5
 * Copyright 2012 Twitter, Inc.
Jacob Thornton's avatar
Jacob Thornton committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

20

21
!function($){
Jacob Thornton's avatar
Jacob Thornton committed
22

23
  "use strict"; // jshint ;_;
Jacob Thornton's avatar
Jacob Thornton committed
24

25
26
27
28
29

 /* TYPEAHEAD PUBLIC CLASS DEFINITION
  * ================================= */

  var Typeahead = function (element, options) {
Jacob Thornton's avatar
Jacob Thornton committed
30
31
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
32
33
34
    this.matcher = this.options.matcher || this.matcher
    this.sorter = this.options.sorter || this.sorter
    this.highlighter = this.options.highlighter || this.highlighter
35
    this.updater = this.options.updater || this.updater
36
    this.source = this.options.source
fat's avatar
fat committed
37
    this.$menu = $(this.options.menu)
Jacob Thornton's avatar
Jacob Thornton committed
38
39
40
41
42
43
44
45
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

46
47
  , select: function () {
      var val = this.$menu.find('.active').attr('data-value')
48
      this.$element
49
        .val(this.updater(val))
50
        .change()
51
      return this.hide()
Jacob Thornton's avatar
Jacob Thornton committed
52
53
    }

54
55
56
57
  , updater: function (item) {
      return item
    }

Jacob Thornton's avatar
Jacob Thornton committed
58
  , show: function () {
59
      var pos = $.extend({}, this.$element.position(), {
60
61
62
        height: this.$element[0].offsetHeight
      })

fat's avatar
fat committed
63
64
65
66
67
68
69
      this.$menu
        .insertAfter(this.$element)
        .css({
          top: pos.top + pos.height
        , left: pos.left
        })
        .show()
70
71

      this.shown = true
Jacob Thornton's avatar
Jacob Thornton committed
72
73
74
75
76
      return this
    }

  , hide: function () {
      this.$menu.hide()
77
      this.shown = false
Jacob Thornton's avatar
Jacob Thornton committed
78
79
80
81
      return this
    }

  , lookup: function (event) {
82
      var items
83
84

      this.query = this.$element.val()
85

Jacob Thornton's avatar
Jacob Thornton committed
86
      if (!this.query || this.query.length < this.options.minLength) {
87
88
        return this.shown ? this.hide() : this
      }
Jacob Thornton's avatar
Jacob Thornton committed
89

90
91
92
93
94
95
96
97
98
      items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source

      return items ? this.process(items) : this
    }

  , process: function (items) {
      var that = this

      items = $.grep(items, function (item) {
99
        return that.matcher(item)
Jacob Thornton's avatar
Jacob Thornton committed
100
101
      })

102
103
      items = this.sorter(items)

Jacob Thornton's avatar
Jacob Thornton committed
104
105
106
107
      if (!items.length) {
        return this.shown ? this.hide() : this
      }

108
      return this.render(items.slice(0, this.options.items)).show()
Jacob Thornton's avatar
Jacob Thornton committed
109
110
    }

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  , matcher: function (item) {
      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
    }

  , sorter: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item

      while (item = items.shift()) {
        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
        else if (~item.indexOf(this.query)) caseSensitive.push(item)
        else caseInsensitive.push(item)
      }

      return beginswith.concat(caseSensitive, caseInsensitive)
    }

  , highlighter: function (item) {
131
      var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
132
      return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
133
134
135
136
        return '<strong>' + match + '</strong>'
      })
    }

137
  , render: function (items) {
Jacob Thornton's avatar
Jacob Thornton committed
138
139
140
      var that = this

      items = $(items).map(function (i, item) {
141
        i = $(that.options.item).attr('data-value', item)
142
        i.find('a').html(that.highlighter(item))
143
        return i[0]
Jacob Thornton's avatar
Jacob Thornton committed
144
145
146
      })

      items.first().addClass('active')
147
      this.$menu.html(items)
Jacob Thornton's avatar
Jacob Thornton committed
148
149
150
151
152
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
153
154
155
156
157
        , next = active.next()

      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }
Jacob Thornton's avatar
Jacob Thornton committed
158
159
160
161
162
163

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
164
        , prev = active.prev()
Jacob Thornton's avatar
Jacob Thornton committed
165

166
167
168
169
170
      if (!prev.length) {
        prev = this.$menu.find('li').last()
      }

      prev.addClass('active')
Jacob Thornton's avatar
Jacob Thornton committed
171
172
    }

173
174
  , listen: function () {
      this.$element
fat's avatar
fat committed
175
        .on('focus',    $.proxy(this.focus, this))
176
177
178
179
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

180
      if (this.eventSupported('keydown')) {
181
        this.$element.on('keydown', $.proxy(this.keydown, this))
182
183
184
185
186
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
fat's avatar
fat committed
187
        .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
188
189
    }

190
191
192
193
194
195
196
197
198
  , eventSupported: function(eventName) {
      var isSupported = eventName in this.$element
      if (!isSupported) {
        this.$element.setAttribute(eventName, 'return;')
        isSupported = typeof this.$element[eventName] === 'function'
      }
      return isSupported
    }

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
  , move: function (e) {
      if (!this.shown) return

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          e.preventDefault()
          this.next()
          break
      }

      e.stopPropagation()
    }

  , keydown: function (e) {
224
      this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27])
225
226
227
228
229
230
231
232
      this.move(e)
    }

  , keypress: function (e) {
      if (this.suppressKeyPressRepeat) return
      this.move(e)
    }

233
234
235
236
  , keyup: function (e) {
      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
237
238
239
        case 16: // shift
        case 17: // ctrl
        case 18: // alt
240
          break
Jacob Thornton's avatar
Jacob Thornton committed
241
242
243

        case 9: // tab
        case 13: // enter
244
          if (!this.shown) return
Jacob Thornton's avatar
Jacob Thornton committed
245
246
247
248
          this.select()
          break

        case 27: // escape
249
          if (!this.shown) return
Jacob Thornton's avatar
Jacob Thornton committed
250
251
252
253
254
255
          this.hide()
          break

        default:
          this.lookup()
      }
256

257
258
      e.stopPropagation()
      e.preventDefault()
Jacob Thornton's avatar
Jacob Thornton committed
259
260
  }

fat's avatar
fat committed
261
262
263
264
  , focus: function (e) {
      this.focused = true
    }

265
  , blur: function (e) {
fat's avatar
fat committed
266
267
      this.focused = false
      if (!this.mousedover && this.shown) this.hide()
268
269
270
271
272
273
274
275
276
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
    }

  , mouseenter: function (e) {
fat's avatar
fat committed
277
      this.mousedover = true
278
279
280
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }
Jacob Thornton's avatar
Jacob Thornton committed
281

fat's avatar
fat committed
282
283
284
285
286
  , mouseleave: function (e) {
      this.mousedover = false
      if (!this.focused && this.shown) this.hide()
    }

Jacob Thornton's avatar
Jacob Thornton committed
287
288
  }

289

Jacob Thornton's avatar
Jacob Thornton committed
290
  /* TYPEAHEAD PLUGIN DEFINITION
291
   * =========================== */
Jacob Thornton's avatar
Jacob Thornton committed
292

293
294
  var old = $.fn.typeahead

295
  $.fn.typeahead = function (option) {
Jacob Thornton's avatar
Jacob Thornton committed
296
297
298
299
300
301
302
303
304
305
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
306
307
    source: []
  , items: 8
308
309
  , menu: '<ul class="typeahead dropdown-menu"></ul>'
  , item: '<li><a href="#"></a></li>'
Jacob Thornton's avatar
Jacob Thornton committed
310
  , minLength: 1
Jacob Thornton's avatar
Jacob Thornton committed
311
312
313
314
  }

  $.fn.typeahead.Constructor = Typeahead

315

316
317
318
319
320
321
322
323
324
325
 /* TYPEAHEAD NO CONFLICT
  * =================== */

  $.fn.typeahead.noConflict = function () {
    $.fn.typeahead = old
    return this
  }


 /* TYPEAHEAD DATA-API
326
327
  * ================== */

328
329
330
331
332
  $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
    var $this = $(this)
    if ($this.data('typeahead')) return
    e.preventDefault()
    $this.typeahead($this.data())
333
334
  })

335
}(window.jQuery);