aboutsummaryrefslogtreecommitdiffstats
path: root/content_scripts/mode_normal.coffee
blob: 9a03e9d0fcb5af0764b9289aebcf990507f457b1 (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
class NormalMode extends KeyHandlerMode
  constructor: (options = {}) ->
    defaults =
      name: "normal"
      indicator: false # There is normally no mode indicator in normal mode.
      commandHandler: @commandHandler.bind this

    super extend defaults, options

    chrome.storage.local.get "normalModeKeyStateMapping", (items) =>
      @setKeyMapping items.normalModeKeyStateMapping

    chrome.storage.onChanged.addListener (changes, area) =>
      if area == "local" and changes.normalModeKeyStateMapping?.newValue
        @setKeyMapping changes.normalModeKeyStateMapping.newValue

  commandHandler: ({command: registryEntry, count}) ->
    count *= registryEntry.options.count ? 1
    count = 1 if registryEntry.noRepeat

    if registryEntry.repeatLimit? and registryEntry.repeatLimit < count
      return unless confirm """
        You have asked Vimium to perform #{count} repetitions of the command: #{registryEntry.description}.\n
        Are you sure you want to continue?"""

    if registryEntry.topFrame
      # We never return to a UI-component frame (e.g. the help dialog), it might have lost the focus.
      sourceFrameId = if window.isVimiumUIComponent then 0 else frameId
      chrome.runtime.sendMessage
        handler: "sendMessageToFrames", message: {name: "runInTopFrame", sourceFrameId, registryEntry}
    else if registryEntry.background
      chrome.runtime.sendMessage {handler: "runBackgroundCommand", registryEntry, count}
    else
      NormalModeCommands[registryEntry.command] count, {registryEntry}

enterNormalMode = (count) ->
  new NormalMode
    indicator: "Normal mode (pass keys disabled)"
    exitOnEscape: true
    singleton: "enterNormalMode"
    count: count

NormalModeCommands =
  # Scrolling.
  scrollToBottom: ->
    Marks.setPreviousPosition()
    Scroller.scrollTo "y", "max"
  scrollToTop: (count) ->
    Marks.setPreviousPosition()
    Scroller.scrollTo "y", (count - 1) * Settings.get("scrollStepSize")
  scrollToLeft: -> Scroller.scrollTo "x", 0
  scrollToRight: -> Scroller.scrollTo "x", "max"
  scrollUp: (count) -> Scroller.scrollBy "y", -1 * Settings.get("scrollStepSize") * count
  scrollDown: (count) -> Scroller.scrollBy "y", Settings.get("scrollStepSize") * count
  scrollPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1/2 * count
  scrollPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1/2 * count
  scrollFullPageUp: (count) -> Scroller.scrollBy "y", "viewSize", -1 * count
  scrollFullPageDown: (count) -> Scroller.scrollBy "y", "viewSize", 1 * count
  scrollLeft: (count) -> Scroller.scrollBy "x", -1 * Settings.get("scrollStepSize") * count
  scrollRight: (count) -> Scroller.scrollBy "x", Settings.get("scrollStepSize") * count

  # Page state.
  reload: (count, options) ->
    hard = options.registryEntry.options.hard ? false
    window.location.reload(hard)
  goBack: (count) -> history.go(-count)
  goForward: (count) -> history.go(count)

  # Url manipulation.
  goUp: (count) ->
    url = window.location.href
    if (url[url.length - 1] == "/")
      url = url.substring(0, url.length - 1)

    urlsplit = url.split("/")
    # make sure we haven't hit the base domain yet
    if (urlsplit.length > 3)
      urlsplit = urlsplit.slice(0, Math.max(3, urlsplit.length - count))
      window.location.href = urlsplit.join('/')

  goToRoot: ->
    window.location.href = window.location.origin

  toggleViewSource: ->
    chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) ->
      if (url.substr(0, 12) == "view-source:")
        url = url.substr(12, url.length - 12)
      else
        url = "view-source:" + url
      chrome.runtime.sendMessage {handler: "openUrlInNewTab", url}

  copyCurrentUrl: ->
    chrome.runtime.sendMessage { handler: "getCurrentTabUrl" }, (url) ->
      chrome.runtime.sendMessage { handler: "copyToClipboard", data: url }
      url = url[0..25] + "...." if 28 < url.length
      HUD.showForDuration("Yanked #{url}", 2000)

  # Mode changes.
  enterInsertMode: ->
    # If a focusable element receives the focus, then we exit and leave the permanently-installed insert-mode
    # instance to take over.
    new InsertMode global: true, exitOnFocus: true

  enterVisualMode: ->
    new VisualMode userLaunchedMode: true

  enterVisualLineMode: ->
    new VisualLineMode userLaunchedMode: true

  enterFindMode: ->
    Marks.setPreviousPosition()
    new FindMode()

  # Find.
  performFind: (count) -> FindMode.findNext false for [0...count] by 1
  performBackwardsFind: (count) -> FindMode.findNext true for [0...count] by 1

  # Misc.
  mainFrame: -> focusThisFrame highlight: true, forceFocusThisFrame: true
  showHelp: (sourceFrameId) -> HelpDialog.toggle {sourceFrameId, showAllCommandDetails: false}

  passNextKey: (count, options) ->
    if options.registryEntry.options.normal
      enterNormalMode count
    else
      new PassNextKeyMode count

  goPrevious: ->
    previousPatterns = Settings.get("previousPatterns") || ""
    previousStrings = previousPatterns.split(",").filter( (s) -> s.trim().length )
    findAndFollowRel("prev") || findAndFollowLink(previousStrings)

  goNext: ->
    nextPatterns = Settings.get("nextPatterns") || ""
    nextStrings = nextPatterns.split(",").filter( (s) -> s.trim().length )
    findAndFollowRel("next") || findAndFollowLink(nextStrings)

  focusInput: (count) ->
    # Focus the first input element on the page, and create overlays to highlight all the input elements, with
    # the currently-focused element highlighted specially. Tabbing will shift focus to the next input element.
    # Pressing any other key will remove the overlays and the special tab behavior.
    resultSet = DomUtils.evaluateXPath textInputXPath, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE
    visibleInputs =
      for i in [0...resultSet.snapshotLength] by 1
        element = resultSet.snapshotItem i
        continue unless DomUtils.getVisibleClientRect element, true
        { element, rect: Rect.copy element.getBoundingClientRect() }

    if visibleInputs.length == 0
      HUD.showForDuration("There are no inputs to focus.", 1000)
      return

    # This is a hack to improve usability on the Vimium options page.  We prime the recently-focused input
    # to be the key-mappings input.  Arguably, this is the input that the user is most likely to use.
    recentlyFocusedElement = lastFocusedInput()
    recentlyFocusedElement ?= document.getElementById "keyMappings" if window.isVimiumOptionsPage

    selectedInputIndex =
      if count == 1
        # As the starting index, we pick that of the most recently focused input element (or 0).
        elements = visibleInputs.map (visibleInput) -> visibleInput.element
        Math.max 0, elements.indexOf recentlyFocusedElement
      else
        Math.min(count, visibleInputs.length) - 1

    hints = for tuple in visibleInputs
      hint = DomUtils.createElement "div"
      hint.className = "vimiumReset internalVimiumInputHint vimiumInputHint"

      # minus 1 for the border
      hint.style.left = (tuple.rect.left - 1) + window.scrollX + "px"
      hint.style.top = (tuple.rect.top - 1) + window.scrollY  + "px"
      hint.style.width = tuple.rect.width + "px"
      hint.style.height = tuple.rect.height + "px"

      hint

    new FocusSelector hints, visibleInputs, selectedInputIndex

