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

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

    if (ival) {
      // clear interval
      clearInterval(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, '');
    }
  });

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

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

      setTimeout(function() {
        clear_delay(me);
        trigger_search(me, me.val());
      }, me.data('search-delay') || 100);
    } 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);
    }
  });
});