]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Simplify command `esc`
[VimFx.git] / extension / lib / commands.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014.
4 # Copyright Wang Zhuochun 2013, 2014.
5 #
6 # This file is part of VimFx.
7 #
8 # VimFx is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # VimFx is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
20 ###
21
22 help = require('./help')
23 { Marker } = require('./marker')
24 utils = require('./utils')
25
26 { isProperLink, isTextInputElement, isContentEditable } = utils
27
28 { classes: Cc, interfaces: Ci, utils: Cu } = Components
29
30 XULDocument = Ci.nsIDOMXULDocument
31
32 commands = {}
33
34
35
36 commands.focus_location_bar = ({ vim }) ->
37 # This function works even if the Address Bar has been removed.
38 vim.rootWindow.focusAndSelectUrlBar()
39
40 commands.focus_search_bar = ({ vim }) ->
41 # The `.webSearch()` method opens a search engine in a tab if the Search Bar
42 # has been removed. Therefore we first check if it exists.
43 if vim.rootWindow.BrowserSearch.searchBar
44 vim.rootWindow.BrowserSearch.webSearch()
45
46 helper_paste = (vim) ->
47 url = vim.rootWindow.readFromClipboard()
48 postData = null
49 if not utils.isURL(url) and submission = utils.browserSearchSubmission(url)
50 url = submission.uri.spec
51 { postData } = submission
52 return {url, postData}
53
54 commands.paste_and_go = ({ vim }) ->
55 { url, postData } = helper_paste(vim)
56 vim.rootWindow.gBrowser.loadURIWithFlags(url, {postData})
57
58 commands.paste_and_go_in_tab = ({ vim }) ->
59 { url, postData } = helper_paste(vim)
60 vim.rootWindow.gBrowser.selectedTab =
61 vim.rootWindow.gBrowser.addTab(url, {postData})
62
63 commands.copy_current_url = ({ vim }) ->
64 utils.writeToClipboard(vim.rootWindow.gBrowser.currentURI.spec)
65
66 # Go up one level in the URL hierarchy.
67 commands.go_up_path = ({ vim, count }) ->
68 { pathname } = vim.window.location
69 vim.window.location.pathname = pathname.replace(
70 /// (?: /[^/]+ ){1,#{ count ? 1 }} /?$ ///, ''
71 )
72
73 # Go up to root of the URL hierarchy.
74 commands.go_to_root = ({ vim }) ->
75 vim.window.location.href = vim.window.location.origin
76
77 commands.go_home = ({ vim }) ->
78 vim.rootWindow.BrowserHome()
79
80 helper_go_history = (num, { vim, count }) ->
81 { gBrowser } = vim.rootWindow
82 { index, count: length } = gBrowser.sessionHistory
83 newIndex = index + num * (count ? 1)
84 newIndex = Math.max(newIndex, 0)
85 newIndex = Math.min(newIndex, length - 1)
86 gBrowser.gotoIndex(newIndex) unless newIndex == index
87
88 commands.history_back = helper_go_history.bind(null, -1)
89
90 commands.history_forward = helper_go_history.bind(null, +1)
91
92 commands.reload = ({ vim }) ->
93 vim.rootWindow.BrowserReload()
94
95 commands.reload_force = ({ vim }) ->
96 vim.rootWindow.BrowserReloadSkipCache()
97
98 commands.reload_all = ({ vim }) ->
99 vim.rootWindow.gBrowser.reloadAllTabs()
100
101 commands.reload_all_force = ({ vim }) ->
102 for tab in vim.rootWindow.gBrowser.visibleTabs
103 gBrowser = tab.linkedBrowser
104 consts = gBrowser.webNavigation
105 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
106 gBrowser.reload(flags)
107 return
108
109 commands.stop = ({ vim }) ->
110 vim.rootWindow.BrowserStop()
111
112 commands.stop_all = ({ vim }) ->
113 for tab in vim.rootWindow.gBrowser.visibleTabs
114 tab.linkedBrowser.stop()
115 return
116
117
118
119 axisMap =
120 x: ['left', 'scrollLeftMax', 'clientWidth', 'horizontalScrollDistance', 5]
121 y: ['top', 'scrollTopMax', 'clientHeight', 'verticalScrollDistance', 20]
122
123 helper_scroll = (method, type, axis, amount, { vim, event, count }) ->
124 frameDocument = event.target.ownerDocument
125 element =
126 if vim.state.scrollableElements.has(event.target)
127 event.target
128 else
129 frameDocument.documentElement
130
131 [ direction, max, dimension, distance, lineAmount ] = axisMap[axis]
132
133 if method == 'scrollTo'
134 amount = Math.min(amount, element[max])
135 else
136 unit = switch type
137 when 'lines'
138 prefs.root.get("toolkit.scrollbox.#{ distance }") * lineAmount
139 when 'pages'
140 element[dimension]
141 amount *= unit * (count ? 1)
142
143 options = {}
144 options[direction] = amount
145 if prefs.root.get('general.smoothScroll') and
146 prefs.root.get("general.smoothScroll.#{ type }")
147 options.behavior = 'smooth'
148
149 prefs.root.tmp(
150 'layout.css.scroll-behavior.spring-constant',
151 vim.parent.options["smoothScroll.#{ type }.spring-constant"],
152 ->
153 element[method](options)
154 # When scrolling the whole page, the body sometimes needs to be scrolled
155 # too.
156 if element == frameDocument.documentElement
157 frameDocument.body?[method](options)
158 )
159
160 scroll = Function::bind.bind(helper_scroll, null)
161
162 commands.scroll_left = scroll('scrollBy', 'lines', 'x', -1)
163 commands.scroll_right = scroll('scrollBy', 'lines', 'x', +1)
164 commands.scroll_down = scroll('scrollBy', 'lines', 'y', +1)
165 commands.scroll_up = scroll('scrollBy', 'lines', 'y', -1)
166 commands.scroll_page_down = scroll('scrollBy', 'pages', 'y', +1)
167 commands.scroll_page_up = scroll('scrollBy', 'pages', 'y', -1)
168 commands.scroll_half_page_down = scroll('scrollBy', 'pages', 'y', +0.5)
169 commands.scroll_half_page_up = scroll('scrollBy', 'pages', 'y', -0.5)
170 commands.scroll_to_top = scroll('scrollTo', 'other', 'y', 0)
171 commands.scroll_to_bottom = scroll('scrollTo', 'other', 'y', Infinity)
172 commands.scroll_to_left = scroll('scrollTo', 'other', 'x', 0)
173 commands.scroll_to_right = scroll('scrollTo', 'other', 'x', Infinity)
174
175
176
177 commands.tab_new = ({ vim }) ->
178 vim.rootWindow.BrowserOpenTab()
179
180 commands.tab_duplicate = ({ vim }) ->
181 { gBrowser } = vim.rootWindow
182 gBrowser.duplicateTab(gBrowser.selectedTab)
183
184 absoluteTabIndex = (relativeIndex, gBrowser) ->
185 tabs = gBrowser.visibleTabs
186 { selectedTab } = gBrowser
187
188 currentIndex = tabs.indexOf(selectedTab)
189 absoluteIndex = currentIndex + relativeIndex
190 numTabs = tabs.length
191
192 wrap = (Math.abs(relativeIndex) == 1)
193 if wrap
194 absoluteIndex %%= numTabs
195 else
196 absoluteIndex = Math.max(0, absoluteIndex)
197 absoluteIndex = Math.min(absoluteIndex, numTabs - 1)
198
199 return absoluteIndex
200
201 helper_switch_tab = (direction, { vim, count }) ->
202 { gBrowser } = vim.rootWindow
203 gBrowser.selectTabAtIndex(absoluteTabIndex(direction * (count ? 1), gBrowser))
204
205 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
206
207 commands.tab_select_next = helper_switch_tab.bind(null, +1)
208
209 helper_move_tab = (direction, { vim, count }) ->
210 { gBrowser } = vim.rootWindow
211 { selectedTab } = gBrowser
212 { pinned } = selectedTab
213
214 index = absoluteTabIndex(direction * (count ? 1), gBrowser)
215
216 if index < gBrowser._numPinnedTabs
217 gBrowser.pinTab(selectedTab) unless pinned
218 else
219 gBrowser.unpinTab(selectedTab) if pinned
220
221 gBrowser.moveTabTo(selectedTab, index)
222
223 commands.tab_move_backward = helper_move_tab.bind(null, -1)
224
225 commands.tab_move_forward = helper_move_tab.bind(null, +1)
226
227 commands.tab_select_first = ({ vim }) ->
228 vim.rootWindow.gBrowser.selectTabAtIndex(0)
229
230 commands.tab_select_first_non_pinned = ({ vim }) ->
231 firstNonPinned = vim.rootWindow.gBrowser._numPinnedTabs
232 vim.rootWindow.gBrowser.selectTabAtIndex(firstNonPinned)
233
234 commands.tab_select_last = ({ vim }) ->
235 vim.rootWindow.gBrowser.selectTabAtIndex(-1)
236
237 commands.tab_toggle_pinned = ({ vim }) ->
238 currentTab = vim.rootWindow.gBrowser.selectedTab
239 if currentTab.pinned
240 vim.rootWindow.gBrowser.unpinTab(currentTab)
241 else
242 vim.rootWindow.gBrowser.pinTab(currentTab)
243
244 commands.tab_close = ({ vim, count }) ->
245 { gBrowser } = vim.rootWindow
246 return if gBrowser.selectedTab.pinned
247 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
248 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + (count ? 1))]
249 gBrowser.removeTab(tab)
250 return
251
252 commands.tab_restore = ({ vim, count }) ->
253 vim.rootWindow.undoCloseTab() for [1..count ? 1] by 1
254
255 commands.tab_close_to_end = ({ vim }) ->
256 { gBrowser } = vim.rootWindow
257 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
258
259 commands.tab_close_other = ({ vim }) ->
260 { gBrowser } = vim.rootWindow
261 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
262
263
264
265 # Combine links with the same href.
266 combine = (hrefs, marker) ->
267 if marker.type == 'link'
268 { href } = marker.element
269 if href of hrefs
270 parent = hrefs[href]
271 marker.parent = parent
272 parent.weight += marker.weight
273 parent.numChildren++
274 else
275 hrefs[href] = marker
276 return marker
277
278 follow_callback = (vim, { inTab, inBackground }, marker, count, keyStr) ->
279 isLast = (count == 1)
280 isLink = (marker.type == 'link')
281
282 switch
283 when keyStr.startsWith(vim.parent.options.hints_toggle_in_tab)
284 inTab = not inTab
285 when keyStr.startsWith(vim.parent.options.hints_toggle_in_background)
286 inTab = true
287 inBackground = not inBackground
288 else
289 unless isLast
290 inTab = true
291 inBackground = true
292
293 inTab = false unless isLink
294
295 if marker.type == 'text' or (isLink and not (inTab and inBackground))
296 isLast = true
297
298 { element } = marker
299 utils.focusElement(element)
300
301 if inTab
302 utils.openTab(vim.rootWindow, element.href, {
303 inBackground
304 relatedToCurrent: true
305 })
306 else
307 if element.target == '_blank' and vim.parent.options.prevent_target_blank
308 targetReset = element.target
309 element.target = ''
310 utils.simulateClick(element)
311 element.target = targetReset if targetReset
312
313 return not isLast
314
315 # Follow links, focus text inputs and click buttons with hint markers.
316 commands.follow = ({ vim, count }) ->
317 hrefs = {}
318 filter = (element, getElementShape) ->
319 document = element.ownerDocument
320 isXUL = (document instanceof XULDocument)
321 semantic = true
322 switch
323 when isProperLink(element)
324 type = 'link'
325 when isTextInputElement(element) or isContentEditable(element)
326 type = 'text'
327 when element.tabIndex > -1 and
328 not (isXUL and element.nodeName.endsWith('box'))
329 type = 'clickable'
330 unless isXUL or element.nodeName in ['A', 'INPUT', 'BUTTON']
331 semantic = false
332 when element != document.documentElement and
333 vim.state.scrollableElements.has(element)
334 type = 'scrollable'
335 when element.hasAttribute('onclick') or
336 element.hasAttribute('onmousedown') or
337 element.hasAttribute('onmouseup') or
338 element.hasAttribute('oncommand') or
339 element.getAttribute('role') in ['link', 'button'] or
340 # Twitter special-case.
341 element.classList.contains('js-new-tweets-bar') or
342 # Feedly special-case.
343 element.hasAttribute('data-app-action') or
344 element.hasAttribute('data-uri') or
345 element.hasAttribute('data-page-action')
346 type = 'clickable'
347 semantic = false
348 # Putting markers on `<label>` elements is generally redundant, because
349 # its `<input>` gets one. However, some sites hide the actual `<input>`
350 # but keeps the `<label>` to click, either for styling purposes or to keep
351 # the `<input>` hidden until it is used. In those cases we should add a
352 # marker for the `<label>`.
353 when element.nodeName == 'LABEL'
354 if element.htmlFor
355 input = document.getElementById(element.htmlFor)
356 if input and not getElementShape(input)
357 type = 'clickable'
358 # Elements that have “button” somewhere in the class might be clickable,
359 # unless they contain a real link or button or yet an element with
360 # “button” somewhere in the class, in which case they likely are
361 # “button-wrapper”s. (`<SVG element>.className` is not a string!)
362 when not isXUL and typeof element.className == 'string' and
363 element.className.toLowerCase().contains('button')
364 unless element.querySelector('a, button, [class*=button]')
365 type = 'clickable'
366 semantic = false
367 # When viewing an image it should get a marker to toggle zoom.
368 when document.body?.childElementCount == 1 and
369 element.nodeName == 'IMG' and
370 (element.classList.contains('overflowing') or
371 element.classList.contains('shrinkToFit'))
372 type = 'clickable'
373 return unless type
374 return unless shape = getElementShape(element)
375 return combine(hrefs, new Marker(element, shape, {semantic, type}))
376
377 callback = follow_callback.bind(null, vim, {inTab: false, inBackground: true})
378
379 vim.enterMode('hints', filter, callback, count)
380
381 # Follow links in a new background tab with hint markers.
382 commands.follow_in_tab = ({ vim, count }, inBackground = true) ->
383 hrefs = {}
384 filter = (element, getElementShape) ->
385 return unless isProperLink(element)
386 return unless shape = getElementShape(element)
387 return combine(hrefs, new Marker(element, shape,
388 {semantic: true, type: 'link'}))
389
390 callback = follow_callback.bind(null, vim, {inTab: true, inBackground})
391
392 vim.enterMode('hints', filter, callback, count)
393
394 # Follow links in a new foreground tab with hint markers.
395 commands.follow_in_focused_tab = (args) ->
396 commands.follow_in_tab(args, false)
397
398 # Like command_follow but multiple times.
399 commands.follow_multiple = (args) ->
400 args.count = Infinity
401 commands.follow(args)
402
403 # Copy the URL or text of a markable element to the system clipboard.
404 commands.follow_copy = ({ vim }) ->
405 hrefs = {}
406 filter = (element, getElementShape) ->
407 type = switch
408 when isProperLink(element) then 'link'
409 when isTextInputElement(element) then 'textInput'
410 when isContentEditable(element) then 'contenteditable'
411 return unless type
412 return unless shape = getElementShape(element)
413 return combine(hrefs, new Marker(element, shape, {semantic: true, type}))
414
415 callback = (marker) ->
416 { element } = marker
417 text = switch marker.type
418 when 'link' then element.href
419 when 'textInput' then element.value
420 when 'contenteditable' then element.textContent
421 utils.writeToClipboard(text)
422
423 vim.enterMode('hints', filter, callback)
424
425 # Focus element with hint markers.
426 commands.follow_focus = ({ vim }) ->
427 filter = (element, getElementShape) ->
428 type = switch
429 when element.tabIndex > -1
430 'focusable'
431 when element != element.ownerDocument.documentElement and
432 vim.state.scrollableElements.has(element)
433 'scrollable'
434 return unless type
435 return unless shape = getElementShape(element)
436 return new Marker(element, shape, {semantic: true, type})
437
438 callback = (marker) ->
439 { element } = marker
440 utils.focusElement(element, {select: true})
441
442 vim.enterMode('hints', filter, callback)
443
444 helper_follow_pattern = (type, { vim }) ->
445 { document } = vim.window
446
447 # If there’s a `<link rel=prev/next>` element we use that.
448 for link in document.head?.getElementsByTagName('link')
449 # Also support `rel=previous`, just like Google.
450 if type == link.rel.toLowerCase().replace(/^previous$/, 'prev')
451 vim.rootWindow.gBrowser.loadURI(link.href)
452 return
453
454 # Otherwise we look for a link or button on the page that seems to go to the
455 # previous or next page.
456 candidates = document.querySelectorAll(vim.parent.options.pattern_selector)
457
458 # Note: Earlier patterns should be favored.
459 patterns = vim.parent.options["#{ type }_patterns"]
460
461 # Search for the prev/next patterns in the following attributes of the
462 # element. `rel` should be kept as the first attribute, since the standard way
463 # of marking up prev/next links (`rel="prev"` and `rel="next"`) should be
464 # favored. Even though some of these attributes only allow a fixed set of
465 # keywords, we pattern-match them anyways since lots of sites don’t follow the
466 # spec and use the attributes arbitrarily.
467 attrs = vim.parent.options.pattern_attrs
468
469 matchingLink = do ->
470 # Helper function that matches a string against all the patterns.
471 matches = (text) -> patterns.some((regex) -> regex.test(text))
472
473 # First search in attributes (favoring earlier attributes) as it's likely
474 # that they are more specific than text contexts.
475 for attr in attrs
476 for element in candidates
477 return element if matches(element.getAttribute(attr))
478
479 # Then search in element contents.
480 for element in candidates
481 return element if matches(element.textContent)
482
483 return null
484
485 utils.simulateClick(matchingLink) if matchingLink
486
487 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
488
489 commands.follow_next = helper_follow_pattern.bind(null, 'next')
490
491 # Focus last focused or first text input.
492 commands.focus_text_input = ({ vim, storage, count }) ->
493 { lastFocusedTextInput } = vim.state
494 inputs = Array.filter(
495 vim.window.document.querySelectorAll('input, textarea'), (element) ->
496 return utils.isTextInputElement(element) and utils.area(element) > 0
497 )
498 if lastFocusedTextInput and lastFocusedTextInput not in inputs
499 inputs.push(lastFocusedTextInput)
500 return unless inputs.length > 0
501 inputs.sort((a, b) -> a.tabIndex - b.tabIndex)
502 unless count?
503 count =
504 if lastFocusedTextInput
505 inputs.indexOf(lastFocusedTextInput) + 1
506 else
507 1
508 index = Math.min(count, inputs.length) - 1
509 utils.focusElement(inputs[index], {select: true})
510 storage.inputs = inputs
511
512 # Switch between text inputs or simulate `<tab>`.
513 helper_move_focus = (direction, { vim, storage }) ->
514 if storage.inputs
515 { inputs } = storage
516 nextInput = inputs[(storage.inputIndex + direction) %% inputs.length]
517 utils.focusElement(nextInput, {select: true})
518 else
519 focusManager = Cc['@mozilla.org/focus-manager;1']
520 .getService(Ci.nsIFocusManager)
521 direction =
522 if direction == -1
523 focusManager.MOVEFOCUS_BACKWARD
524 else
525 focusManager.MOVEFOCUS_FORWARD
526 focusManager.moveFocus(
527 null, # Use current window.
528 null, # Move relative to the currently focused element.
529 direction,
530 focusManager.FLAG_BYKEY
531 )
532
533 commands.focus_next = helper_move_focus.bind(null, +1)
534 commands.focus_previous = helper_move_focus.bind(null, -1)
535
536
537
538 findStorage = {lastSearchString: ''}
539
540 helper_find = (highlight, { vim }) ->
541 findBar = vim.rootWindow.gBrowser.getFindBar()
542
543 findBar.onFindCommand()
544 utils.focusElement(findBar._findField, {select: true})
545
546 return unless highlightButton = findBar.getElement('highlight')
547 if highlightButton.checked != highlight
548 highlightButton.click()
549
550 # Open the find bar, making sure that hightlighting is off.
551 commands.find = helper_find.bind(null, false)
552
553 # Open the find bar, making sure that hightlighting is on.
554 commands.find_highlight_all = helper_find.bind(null, true)
555
556 helper_find_again = (direction, { vim }) ->
557 findBar = vim.rootWindow.gBrowser.getFindBar()
558 if findStorage.lastSearchString.length > 0
559 findBar._findField.value = findStorage.lastSearchString
560 findBar.onFindAgainCommand(direction)
561
562 commands.find_next = helper_find_again.bind(null, false)
563
564 commands.find_previous = helper_find_again.bind(null, true)
565
566
567
568 commands.enter_mode_ignore = ({ vim }) ->
569 vim.enterMode('ignore')
570
571 # Quote next keypress (pass it through to the page).
572 commands.quote = ({ vim, count }) ->
573 vim.enterMode('ignore', count ? 1)
574
575 # Display the Help Dialog.
576 commands.help = ({ vim }) ->
577 help.injectHelp(vim.rootWindow, vim.parent)
578
579 # Open and focus the Developer Toolbar.
580 commands.dev = ({ vim }) ->
581 vim.rootWindow.DeveloperToolbar.show(true) # `true` to focus.
582
583 commands.esc = ({ vim, event }) ->
584 utils.blurActiveElement(vim.window)
585 utils.blurActiveElement(vim.rootWindow)
586
587 help.removeHelp(vim.rootWindow)
588
589 vim.rootWindow.DeveloperToolbar.hide()
590
591 vim.rootWindow.gBrowser.getFindBar().close()
592
593 vim.rootWindow.TabView.hide()
594
595 { document } = vim.window
596 if document.exitFullscreen
597 document.exitFullscreen()
598 else
599 document.mozCancelFullScreen()
600
601
602
603 module.exports = {
604 commands
605 findStorage
606 }
Imprint / Impressum