if LinkHints?
  extend NormalModeCommands,
    "LinkHints.activateMode": LinkHints.activateMode.bind LinkHints
    "LinkHints.activateModeToOpenInNewTab": LinkHints.activateModeToOpenInNewTab.bind LinkHints
    "LinkHints.activateModeToOpenInNewForegroundTab": LinkHints.activateModeToOpenInNewForegroundTab.bind LinkHints
    "LinkHints.activateModeWithQueue": LinkHints.activateModeWithQueue.bind LinkHints
    "LinkHints.activateModeToOpenIncognito": LinkHints.activateModeToOpenIncognito.bind LinkHints
    "LinkHints.activateModeToDownloadLink": LinkHints.activateModeToDownloadLink.bind LinkHints
    "LinkHints.activateModeToCopyLinkUrl": LinkHints.activateModeToCopyLinkUrl.bind LinkHints

if Vomnibar?
  extend NormalModeCommands,
    "Vomnibar.activate": Vomnibar.activate.bind Vomnibar
    "Vomnibar.activateInNewTab": Vomnibar.activateInNewTab.bind Vomnibar
    "Vomnibar.activateTabSelection": Vomnibar.activateTabSelection.bind Vomnibar
    "Vomnibar.activateBookmarks": Vomnibar.activateBookmarks.bind Vomnibar
    "Vomnibar.activateBookmarksInNewTab": Vomnibar.activateBookmarksInNewTab.bind Vomnibar
    "Vomnibar.activateEditUrl": Vomnibar.activateEditUrl.bind Vomnibar
    "Vomnibar.activateEditUrlInNewTab": Vomnibar.activateEditUrlInNewTab.bind Vomnibar

