aboutsummaryrefslogtreecommitdiffstats
path: root/pages/vomnibar.coffee
blob: a96a3b4fc2fe3dce4758fe0c273f2ea9c1c29ea4 (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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#
# This controls the contents of the Vomnibar iframe. We use an iframe to avoid changing the selection on the
# page (useful for bookmarklets), ensure that the Vomnibar style is unaffected by the page, and simplify key
# handling in vimium_frontend.coffee
#
Vomnibar =
  vomnibarUI: null # the dialog instance for this window
  getUI: -> @vomnibarUI
  completers: {}

  getCompleter: (name) ->
    @completers[name] ?= new BackgroundCompleter name

  activate: (userOptions) ->
    options =
      completer: "omni"
      query: ""
      newTab: false
      selectFirst: false
    extend options, userOptions
    extend options, refreshInterval: if options.completer == "omni" then 150 else 0

    completer = @getCompleter options.completer
    @vomnibarUI ?= new VomnibarUI()
    completer.refresh @vomnibarUI
    @vomnibarUI.setInitialSelectionValue if options.selectFirst then 0 else -1
    @vomnibarUI.setCompleter completer
    @vomnibarUI.setRefreshInterval options.refreshInterval
    @vomnibarUI.setForceNewTab options.newTab
    @vomnibarUI.setQuery options.query
    @vomnibarUI.update true

  hide: -> @vomnibarUI?.hide()
  onHidden: -> @vomnibarUI?.onHidden()

class VomnibarUI
  constructor: ->
    @refreshInterval = 0
    @postHideCallback = null
    @initDom()

  setQuery: (query) -> @input.value = query
  setInitialSelectionValue: (@initialSelectionValue) ->
  setRefreshInterval: (@refreshInterval) ->
  setForceNewTab: (@forceNewTab) ->
  setCompleter: (@completer) -> @reset()
  setKeywords: (@keywords) ->

  # The sequence of events when the vomnibar is hidden is as follows:
  # 1. Post a "hide" message to the host page.
  # 2. The host page hides the vomnibar.
  # 3. When that page receives the focus, and it posts back a "hidden" message.
  # 3. Only once the "hidden" message is received here is any required action  invoked (in onHidden).
  # This ensures that the vomnibar is actually hidden before any new tab is created, and avoids flicker after
  # opening a link in a new tab then returning to the original tab (see #1485).
  hide: (@postHideCallback = null) ->
    UIComponentServer.postMessage "hide"
    @reset()
    @completer?.reset()

  onHidden: ->
    @postHideCallback?()
    @postHideCallback = null

  reset: ->
    @clearUpdateTimer()
    @completionList.style.display = ""
    @input.value = ""
    @completions = []
    @previousAutoSelect = null
    @previousInputValue = null
    @lastUpdateTime = null
    @suppressedLeadingKeyword = null
    @selection = @initialSelectionValue
    @keywords = []

  updateSelection: ->
    # We retain global state here (previousAutoSelect) to tell if a search item (for which autoSelect is set)
    # has just appeared or disappeared. If that happens, we set @selection to 0 or -1.
    if 0 < @completions.length
      @selection = 0 if @completions[0].autoSelect and not @previousAutoSelect
      @selection = -1 if @previousAutoSelect and not @completions[0].autoSelect
      @previousAutoSelect = @completions[0].autoSelect
    else
      @previousAutoSelect = null

    # Notwithstanding all of the above, disable autoSelect if the user is deleting text from the query.
    if @lastAction == "delete"
      @selection = -1
      @previousAutoSelect = null

    # For custom search engines, we suppress the leading term (e.g. the "w" of "w query terms") within the
    # vomnibar input.
    if @lastReponse.suppressLeadingKeyword and not @suppressedLeadingKeyword?
      queryTerms = @input.value.trim().split /\s+/
      @suppressedLeadingKeyword = queryTerms[0]
      @input.value = queryTerms[1..].join " "

    # For suggestions for custom search engines, we copy the suggested text into the input when the item is
    # selected, and revert when it is not.  This allows the user to select a suggestion and then continue
    # typing.
    if 0 <= @selection and @completions[@selection].insertText?
      @previousInputValue ?=
        value: @input.value
        selectionStart: @input.selectionStart
        selectionEnd: @input.selectionEnd
      @input.value = @completions[@selection].insertText + (if @selection == 0 then "" else " ")
    else if @previousInputValue?
      # Restore the text.
      @input.value = @previousInputValue.value
      # Restore the selection.
      if @previousInputValue.selectionStart? and @previousInputValue.selectionEnd? and
        @previousInputValue.selectionStart != @previousInputValue.selectionEnd
          @input.setSelectionRange @previousInputValue.selectionStart, @previousInputValue.selectionEnd
      @previousInputValue = null

    # Highlight the selected entry, and only the selected entry.
    for i in [0...@completionList.children.length]
      @completionList.children[i].className = (if i == @selection then "vomnibarSelected" else "")

  # This adds prompted text to the vomnibar input.  The prompted text is a continuation of the text the user
  # has already typed, taken from one of the search suggestions.  It is highlight (using the selection) and
  # will be included with the query should the user type <Enter>.
  addPromptedText: ->
    # Bail if we don't yet have the background completer's final word on the current query.
    return unless @lastReponse.mayCacheResults

    # Bail if the last action was "delete"; or we may be putting back what the user just deleted.
    return if @lastAction == "delete"

    # Bail if there's an update pending, because @input and the completion state are out of sync.
    return if @updateTimer?

    completions = @completions.filter (completion) ->
      completion. searchSuggestionType in [ "primary", "completion" ]
    return unless 0 < completions.length

    query = @getInputWithoutPromptedText().ltrim().split(/\s+/).join(" ").toLowerCase()
    suggestion = completions[0].title

    index = suggestion.toLowerCase().indexOf query
    return unless 0 <= index and index + query.length < suggestion.length

    # If the typed text is all lower case, then make the prompted text lower case too.
    suggestion = suggestion[index..]
    suggestion = suggestion.toLowerCase() unless /[A-Z]/.test @getInputWithoutPromptedText()

    suggestion = suggestion[query.length..]
    @input.value = query + suggestion
    @input.setSelectionRange query.length, query.length + suggestion.length

  # Returns the user's action ("up", "down", "tab", etc, or null) based on their keypress.  We support the
  # arrow keys and various other shortcuts, and this function hides the event-decoding complexity.
  actionFromKeyEvent: (event) ->
    key = KeyboardUtils.getKeyChar(event)
    if (KeyboardUtils.isEscape(event))
      return "dismiss"
    else if (key == "up" ||
        (event.shiftKey && event.keyCode == keyCodes.tab) ||
        (event.ctrlKey && (key == "k" || key == "p")))
      return "up"
    else if (event.keyCode == keyCodes.tab && !event.shiftKey)
      return "tab"
    else if (key == "down" ||
        (event.ctrlKey && (key == "j" || key == "n")))
      return "down"
    else if (event.keyCode == keyCodes.enter)
      return "enter"
    else if event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey
      return "delete"
    else if key in [ "left", "right" ]
      return key

    null

  onKeydown: (event) =>
    @lastAction = action = @actionFromKeyEvent event
    return true unless action # pass through

    openInNewTab = @forceNewTab ||
      (event.shiftKey || event.ctrlKey || KeyboardUtils.isPrimaryModifierKey(event))
    if (action == "dismiss")
      @hide()
    else if action in [ "tab", "down" ]
      # if action == "tab"
      #   if @inputContainsASelectionRange()
      #     window.getSelection().collapseToEnd()
      #   else
      #     action = "down"
      # if action == "down"
      @selection += 1
      @selection = @initialSelectionValue if @selection == @completions.length
      @updateSelection()
    else if (action == "up")
      @selection -= 1
      @selection = @completions.length - 1 if @selection < @initialSelectionValue
      @updateSelection()
    else if (action == "enter")
      # <Enter> immediately after new suggestions have been posted is ignored.  It's all too common that the
      # user gets results they weren't intending.
      return if @lastUpdateTime? and new Date() - @lastUpdateTime < 250 and @inputContainsASelectionRange()
      @lastUpdateTime = null
      if @selection == -1
        query = @input.value.trim()
        # <Enter> on an empty query is a no-op.
        return unless 0 < query.length
        # If the user types something and hits enter without selecting a completion from the list, then:
        #   - If a search URL has been provided, then use it.  This is custom search engine request.
        #   - Otherwise, send the query to the background page, which will open it as a URL or create a
        #     default search, as appropriate.
        query = Utils.createSearchUrl query, @lastReponse.searchUrl if @lastReponse.searchUrl?
        @hide ->
          chrome.runtime.sendMessage
            handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
            url: query
      else
        completion = @completions[@selection]
        @hide -> completion.performAction openInNewTab
    else if action == "delete"
      if @suppressedLeadingKeyword? and @input.value.length == 0
        # Normally, with custom search engines, the keyword (e,g, the "w" of "w query terms") is suppressed.
        # If the input is empty, then show the keyword again.
        @input.value = @suppressedLeadingKeyword
        @suppressedLeadingKeyword = null
        @updateCompletions()
      else
        return true # Do not suppress event.
    else if action in [ "left", "right" ]
      [ start, end ] = [ @input.selectionStart, @input.selectionEnd ]
      if event.ctrlKey and not (event.altKey or event.metaKey)
        return true unless @inputContainsASelectionRange() and end == @input.value.length
        # "Control-Right" advances the start of the selection by a word.
        text = @input.value[start...end]
        switch action
          when "right"
            newText = text.replace /^\s*\S+\s*/, ""
            @input.setSelectionRange start + (text.length - newText.length), end
          when "left"
            newText = text.replace /\S+\s*$/, ""
            @input.setSelectionRange start + (newText.length - text.length), end
      else
        return true # Do not suppress event.

    # It seems like we have to manually suppress the event here and still return true.
    event.stopImmediatePropagation()
    event.preventDefault()
    true

  onKeypress: (event) =>
    # The user is typing. They know what they're doing.
    @lastUpdateTime = null
    # Handle typing together with prompted text.
    unless event.altKey or event.ctrlKey or event.metaKey
      if @inputContainsASelectionRange()
        # As the user types characters which the match the prompted text, we suppress the keyboard event and
        # simulate it by advancing the start of the selection (but only if the typed character matches).
        # If we were to allow the event through, we would get flicker, as the selection is first collapsed and
        # then (shortly afterwards) restored.
        if @input.value[@input.selectionStart][0].toLowerCase() == (String.fromCharCode event.charCode).toLowerCase()
          @input.setSelectionRange @input.selectionStart + 1, @input.selectionEnd
          @updateOnInput()
          event.stopImmediatePropagation()
          event.preventDefault()
    true

  # Test whether the input contains prompted text.
  inputContainsASelectionRange: ->
    @input.selectionStart? and @input.selectionEnd? and @input.selectionStart != @input.selectionEnd

  # Return the text of the input, with any prompted text removed.
  getInputWithoutPromptedText: ->
    if @inputContainsASelectionRange()
      @input.value[0...@input.selectionStart] + @input.value[@input.selectionEnd..]
    else
      @input.value

  # Return the background-page query corresponding to the current input state.  In other words, reinstate any
  # search engine keyword which is currently being suppressed, and strip any prompted text.
  getInputValueAsQuery: ->
    (if @suppressedLeadingKeyword? then @suppressedLeadingKeyword + " " else "") + @getInputWithoutPromptedText()

  updateCompletions: (callback = null) ->
    @completer.filter
      query: @getInputValueAsQuery()
      callback: (@lastReponse) =>
        { results } = @lastReponse
        @completions = results
        # Update completion list with the new suggestions.
        @completionList.innerHTML = @completions.map((completion) -> "<li>#{completion.html}</li>").join("")
        @completionList.style.display = if @completions.length > 0 then "block" else ""
        @selection = Math.min @completions.length - 1, Math.max @initialSelectionValue, @selection
        @previousAutoSelect = null if @completions[0]?.autoSelect and @completions[0]?.forceAutoSelect
        @updateSelection()
        @addPromptedText()
        @lastUpdateTime = new Date()
        callback?()

  updateOnInput: =>
    @completer.cancel()
    # If the user types, then don't reset any previous text, and restart auto select.
    if @previousInputValue?
      @previousInputValue = null
      @previousAutoSelect = null
      @selection = -1
    @update false

  clearUpdateTimer: ->
    if @updateTimer?
      window.clearTimeout @updateTimer
      @updateTimer = null

  isCustomSearch: ->
    queryTerms = @input.value.ltrim().split /\s+/
    1 < queryTerms.length and queryTerms[0] in @keywords

  update: (updateSynchronously = false, callback = null) =>
    # If the query text becomes a custom search (the user enters a search keyword), then we need to force a
    # synchronous update (so that the state is updated immediately).
    updateSynchronously ||= @isCustomSearch() and not @suppressedLeadingKeyword?
    if updateSynchronously
      @clearUpdateTimer()
      @updateCompletions callback
    else if not @updateTimer?
      # Update asynchronously for a better user experience, and to take some load off the CPU (not every
      # keystroke will cause a dedicated update).
      @updateTimer = Utils.setTimeout @refreshInterval, =>
        @updateTimer = null
        @updateCompletions callback

    @input.focus()

  initDom: ->
    @box = document.getElementById("vomnibar")

    @input = @box.querySelector("input")
    @input.addEventListener "input", @updateOnInput
    @input.addEventListener "keydown", @onKeydown
    @input.addEventListener "keypress", @onKeypress
    @completionList = @box.querySelector("ul")
    @completionList.style.display = ""

    window.addEventListener "focus", => @input.focus()
    # A click in the vomnibar itself refocuses the input.
    @box.addEventListener "click", (event) =>
      @input.focus()
      event.stopImmediatePropagation()
    # A click anywhere else hides the vomnibar.
    document.body.addEventListener "click", => @hide()

#
# Sends requests to a Vomnibox completer on the background page.
#
class BackgroundCompleter
  # The "name" is the background-page completer to connect to: "omni", "tabs", or "bookmarks".
  constructor: (@name) ->
    @port = chrome.runtime.connect name: "completions"
    @messageId = null
    @reset()

    @port.onMessage.addListener (msg) =>
      switch msg.handler
        when "keywords"
          @keywords = msg.keywords
          @lastUI.setKeywords @keywords
        when "completions"
          if msg.id == @messageId
            # The result objects coming from the background page will be of the form:
            #   { html: "", type: "", url: "", ... }
            # Type will be one of [tab, bookmark, history, domain, search], or a custom search engine description.
            for result in msg.results
              extend result,
                performAction:
                  if result.type == "tab"
                    @completionActions.switchToTab result.tabId
                  else
                    @completionActions.navigateToUrl result.url

            # Handle the message, but only if it hasn't arrived too late.
            @mostRecentCallback msg

  filter: (request) ->
    { query, callback } = request
    @mostRecentCallback = callback

    @port.postMessage extend request,
      handler: "filter"
      name: @name
      id: @messageId = Utils.createUniqueId()
      queryTerms: query.trim().split(/\s+/).filter (s) -> 0 < s.length
      # We don't send these keys.
      callback: null
      mayUseVomnibarCache: null

  reset: ->
    @keywords = []

  refresh: (@lastUI) ->
    @reset()
    @port.postMessage name: @name, handler: "refresh"

  cancel: ->
    # Inform the background completer that it may (should it choose to do so) abandon any pending query
    # (because the user is typing, and there will be another query along soon).
    @port.postMessage name: @name, handler: "cancel"

  # These are the actions we can perform when the user selects a result.
  completionActions:
    navigateToUrl: (url) -> (openInNewTab) ->
      # If the URL is a bookmarklet (so, prefixed with "javascript:"), then we always open it in the current
      # tab.
      openInNewTab &&= not Utils.hasJavascriptPrefix url
      chrome.runtime.sendMessage
        handler: if openInNewTab then "openUrlInNewTab" else "openUrlInCurrentTab"
        url: url
        selected: openInNewTab

    switchToTab: (tabId) -> ->
      chrome.runtime.sendMessage handler: "selectSpecificTab", id: tabId

UIComponentServer.registerHandler (event) ->
  switch event.data
    when "hide" then Vomnibar.hide()
    when "hidden" then Vomnibar.onHidden()
    else Vomnibar.activate event.data

root = exports ? window
root.Vomnibar = Vomnibar