aboutsummaryrefslogtreecommitdiff
path: root/data/assets/js/search-field.js
blob: 3d6c4940197e66caac0752fd044454ea2c05d3f3 (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
jQuery(function($) {
  "use strict";

  function clear_delay(el) {
    var ival = el.data('search-interval');

    if (ival) {
      // clear timeout
      clearTimeout(ival);
      el.data('search-interval', null);
    }
  }

  function trigger_search(el, q) {
    if (q == el.data('q'))
      return;

    // cache search
    el.data('q', q);

    // trigger search
    el.trigger({
      type: "search-update",
      query: "",
    });
  }

  $('.btn.search-toggle').click(function() {
    var btn = $(this),
        bar = btn.parents('.panel').find('.panel-heading.search-toggle'),
        field = bar.find('input');

    // toggle button highlight
    btn.toggleClass('btn-primary btn-default')
    var active = btn.hasClass('btn-primary');

    // clear field
    field.val('');

    // toggle bar visibility
    bar.toggleClass('hidden', !active);

    if (active) {
      setTimeout(function() {
        // focus text field
        field.focus();
      }, 10);
    } else {
      // trigger search
      trigger_search(field, '');
    }

    // stop event
    return false;
  });

  $('.panel-heading.search-toggle input').keydown(function(ev) {
    var me = $(this),
        trigger = me.data('search-trigger') || 'delay';

    if (trigger == 'delay') {
      clear_delay(me);

      me.data('search-interval', setTimeout(function() {
        clear_delay(me);
        trigger_search(me, me.val());
      }, me.data('search-delay') || 300));
    } else if (trigger == 'enter') {
      if (ev.which == 13) {
        setTimeout(function() {
          trigger_search(me, me.val());
        }, 10);

        // stop event
        return false;
      }
    } else {
      // unknown trigger type
      throw new Error('unknown search trigger: ' + trigger);
    }
  });
});