if Marks?
  extend NormalModeCommands,
    "Marks.activateCreateMode": Marks.activateCreateMode.bind Marks
    "Marks.activateGotoMode": Marks.activateGotoMode.bind Marks

# The types in <input type="..."> that we consider for focusInput command. Right now this is recalculated in
# each content script. Alternatively we could calculate it once in the background page and use a request to
# fetch it each time.
# Should we include the HTML5 date pickers here?

# The corresponding XPath for such elements.
textInputXPath = (->
  textInputTypes = [ "text", "search", "email", "url", "number", "password", "date", "tel" ]
  inputElements = ["input[" +
    "(" + textInputTypes.map((type) -> '@type="' + type + '"').join(" or ") + "or not(@type))" +
    " and not(@disabled or @readonly)]",
    "textarea", "*[@contenteditable='' or translate(@contenteditable, 'TRUE', 'true')='true']"]
  DomUtils.makeXPath(inputElements)
)()

class FocusSelector extends Mode
  constructor: (hints, visibleInputs, selectedInputIndex) ->
    super
      name: "focus-selector"
      exitOnClick: true
      keydown: (event) =>
        if event.key == "Tab"
          hints[selectedInputIndex].classList.remove 'internalVimiumSelectedInputHint'
          selectedInputIndex += hints.length + (if event.shiftKey then -1 else 1)
          selectedInputIndex %= hints.length
          hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint'
          DomUtils.simulateSelect visibleInputs[selectedInputIndex].element
          @suppressEvent
        else unless event.key == "Shift"
          @exit()
          # Give the new mode the opportunity to handle the event.
          @restartBubbling

    @hintContainingDiv = DomUtils.addElementList hints,
      id: "vimiumInputMarkerContainer"
      className: "vimiumReset"

    DomUtils.simulateSelect visibleInputs[selectedInputIndex].element
    if visibleInputs.length == 1
      @exit()
      return
    else
      hints[selectedInputIndex].classList.add 'internalVimiumSelectedInputHint'

  exit: ->
    super()
    DomUtils.removeElement @hintContainingDiv
    if document.activeElement and DomUtils.isEditable document.activeElement
      new InsertMode
        singleton: "post-find-mode/focus-input"
        targetElement: document.activeElement
        indicator: false

root = exports ? (window.root ?= {})
root.NormalMode = NormalMode
root.NormalModeCommands = NormalModeCommands
extend window, root unless exports?