]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Fix broken `yv` command
[VimFx.git] / extension / lib / commands.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
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 # This file defines all Normal mode commands. Commands that need to interact
23 # with web page content do so by running `vim._run(name)`, which invokes `name`
24 # in commands-frame.coffee.
25
26 # NOTE: Most tab related commands need to do their actual tab manipulations in
27 # the next tick (`utils.nextTick`) to work around bug 1200334.
28
29 config = require('./config')
30 help = require('./help')
31 markableElements = require('./markable-elements')
32 MarkerContainer = require('./marker-container')
33 prefs = require('./prefs')
34 SelectionManager = require('./selection')
35 translate = require('./translate')
36 utils = require('./utils')
37 viewportUtils = require('./viewport')
38
39 {ContentClick} = Cu.import('resource:///modules/ContentClick.jsm', {})
40 {FORWARD, BACKWARD} = SelectionManager
41
42 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
43
44 commands = {}
45
46
47
48 commands.focus_location_bar = ({vim}) ->
49 vim.window.focusAndSelectUrlBar()
50
51 commands.focus_search_bar = ({vim, count}) ->
52 # The `.webSearch()` method opens a search engine in a tab if the search bar
53 # has been removed. Therefore we first check if it exists.
54 if vim.window.BrowserSearch.searchBar
55 vim.window.BrowserSearch.webSearch()
56 else
57 vim.notify(translate('notification.focus_search_bar.none'))
58
59 helper_paste_and_go = (props, {vim}) ->
60 {gURLBar} = vim.window
61 gURLBar.value = vim.window.readFromClipboard()
62 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
63
64 commands.paste_and_go = helper_paste_and_go.bind(null, null)
65
66 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
67
68 commands.copy_current_url = ({vim}) ->
69 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
70 vim.notify(translate('notification.copy_current_url.success'))
71
72 commands.go_up_path = ({vim, count}) ->
73 vim._run('go_up_path', {count})
74
75 commands.go_to_root = ({vim}) ->
76 vim._run('go_to_root')
77
78 commands.go_home = ({vim}) ->
79 vim.window.BrowserHome()
80
81 helper_go_history = (direction, {vim, count = 1}) ->
82 {window} = vim
83 {SessionStore, gBrowser} = window
84
85 if (direction == 'back' and not gBrowser.canGoBack) or
86 (direction == 'forward' and not gBrowser.canGoForward)
87 vim.notify(translate("notification.history_#{direction}.limit"))
88 return
89
90 # `SessionStore.getSessionHistory()` (used below to support counts) starts
91 # lots of asynchronous tasks internally, which is a bit unreliable, it has
92 # turned out. The primary use of the `history_back` and `history_forward`
93 # commands is to go _one_ step back or forward, though, so those cases are
94 # optimized to use more reliable ways of going back and forward. Also, some
95 # extensions override the following functions, so calling them also gives
96 # better interoperability.
97 if count == 1
98 if direction == 'back'
99 window.BrowserBack()
100 else
101 window.BrowserForward()
102 return
103
104 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
105 {index} = sessionHistory
106 newIndex = index + count * (if direction == 'back' then -1 else 1)
107 newIndex = Math.max(newIndex, 0)
108 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
109 gBrowser.gotoIndex(newIndex)
110 )
111
112 commands.history_back = helper_go_history.bind(null, 'back')
113
114 commands.history_forward = helper_go_history.bind(null, 'forward')
115
116 commands.history_list = ({vim}) ->
117 menu = vim.window.document.getElementById('backForwardMenu')
118 utils.openPopup(menu)
119 if menu.childElementCount == 0
120 vim.notify(translate('notification.history_list.none'))
121
122 commands.reload = ({vim}) ->
123 vim.window.BrowserReload()
124
125 commands.reload_force = ({vim}) ->
126 vim.window.BrowserReloadSkipCache()
127
128 commands.reload_all = ({vim}) ->
129 vim.window.gBrowser.reloadAllTabs()
130
131 commands.reload_all_force = ({vim}) ->
132 for tab in vim.window.gBrowser.visibleTabs
133 gBrowser = tab.linkedBrowser
134 consts = gBrowser.webNavigation
135 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
136 gBrowser.reload(flags)
137 return
138
139 commands.stop = ({vim}) ->
140 vim.window.BrowserStop()
141
142 commands.stop_all = ({vim}) ->
143 for tab in vim.window.gBrowser.visibleTabs
144 tab.linkedBrowser.stop()
145 return
146
147
148
149 springConstant = {
150 nonce: null
151 value: null
152 }
153
154 helper_scroll = (vim, uiEvent, args...) ->
155 [
156 method, type, directions, amounts
157 properties = null, adjustment = 0, name = 'scroll'
158 ] = args
159 options = {
160 method, type, directions, amounts, properties, adjustment
161 smooth: (
162 prefs.root.get('general.smoothScroll') and
163 prefs.root.get("general.smoothScroll.#{type}")
164 )
165 }
166
167 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
168 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
169 # scrolling command was invoked.
170 springConstant.nonce = nonce = {}
171 springConstant.value ?= prefs.root.get(SPRING_CONSTANT_PREF)
172 prefs.root.set(
173 SPRING_CONSTANT_PREF,
174 vim.options["smoothScroll.#{type}.spring-constant"]
175 )
176 reset = ->
177 vim.window.setTimeout((->
178 return unless springConstant.nonce == nonce
179 prefs.root.set(SPRING_CONSTANT_PREF, springConstant.value)
180 springConstant.nonce = null
181 springConstant.value = null
182 ), vim.options['scroll.reset_timeout'])
183
184 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
185 if uiEvent or helpScroll
186 activeElement = helpScroll or utils.getActiveElement(vim.window)
187 if vim._state.scrollableElements.has(activeElement) or helpScroll
188 viewportUtils.scroll(activeElement, options)
189 reset()
190 return
191
192 vim._run(name, options, reset)
193
194
195 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
196 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
197 helper_scroll(
198 vim, uiEvent, 'scrollBy', 'lines', ['left'], [amount * distance * count * 5]
199 )
200
201 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
202 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
203 helper_scroll(
204 vim, uiEvent, 'scrollBy', 'lines', ['top'], [amount * distance * count * 20]
205 )
206
207 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
208 adjustment = vim.options["scroll.#{type}_page_adjustment"]
209 helper_scroll(
210 vim, uiEvent, 'scrollBy', 'pages', ['top'], [amount * count],
211 ['clientHeight'], adjustment
212 )
213
214 helper_scrollToX = (amount, {vim, uiEvent}) ->
215 helper_mark_last_scroll_position(vim)
216 helper_scroll(
217 vim, uiEvent, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
218 )
219
220 helper_scrollToY = (amount, {vim, uiEvent}) ->
221 helper_mark_last_scroll_position(vim)
222 helper_scroll(
223 vim, uiEvent, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
224 )
225
226 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
227 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
228 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
229 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
230 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
231 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
232 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
233 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
234 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
235 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
236 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
237 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
238
239 helper_mark_last_scroll_position = (vim) ->
240 keyStr = vim.options['scroll.last_position_mark']
241 vim._run('mark_scroll_position', {keyStr, notify: false})
242
243 commands.mark_scroll_position = ({vim}) ->
244 vim._enterMode('marks', (keyStr) ->
245 vim._run('mark_scroll_position', {keyStr})
246 )
247 vim.notify(translate('notification.mark_scroll_position.enter'))
248
249 commands.scroll_to_mark = ({vim}) ->
250 vim._enterMode('marks', (keyStr) ->
251 unless keyStr == vim.options['scroll.last_position_mark']
252 helper_mark_last_scroll_position(vim)
253 helper_scroll(
254 vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
255 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark'
256 )
257 )
258 vim.notify(translate('notification.scroll_to_mark.enter'))
259
260
261
262 commands.tab_new = ({vim}) ->
263 utils.nextTick(vim.window, ->
264 vim.window.BrowserOpenTab()
265 )
266
267 commands.tab_new_after_current = ({vim}) ->
268 {window} = vim
269 newTabPosition = window.gBrowser.selectedTab._tPos + 1
270 utils.nextTick(window, ->
271 utils.listenOnce(window, 'TabOpen', (event) ->
272 newTab = event.originalTarget
273 window.gBrowser.moveTabTo(newTab, newTabPosition)
274 )
275 window.BrowserOpenTab()
276 )
277
278 commands.tab_duplicate = ({vim}) ->
279 {gBrowser} = vim.window
280 utils.nextTick(vim.window, ->
281 gBrowser.duplicateTab(gBrowser.selectedTab)
282 )
283
284 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
285 tabs = gBrowser.visibleTabs
286 {selectedTab} = gBrowser
287
288 currentIndex = tabs.indexOf(selectedTab)
289 absoluteIndex = currentIndex + relativeIndex
290 numTabsTotal = tabs.length
291 numPinnedTabs = gBrowser._numPinnedTabs
292
293 [numTabs, min] = switch
294 when not pinnedSeparate
295 [numTabsTotal, 0]
296 when selectedTab.pinned
297 [numPinnedTabs, 0]
298 else
299 [numTabsTotal - numPinnedTabs, numPinnedTabs]
300
301 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
302 # current direction.
303 if (relativeIndex < 0 and currentIndex == min) or
304 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
305 if absoluteIndex < min
306 absoluteIndex += numTabs
307 else if absoluteIndex >= min + numTabs
308 absoluteIndex -= numTabs
309
310 absoluteIndex = Math.max(min, absoluteIndex)
311 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
312
313 return absoluteIndex
314
315 helper_switch_tab = (direction, {vim, count = 1}) ->
316 {gBrowser} = vim.window
317 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
318 utils.nextTick(vim.window, ->
319 gBrowser.selectTabAtIndex(index)
320 )
321
322 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
323
324 commands.tab_select_next = helper_switch_tab.bind(null, +1)
325
326 helper_is_visited = (tab) ->
327 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
328
329 commands.tab_select_most_recent = ({vim, count = 1}) ->
330 {gBrowser} = vim.window
331 tabsSorted =
332 Array.filter(
333 gBrowser.tabs,
334 (tab) -> not tab.closing and helper_is_visited(tab)
335 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
336 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
337 if tab
338 gBrowser.selectedTab = tab
339 else
340 vim.notify(translate('notification.tab_select_most_recent.none'))
341
342 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
343 {gBrowser} = vim.window
344 tabsSorted =
345 Array.filter(
346 gBrowser.tabs,
347 (tab) -> not tab.closing and not helper_is_visited(tab)
348 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
349 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
350 if tab
351 gBrowser.selectedTab = tab
352 else
353 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
354
355 helper_move_tab = (direction, {vim, count = 1}) ->
356 {gBrowser} = vim.window
357 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
358 utils.nextTick(vim.window, ->
359 gBrowser.moveTabTo(gBrowser.selectedTab, index)
360 )
361
362 commands.tab_move_backward = helper_move_tab.bind(null, -1)
363
364 commands.tab_move_forward = helper_move_tab.bind(null, +1)
365
366 commands.tab_move_to_window = ({vim}) ->
367 {gBrowser} = vim.window
368 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
369
370 commands.tab_select_first = ({vim, count = 1}) ->
371 utils.nextTick(vim.window, ->
372 vim.window.gBrowser.selectTabAtIndex(count - 1)
373 )
374
375 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
376 firstNonPinned = vim.window.gBrowser._numPinnedTabs
377 utils.nextTick(vim.window, ->
378 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
379 )
380
381 commands.tab_select_last = ({vim, count = 1}) ->
382 utils.nextTick(vim.window, ->
383 vim.window.gBrowser.selectTabAtIndex(-count)
384 )
385
386 commands.tab_toggle_pinned = ({vim}) ->
387 currentTab = vim.window.gBrowser.selectedTab
388 if currentTab.pinned
389 vim.window.gBrowser.unpinTab(currentTab)
390 else
391 vim.window.gBrowser.pinTab(currentTab)
392
393 commands.tab_close = ({vim, count = 1}) ->
394 {gBrowser} = vim.window
395 return if gBrowser.selectedTab.pinned
396 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
397 utils.nextTick(vim.window, ->
398 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
399 gBrowser.removeTab(tab)
400 return
401 )
402
403 commands.tab_restore = ({vim, count = 1}) ->
404 utils.nextTick(vim.window, ->
405 for index in [0...count] by 1
406 restoredTab = vim.window.undoCloseTab()
407 if not restoredTab and index == 0
408 vim.notify(translate('notification.tab_restore.none'))
409 break
410 return
411 )
412
413 commands.tab_restore_list = ({vim}) ->
414 {window} = vim
415 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
416 window, 'menuitem'
417 )
418 if fragment.childElementCount == 0
419 vim.notify(translate('notification.tab_restore.none'))
420 else
421 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
422
423 commands.tab_close_to_end = ({vim}) ->
424 {gBrowser} = vim.window
425 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
426
427 commands.tab_close_other = ({vim}) ->
428 {gBrowser} = vim.window
429 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
430
431
432
433 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
434 {window} = vim
435 vim.markPageInteraction()
436 help.removeHelp(window)
437
438 markerContainer = new MarkerContainer({
439 window
440 hintChars: vim.options.hint_chars
441 getComplementaryWrappers: (callback) ->
442 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
443 # `markerContainer.container` is `null`ed out when leaving Hints mode.
444 # If this callback is called after we’ve left Hints mode (and perhaps
445 # even entered it again), simply discard the result.
446 return unless markerContainer.container
447 if wrappers.length == 0
448 vim.notify(translate('notification.follow.none'))
449 callback({wrappers, viewport})
450 )
451 })
452 MarkerContainer.remove(window) # Better safe than sorry.
453 window.gBrowser.selectedBrowser.parentNode.appendChild(
454 markerContainer.container
455 )
456
457 chooseCallback = (marker, timesLeft, keyStr) ->
458 if callbackOverride
459 {type, href = null, elementIndex} = marker.wrapper
460 return callbackOverride({type, href, id: elementIndex, timesLeft})
461 else
462 return callback(marker, timesLeft, keyStr)
463
464 # Enter Hints mode immediately, with an empty set of markers. The user might
465 # press keys before any hints have been generated. Those key presses should be
466 # handled in Hints mode, not Normal mode.
467 vim._enterMode('hints', {
468 markerContainer, count
469 callback: chooseCallback
470 sleep: vim.options.hints_sleep
471 })
472
473 injectHints = ({wrappers, viewport, pass}) ->
474 # See `getComplementaryWrappers` above.
475 return unless markerContainer.container
476
477 if wrappers.length == 0
478 if pass in ['single', 'second'] and markerContainer.markers.length == 0
479 vim.notify(translate('notification.follow.none'))
480 vim._enterMode('normal')
481 else
482 markerContainer.injectHints(wrappers, viewport, pass)
483
484 if pass == 'first'
485 vim._run(name, {pass: 'second'}, injectHints)
486
487 vim._run(name, {pass: 'auto'}, injectHints)
488
489 helper_follow_clickable = (options, args) ->
490 {vim} = args
491
492 callback = (marker, timesLeft, keyStr) ->
493 {inTab, inBackground} = options
494 {type, elementIndex} = marker.wrapper
495 isLast = (timesLeft == 1)
496 isLink = (type == 'link')
497 {window} = vim
498
499 switch
500 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
501 inTab = not inTab
502 when keyStr.startsWith(vim.options.hints_toggle_in_background)
503 inTab = true
504 inBackground = not inBackground
505 else
506 unless isLast
507 inTab = true
508 inBackground = true
509
510 inTab = false unless isLink
511
512 if type == 'text' or (isLink and not (inTab and inBackground))
513 isLast = true
514
515 vim._focusMarkerElement(elementIndex)
516
517 if inTab
518 utils.nextTick(window, ->
519 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
520 # links using the mouse. Using that instead of simply
521 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
522 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
523 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
524 ContentClick.contentAreaClick({
525 href: marker.wrapper.href
526 shiftKey: not inBackground
527 ctrlKey: true
528 metaKey: true
529 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
530 }, vim.browser)
531 reset()
532 )
533 else
534 vim._run('click_marker_element', {
535 elementIndex, type
536 preventTargetBlank: vim.options.prevent_target_blank
537 })
538
539 return not isLast
540
541 name = if options.inTab then 'follow_in_tab' else 'follow'
542 helper_follow({name, callback}, args)
543
544 commands.follow =
545 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
546
547 commands.follow_in_tab =
548 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
549
550 commands.follow_in_focused_tab =
551 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
552
553 commands.follow_in_window = (args) ->
554 {vim} = args
555
556 callback = (marker) ->
557 vim._focusMarkerElement(marker.wrapper.elementIndex)
558 {href} = marker.wrapper
559 vim.window.openLinkIn(href, 'window', {}) if href
560 return false
561
562 helper_follow({name: 'follow_in_tab', callback}, args)
563
564 commands.follow_multiple = (args) ->
565 args.count = Infinity
566 commands.follow(args)
567
568 commands.follow_copy = (args) ->
569 {vim} = args
570
571 callback = (marker) ->
572 property = switch marker.wrapper.type
573 when 'link'
574 'href'
575 when 'text'
576 'value'
577 when 'contenteditable', 'complementary'
578 '_selection'
579 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
580 return false
581
582 helper_follow({name: 'follow_copy', callback}, args)
583
584 commands.follow_focus = (args) ->
585 {vim} = args
586
587 callback = (marker) ->
588 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
589 return false
590
591 helper_follow({name: 'follow_focus', callback}, args)
592
593 commands.click_browser_element = ({vim}) ->
594 {window} = vim
595 markerElements = []
596
597 getButtonMenu = (element) ->
598 if element.localName == 'dropmarker' and
599 element.parentNode?.localName == 'toolbarbutton'
600 return element.parentNode.querySelector('menupopup')
601 else
602 return null
603
604 filter = ({complementary}, element, getElementShape) ->
605 type = switch
606 when vim._state.scrollableElements.has(element)
607 'scrollable'
608 when getButtonMenu(element)
609 'dropmarker'
610 when utils.isFocusable(element) or
611 (element.onclick and element.localName != 'statuspanel')
612 'clickable'
613
614 if complementary
615 type = if type then null else 'complementary'
616
617 return unless type
618
619 # `getElementShape(element, -1)` is intentionally _not_ used in the
620 # `complementary` run, because it results in tons of useless hints for
621 # hidden context menus.
622 shape = getElementShape(element)
623 return unless shape.nonCoveredPoint
624
625 length = markerElements.push(element)
626 return {type, shape, elementIndex: length - 1}
627
628 callback = (marker) ->
629 element = markerElements[marker.wrapper.elementIndex]
630 switch marker.wrapper.type
631 when 'scrollable'
632 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
633 when 'dropmarker'
634 getButtonMenu(element).openPopup(
635 element.parentNode, # Anchor node.
636 'after_end', # Position.
637 0, 0, # Offset.
638 false, # Isn’t a context menu.
639 true, # Allow the 'position' attribute to override the above position.
640 )
641 when 'clickable', 'complementary'
642 # VimFx’s own button won’t trigger unless the click is simulated in the
643 # next tick. This might be true for other buttons as well.
644 utils.nextTick(window, ->
645 utils.focusElement(element)
646 switch
647 when element.localName == 'tab'
648 # Only 'mousedown' seems to be able to activate tabs.
649 utils.simulateMouseEvents(element, ['mousedown'])
650 when element.closest('tab')
651 # If `.click()` is used on a tab close button, its tab will be
652 # selected first, which might cause the selected tab to change.
653 utils.simulateMouseEvents(element, 'click-xul')
654 else
655 # `.click()` seems to trigger more buttons (such as NoScript’s
656 # button and Firefox’s “hamburger” menu button) than simulating
657 # 'click-xul'.
658 element.click()
659 utils.openDropdown(element)
660 )
661 return false
662
663 wrappers = markableElements.find(
664 window, filter.bind(null, {complementary: false})
665 )
666
667 if wrappers.length > 0
668 viewport = viewportUtils.getWindowViewport(window)
669
670 markerContainer = new MarkerContainer({
671 window
672 hintChars: vim.options.hint_chars
673 adjustZoom: false
674 getComplementaryWrappers: (callback) ->
675 newWrappers = markableElements.find(
676 window, filter.bind(null, {complementary: true})
677 )
678 callback({wrappers: newWrappers, viewport})
679 })
680 MarkerContainer.remove(window) # Better safe than sorry.
681 markerContainer.container.classList.add('ui')
682 window.document.getElementById('browser-panel').appendChild(
683 markerContainer.container
684 )
685
686 markerContainer.injectHints(wrappers, viewport, 'single')
687 vim._enterMode('hints', {markerContainer, callback})
688
689 else
690 vim.notify(translate('notification.follow.none'))
691
692 helper_follow_pattern = (type, {vim}) ->
693 options = {
694 pattern_selector: vim.options.pattern_selector
695 pattern_attrs: vim.options.pattern_attrs
696 patterns: vim.options["#{type}_patterns"]
697 }
698 vim._run('follow_pattern', {type, options})
699
700 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
701
702 commands.follow_next = helper_follow_pattern.bind(null, 'next')
703
704 commands.focus_text_input = ({vim, count}) ->
705 vim.markPageInteraction()
706 vim._run('focus_text_input', {count})
707
708 helper_follow_selectable = ({select}, args) ->
709 {vim} = args
710
711 callback = (marker) ->
712 vim._run('element_text_select', {
713 elementIndex: marker.wrapper.elementIndex
714 full: select
715 scroll: select
716 })
717 vim._enterMode('caret', {select})
718 return false
719
720 helper_follow({name: 'follow_selectable', callback}, args)
721
722 commands.element_text_caret =
723 helper_follow_selectable.bind(null, {select: false})
724
725 commands.element_text_select =
726 helper_follow_selectable.bind(null, {select: true})
727
728 commands.element_text_copy = (args) ->
729 {vim} = args
730
731 callback = (marker) ->
732 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
733 return false
734
735 helper_follow({name: 'follow_selectable', callback}, args)
736
737 helper_copy_marker_element = (vim, elementIndex, property) ->
738 if property == '_selection'
739 # Selecting the text and then copying that selection is better than copying
740 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
741 # and then includes those backticks in the compiled output (!), in hidden
742 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
743 # elements, text selection gives better whitespace than `.textContent`.
744 vim._run('element_text_select', {elementIndex, full: true}, ->
745 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
746 vim._run('clear_selection')
747 )
748 else
749 vim._run('copy_marker_element', {elementIndex, property})
750
751
752
753 findStorage = {
754 lastSearchString: ''
755 busy: false
756 }
757
758 helper_find_from_top_of_viewport = (vim, direction, callback) ->
759 return if findStorage.busy
760 if vim.options.find_from_top_of_viewport
761 findStorage.busy = true
762 vim._run('find_from_top_of_viewport', {direction}, ->
763 findStorage.busy = false
764 callback()
765 )
766 else
767 callback()
768
769 helper_find = ({highlight, linksOnly = false}, {vim}) ->
770 helpSearchInput = help.getSearchInput(vim.window)
771 if helpSearchInput
772 helpSearchInput.select()
773 return
774
775 # In case `helper_find_from_top_of_viewport` is slow, make sure that keys
776 # pressed before the find bar input is focsued doesn’t trigger commands.
777 vim._enterMode('find')
778
779 helper_mark_last_scroll_position(vim)
780 helper_find_from_top_of_viewport(vim, FORWARD, ->
781 return unless vim.mode == 'find'
782 findBar = vim.window.gBrowser.getFindBar()
783
784 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
785 findBar.startFind(mode)
786 utils.focusElement(findBar._findField, {select: true})
787
788 return if linksOnly
789 return unless highlightButton = findBar.getElement('highlight')
790 if highlightButton.checked != highlight
791 highlightButton.click()
792 )
793
794 commands.find = helper_find.bind(null, {highlight: false})
795
796 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
797
798 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
799
800 helper_find_again = (direction, {vim}) ->
801 findBar = vim.window.gBrowser.getFindBar()
802 if findStorage.lastSearchString.length == 0
803 vim.notify(translate('notification.find_again.none'))
804 return
805
806 helper_mark_last_scroll_position(vim)
807 helper_find_from_top_of_viewport(vim, direction, ->
808 findBar._findField.value = findStorage.lastSearchString
809
810 # Temporarily hack `.onFindResult` to be able to know when the asynchronous
811 # `.onFindAgainCommand` is done.
812 originalOnFindResult = findBar.onFindResult
813 findBar.onFindResult = (data) ->
814 # Prevent the find bar from re-opening if there are no matches.
815 data.storeResult = false
816 findBar.onFindResult = originalOnFindResult
817 findBar.onFindResult(data)
818 message = findBar._findStatusDesc.textContent
819 vim.notify(message) if message
820
821 findBar.onFindAgainCommand(not direction)
822 )
823
824 commands.find_next = helper_find_again.bind(null, FORWARD)
825
826 commands.find_previous = helper_find_again.bind(null, BACKWARD)
827
828
829
830 commands.window_new = ({vim}) ->
831 vim.window.OpenBrowserWindow()
832
833 commands.window_new_private = ({vim}) ->
834 vim.window.OpenBrowserWindow({private: true})
835
836 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
837 type = if blacklist then 'blacklist' else 'explicit'
838 vim._enterMode('ignore', {type})
839
840 # Quote next keypress (pass it through to the page).
841 commands.quote = ({vim, count = 1}) ->
842 vim._enterMode('ignore', {type: 'explicit', count})
843
844 commands.enter_reader_view = ({vim}) ->
845 button = vim.window.document.getElementById('reader-mode-button')
846 if not button?.hidden
847 button.click()
848 else
849 vim.notify(translate('notification.enter_reader_view.none'))
850
851 commands.reload_config_file = ({vim}) ->
852 vim._parent.emit('shutdown')
853 config.load(vim._parent, (status) -> switch status
854 when null
855 vim.notify(translate('notification.reload_config_file.none'))
856 when true
857 vim.notify(translate('notification.reload_config_file.success'))
858 else
859 vim.notify(translate('notification.reload_config_file.failure'))
860 )
861
862 commands.help = ({vim}) ->
863 help.toggleHelp(vim.window, vim._parent)
864
865 commands.dev = ({vim}) ->
866 vim.window.DeveloperToolbar.show(true) # `true` to focus.
867
868 commands.esc = ({vim}) ->
869 vim._run('esc')
870 utils.blurActiveBrowserElement(vim)
871 vim.window.gBrowser.getFindBar().close()
872 MarkerContainer.remove(vim.window) # Better safe than sorry.
873
874 # Calling `.hide()` when the toolbar is not open can destroy it for the rest
875 # of the Firefox session. The code here is taken from the `.toggle()` method.
876 {DeveloperToolbar} = vim.window
877 if DeveloperToolbar.visible
878 DeveloperToolbar.hide().catch(console.error)
879
880 unless help.getSearchInput(vim.window)?.getAttribute('focused')
881 help.removeHelp(vim.window)
882
883 vim._setFocusType('none') # Better safe than sorry.
884
885
886
887 module.exports = {
888 commands
889 findStorage
890 }
Imprint / Impressum