aboutsummaryrefslogtreecommitdiffstats
path: root/fuzzyMode.js
blob: f4bc2357a4cbb463ecccece1a351b2e3d82f69bd (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
224
225
var fuzzyMode = (function() {
  var fuzzyBox = null;  // the dialog instance for this window
  var completers = { };

  function getCompleter(name) {
    if (!(name in completers))
      completers[name] = new BackgroundCompleter(name);
    return completers[name];
  }

  /** Trigger the fuzzy mode dialog */
  function start(name, refreshInterval) {
    var completer = getCompleter(name);
    if (!fuzzyBox)
      fuzzyBox = new FuzzyBox(10);
    completer.refresh();
    fuzzyBox.setCompleter(completer);
    fuzzyBox.setRefreshInterval(refreshInterval);
    fuzzyBox.show();
  }

  /** User interface for fuzzy completion */
  var FuzzyBox = function(maxResults) {
    this.prompt = '>';
    this.maxResults = maxResults;
    this.refreshInterval = 0;
    this.initDom();
  }
  FuzzyBox.prototype = {
    setCompleter: function(completer) {
      this.completer = completer;
      this.reset();
    },

    setRefreshInterval: function(refreshInterval) {
      this.refreshInterval = refreshInterval;
    },

    show: function() {
      this.box.style.display = "block";
      this.input.focus();
      handlerStack.push({ keydown: this.onKeydown.bind(this) });
    },

    hide: function() {
      this.box.style.display = "none";
      this.completionList.style.display = "none";
      this.input.blur();
      handlerStack.pop();
    },

    reset: function() {
      this.input.value = "";
      this.updateTimer = null;
      this.completions = [];
      this.selection = 0;
      this.update(true);
    },

    updateSelection: function() {
      if (this.completions.length > 0)
        this.selection = Math.min(this.selection, this.completions.length - 1);
      for (var i = 0; i < this.completionList.children.length; ++i)
        this.completionList.children[i].className = (i == this.selection) ? "selected" : "";
    },

    onKeydown: function(event) {
      var self = this;
      var keyChar = getKeyChar(event);

      if (isEscape(event)) {
        this.hide();
      }
      // move selection with Up/Down, Tab/Shift-Tab, Ctrl-k/Ctrl-j
      else if (keyChar === "up" || (event.keyCode == keyCodes.tab && event.shiftKey)
              || (keyChar === "k" && event.ctrlKey)) {
        if (this.selection > 0)
          this.selection -= 1;
        this.updateSelection();
      }
      else if (keyChar === "down" || (event.keyCode == keyCodes.tab && !event.shiftKey)
              || (keyChar === "j" && isPrimaryModifierKey(event))) {
        if (this.selection < this.completions.length - 1)
          this.selection += 1;
        this.updateSelection();
      }

      // refresh with F5
      else if (keyChar == "f5") {
        this.completer.refresh();
        this.update(true); // force immediate update
      }

      else if (event.keyCode == keyCodes.enter) {
        this.update(true, function() {
          // Shift+Enter will open the result in a new tab instead of the current tab.
          var openInNewTab = (event.shiftKey || isPrimaryModifierKey(event));
          self.completions[self.selection].action(openInNewTab);
          self.hide();
        });
      }
      else {
        return true; // pass through
      }

      // it seems like we have to manually supress the event here and still return true...
      event.stopPropagation();
      event.preventDefault();
      return true;
    },

    updateCompletions: function(callback) {
      var self = this;
      query = this.input.value.replace(/^\s*/, "");

      this.completer.filter(query, this.maxResults, function(completions) {
        self.completions = completions;

        // update completion list with the new data
        self.completionList.innerHTML = completions.map(function(completion) {
          return "<li>" + completion.html + "</li>";
        }).join('');

        self.completionList.style.display = self.completions.length > 0 ? "block" : "none";
        self.updateSelection();
        if (callback) callback();
      });
    },

    update: function(force, callback) {
      force = force || false; // explicitely default to asynchronous updating

      if (force) {
        // cancel scheduled update
        if (this.updateTimer !== null)
          window.clearTimeout(this.updateTimer);
        this.updateCompletions(callback);
      } else if (this.updateTimer !== null) {
        // an update is already scheduled, don't do anything
        return;
      } else {
        var self = this;
        // always update asynchronously for better user experience and to take some load off the CPU
        // (not every keystroke will cause a dedicated update)
        this.updateTimer = setTimeout(function() {
          self.updateCompletions(callback);
          self.updateTimer = null;
        }, this.refreshInterval);
      }
    },

    initDom: function() {
      this.box = utils.createElementFromHtml(
        '<div id="fuzzybox" class="vimiumReset">'+
          '<div class="input">'+
            '<span class="prompt">' + utils.escapeHtml(this.prompt) + '</span> '+
            '<input type="text" class="query"></span></div>'+
          '<ul></ul></div>');
      this.box.style.display = 'none';
      document.body.appendChild(this.box);

      this.input = document.querySelector("#fuzzybox .query");
      this.input.addEventListener("input", function() { this.update(); }.bind(this));
      this.completionList = document.querySelector("#fuzzybox ul");
      this.completionList.style.display = "none";
    },
  }

  /*
   * Sends filter and refresh requests to a Vomnibar completer on the background page.
   */
  var BackgroundCompleter = Class.extend({
    /*
     * - name: The name of the background page completer that you want to interface with. One of [omni, tabs].
     */
    init: function(name) {
      this.name = name;
      this.filterPort = chrome.extension.connect({ name: "filterCompleter" });
    },

    refresh: function() { chrome.extension.sendRequest({ handler: "refreshCompleter", name: this.name }); },

    filter: function(query, maxResults, callback) {
      var id = utils.createUniqueId();
      this.filterPort.onMessage.addListener(function(msg) {
        if (msg.id != id) return;
        callback(msg.results.map(function(result) {
          var action = result.action;
          result.action = eval(action.func).apply(null, action.args);
          return result;
        }));
      });
      this.filterPort.postMessage({ id: id, name: this.name, query: query, maxResults: maxResults });
    }
  });

  /** Creates an action that opens :url in the current tab by default or in a new tab as an alternative. */
  function createActionOpenUrl(url) {
    return function(openInNewTab) {
      // If the URL is a bookmarklet prefixed with javascript:, we don't need to open that in a new tab.
      if (url.indexOf("javascript:") == 0)
        openInNewTab = false;
      var selected = openInNewTab;
      chrome.extension.sendRequest({
        handler:  openInNewTab ? "openUrlInNewTab" : "openUrlInCurrentTab",
        url:      url,
        selected: openInNewTab
      });
    };
  }

  /** Returns an action that switches to the tab with the given :id. */
  function createActionSwitchToTab(id) {
    return function() { chrome.extension.sendRequest({ handler: "selectSpecificTab", id: id }); };
  }


  // public interface
  return {
    activateAll:       function() { start("omni", false, 100); },
    activateAllNewTab: function() { start("omni", true,  100);  },
    activateTabs:      function() { start("tabs", false, 0);  },
  }

})();