]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
improve contentAreaClick
[VimFx.git] / extension / lib / commands.coffee
1 # This file defines all Normal mode commands. Commands that need to interact
2 # with web page content do so by running `vim._run(name)`, which invokes `name`
3 # in commands-frame.coffee.
4
5 # NOTE: Most tab related commands need to do their actual tab manipulations in
6 # the next tick (`utils.nextTick`) to work around bug 1200334.
7
8 config = require('./config')
9 help = require('./help')
10 markableElements = require('./markable-elements')
11 MarkerContainer = require('./marker-container')
12 parsePrefs = require('./parse-prefs')
13 prefs = require('./prefs')
14 SelectionManager = require('./selection')
15 translate = require('./translate')
16 utils = require('./utils')
17 viewportUtils = require('./viewport')
18
19 {FORWARD, BACKWARD} = SelectionManager
20
21 READER_VIEW_PREFIX = 'about:reader?url='
22 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
23 USER_CONTEXT_ID_ATTRIBUTE_NAME = 'usercontextid'
24
25 commands = {}
26
27
28
29 commands.focus_location_bar = ({vim}) ->
30 vim.window.gURLBar.select()
31
32 commands.focus_search_bar = ({vim, count}) ->
33 # The `.webSearch()` method opens a search engine in a tab if the search bar
34 # has been removed. Therefore we first check if it exists.
35 if vim.window.BrowserSearch.searchBar
36 vim.window.BrowserSearch.webSearch()
37 else
38 vim.notify(translate('notification.focus_search_bar.none'))
39
40 helper_paste_and_go = (props, {vim}) ->
41 {gURLBar} = vim.window
42 gURLBar.value = vim.window.readFromClipboard()
43 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
44
45 commands.paste_and_go = helper_paste_and_go.bind(null, null)
46
47 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
48
49 commands.copy_current_url = ({vim}) ->
50 url = vim.window.gBrowser.currentURI.spec
51 adjustedUrl =
52 if url.startsWith(READER_VIEW_PREFIX)
53 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
54 else
55 url
56 utils.writeToClipboard(adjustedUrl)
57 vim.notify(translate('notification.copy_current_url.success'))
58
59 commands.go_up_path = ({vim, count}) ->
60 vim._run('go_up_path', {count})
61
62 commands.go_to_root = ({vim}) ->
63 vim._run('go_to_root')
64
65 commands.go_home = ({vim}) ->
66 vim.window.BrowserHome()
67
68 helper_go_history = (direction, {vim, count = 1}) ->
69 {window} = vim
70 {SessionStore, gBrowser} = window
71
72 if (direction == 'back' and not gBrowser.canGoBack) or
73 (direction == 'forward' and not gBrowser.canGoForward)
74 vim.notify(translate("notification.history_#{direction}.limit"))
75 return
76
77 # `SessionStore.getSessionHistory()` (used below to support counts) starts
78 # lots of asynchronous tasks internally, which is a bit unreliable, it has
79 # turned out. The primary use of the `history_back` and `history_forward`
80 # commands is to go _one_ step back or forward, though, so those cases are
81 # optimized to use more reliable ways of going back and forward. Also, some
82 # extensions override the following functions, so calling them also gives
83 # better interoperability.
84 if count == 1
85 if direction == 'back'
86 window.BrowserBack()
87 else
88 window.BrowserForward()
89 return
90
91 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
92 {index} = sessionHistory
93 newIndex = index + count * (if direction == 'back' then -1 else 1)
94 newIndex = Math.max(newIndex, 0)
95 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
96 gBrowser.gotoIndex(newIndex)
97 )
98
99 commands.history_back = helper_go_history.bind(null, 'back')
100
101 commands.history_forward = helper_go_history.bind(null, 'forward')
102
103 commands.history_list = ({vim}) ->
104 menu = vim.window.document.getElementById('backForwardMenu')
105 utils.openPopup(menu)
106 if menu.childElementCount == 0
107 vim.notify(translate('notification.history_list.none'))
108
109 commands.reload = ({vim}) ->
110 vim.window.BrowserReload()
111
112 commands.reload_force = ({vim}) ->
113 vim.window.BrowserReloadSkipCache()
114
115 commands.reload_all = ({vim}) ->
116 vim.window.gBrowser.reloadAllTabs()
117
118 commands.reload_all_force = ({vim}) ->
119 for tab in vim.window.gBrowser.visibleTabs
120 gBrowser = tab.linkedBrowser
121 consts = gBrowser.webNavigation
122 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
123 gBrowser.reload(flags)
124 return
125
126 commands.stop = ({vim}) ->
127 vim.window.BrowserStop()
128
129 commands.stop_all = ({vim}) ->
130 for tab in vim.window.gBrowser.visibleTabs
131 tab.linkedBrowser.stop()
132 return
133
134
135
136 scrollData = {
137 nonce: null
138 springConstant: null
139 lastRepeat: 0
140 }
141
142 helper_scroll = (vim, event, args...) ->
143 [
144 method, type, directions, amounts
145 properties = null, adjustment = 0, name = 'scroll', extra = {}
146 ] = args
147
148 elapsed = event.timeStamp - scrollData.lastRepeat
149
150 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
151 return
152
153 scrollData.lastRepeat = event.timeStamp
154
155 options = {
156 method, type, directions, amounts, properties, adjustment, extra
157 smooth: (
158 prefs.root.get('general.smoothScroll') and
159 prefs.root.get("general.smoothScroll.#{type}")
160 )
161 }
162
163 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
164 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
165 # scrolling command was invoked.
166 scrollData.nonce = nonce = {}
167 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
168 prefs.root.set(
169 SPRING_CONSTANT_PREF,
170 vim.options["smoothScroll.#{type}.spring-constant"]
171 )
172 reset = ->
173 vim.window.setTimeout((->
174 return unless scrollData.nonce == nonce
175 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
176 scrollData.nonce = null
177 scrollData.springConstant = null
178 ), vim.options['scroll.reset_timeout'])
179
180 {isUIEvent = vim.isUIEvent(event)} = extra
181 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
182 if isUIEvent or helpScroll
183 activeElement = helpScroll or utils.getActiveElement(vim.window)
184 if vim._state.scrollableElements.has(activeElement) or helpScroll
185 viewportUtils.scroll(activeElement, options)
186 reset()
187 return
188
189 vim._run(name, options, reset)
190
191
192 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
193 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
194 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
195 helper_scroll(
196 vim, event, 'scrollBy', 'lines', ['left'],
197 [amount * distance * boost * count * 5]
198 )
199
200 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
201 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
202 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
203 helper_scroll(
204 vim, event, 'scrollBy', 'lines', ['top'],
205 [amount * distance * boost * count * 20]
206 )
207
208 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
209 adjustment = vim.options["scroll.#{type}_page_adjustment"]
210 helper_scroll(
211 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
212 ['clientHeight'], adjustment
213 )
214
215 helper_scrollToX = (amount, {vim, event}) ->
216 helper_mark_last_scroll_position(vim)
217 helper_scroll(
218 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
219 )
220
221 helper_scrollToY = (amount, {vim, event}) ->
222 helper_mark_last_scroll_position(vim)
223 helper_scroll(
224 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
225 )
226
227 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
228 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
229 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
230 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
231 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
232 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
233 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
234 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
235 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
236 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
237 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
238 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
239
240 helper_mark_last_scroll_position = (vim) ->
241 keyStr = vim.options['scroll.last_position_mark']
242 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
243
244 commands.mark_scroll_position = ({vim}) ->
245 vim._enterMode('marks', (keyStr) ->
246 vim._run('mark_scroll_position', {keyStr})
247 )
248 vim.notify(translate('notification.mark_scroll_position.enter'))
249
250 commands.scroll_to_mark = ({vim, event}) ->
251 vim._enterMode('marks', (keyStr) ->
252 lastPositionMark = vim.options['scroll.last_position_mark']
253 helper_scroll(
254 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
255 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
256 {keyStr, lastPositionMark, isUIEvent: false}
257 )
258 vim.hideNotification()
259 )
260 vim.notify(translate('notification.scroll_to_mark.enter'))
261
262 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
263 lastPositionMark = vim.options['scroll.last_position_mark']
264 helper_scroll(
265 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
266 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
267 {count, direction, lastPositionMark, isUIEvent: false}
268 )
269
270 commands.scroll_to_previous_position =
271 helper_scroll_to_position.bind(null, 'previous')
272
273 commands.scroll_to_next_position =
274 helper_scroll_to_position.bind(null, 'next')
275
276
277
278 commands.tab_new = ({vim}) ->
279 utils.nextTick(vim.window, ->
280 vim.window.BrowserOpenTab()
281 )
282
283 commands.tab_new_after_current = ({vim}) ->
284 {window} = vim
285 newTabPosition = window.gBrowser.selectedTab._tPos + 1
286 utils.nextTick(window, ->
287 utils.listenOnce(window, 'TabOpen', (event) ->
288 newTab = event.originalTarget
289 window.gBrowser.moveTabTo(newTab, newTabPosition)
290 )
291 window.BrowserOpenTab()
292 )
293
294 commands.tab_duplicate = ({vim}) ->
295 {gBrowser} = vim.window
296 utils.nextTick(vim.window, ->
297 gBrowser.duplicateTab(gBrowser.selectedTab)
298 )
299
300 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
301 tabs = gBrowser.visibleTabs
302 {selectedTab} = gBrowser
303
304 currentIndex = tabs.indexOf(selectedTab)
305 absoluteIndex = currentIndex + relativeIndex
306 numTabsTotal = tabs.length
307 numPinnedTabs = gBrowser._numPinnedTabs
308
309 [numTabs, min] = switch
310 when not pinnedSeparate
311 [numTabsTotal, 0]
312 when selectedTab.pinned
313 [numPinnedTabs, 0]
314 else
315 [numTabsTotal - numPinnedTabs, numPinnedTabs]
316
317 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
318 # current direction.
319 if (relativeIndex < 0 and currentIndex == min) or
320 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
321 if absoluteIndex < min
322 absoluteIndex += numTabs
323 else if absoluteIndex >= min + numTabs
324 absoluteIndex -= numTabs
325
326 absoluteIndex = Math.max(min, absoluteIndex)
327 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
328
329 return absoluteIndex
330
331 helper_switch_tab = (direction, {vim, count = 1}) ->
332 {gBrowser} = vim.window
333 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
334 utils.nextTick(vim.window, ->
335 gBrowser.selectTabAtIndex(index)
336 )
337
338 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
339
340 commands.tab_select_next = helper_switch_tab.bind(null, +1)
341
342 helper_is_visited = (tab) ->
343 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
344
345 commands.tab_select_most_recent = ({vim, count = 1}) ->
346 {gBrowser} = vim.window
347 tabsSorted =
348 Array.prototype.filter.call(
349 gBrowser.tabs,
350 (tab) -> not tab.closing and helper_is_visited(tab)
351 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
352 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
353 if tab
354 gBrowser.selectedTab = tab
355 else
356 vim.notify(translate('notification.tab_select_most_recent.none'))
357
358 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
359 {gBrowser} = vim.window
360 tabsSorted =
361 Array.prototype.filter.call(
362 gBrowser.tabs,
363 (tab) -> not tab.closing and not helper_is_visited(tab)
364 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
365 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
366 if tab
367 gBrowser.selectedTab = tab
368 else
369 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
370
371 helper_move_tab = (direction, {vim, count = 1}) ->
372 {gBrowser} = vim.window
373 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
374 utils.nextTick(vim.window, ->
375 gBrowser.moveTabTo(gBrowser.selectedTab, index)
376 )
377
378 commands.tab_move_backward = helper_move_tab.bind(null, -1)
379
380 commands.tab_move_forward = helper_move_tab.bind(null, +1)
381
382 commands.tab_move_to_window = ({vim}) ->
383 {gBrowser} = vim.window
384 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
385
386 commands.tab_select_first = ({vim, count = 1}) ->
387 utils.nextTick(vim.window, ->
388 vim.window.gBrowser.selectTabAtIndex(count - 1)
389 )
390
391 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
392 firstNonPinned = vim.window.gBrowser._numPinnedTabs
393 utils.nextTick(vim.window, ->
394 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
395 )
396
397 commands.tab_select_last = ({vim, count = 1}) ->
398 utils.nextTick(vim.window, ->
399 vim.window.gBrowser.selectTabAtIndex(-count)
400 )
401
402 commands.tab_toggle_pinned = ({vim}) ->
403 currentTab = vim.window.gBrowser.selectedTab
404 if currentTab.pinned
405 vim.window.gBrowser.unpinTab(currentTab)
406 else
407 vim.window.gBrowser.pinTab(currentTab)
408
409 commands.tab_close = ({vim, count = 1}) ->
410 {gBrowser} = vim.window
411 return if gBrowser.selectedTab.pinned
412 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
413 utils.nextTick(vim.window, ->
414 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
415 gBrowser.removeTab(tab)
416 return
417 )
418
419 commands.tab_restore = ({vim, count = 1}) ->
420 utils.nextTick(vim.window, ->
421 for index in [0...count] by 1
422 restoredTab = vim.window.undoCloseTab()
423 if not restoredTab and index == 0
424 vim.notify(translate('notification.tab_restore.none'))
425 break
426 return
427 )
428
429 commands.tab_restore_list = ({vim}) ->
430 {window} = vim
431 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
432 window, 'menuitem'
433 )
434 if fragment.childElementCount == 0
435 vim.notify(translate('notification.tab_restore.none'))
436 else
437 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
438
439 commands.tab_close_to_end = ({vim}) ->
440 {gBrowser} = vim.window
441 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
442
443 commands.tab_close_other = ({vim}) ->
444 {gBrowser} = vim.window
445 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
446
447
448
449 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
450 {window} = vim
451 vim.markPageInteraction()
452 help.removeHelp(window)
453
454 markerContainer = new MarkerContainer({
455 window
456 hintChars: vim.options['hints.chars']
457 getComplementaryWrappers: (callback) ->
458 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
459 # `markerContainer.container` is `null`ed out when leaving Hints mode.
460 # If this callback is called after we’ve left Hints mode (and perhaps
461 # even entered it again), simply discard the result.
462 return unless markerContainer.container
463 if wrappers.length == 0
464 vim.notify(translate('notification.follow.none'))
465 callback({wrappers, viewport})
466 )
467 })
468 MarkerContainer.remove(window) # Better safe than sorry.
469 window.gBrowser.selectedBrowser.parentNode.appendChild(
470 markerContainer.container
471 )
472
473 chooseCallback = (marker, timesLeft, keyStr) ->
474 if callbackOverride
475 {type, href = null, elementIndex} = marker.wrapper
476 return callbackOverride({type, href, id: elementIndex, timesLeft})
477 else
478 return callback(marker, timesLeft, keyStr)
479
480 # Enter Hints mode immediately, with an empty set of markers. The user might
481 # press keys before any hints have been generated. Those keypresses should be
482 # handled in Hints mode, not Normal mode.
483 vim._enterMode('hints', {
484 markerContainer, count
485 callback: chooseCallback
486 matchText: vim.options['hints.match_text']
487 sleep: vim.options['hints.sleep']
488 })
489
490 injectHints = ({wrappers, viewport, pass}) ->
491 # See `getComplementaryWrappers` above.
492 return unless markerContainer.container
493
494 if wrappers.length == 0
495 if pass in ['single', 'second'] and markerContainer.markers.length == 0
496 vim.notify(translate('notification.follow.none'))
497 vim._enterMode('normal')
498 else
499 markerContainer.injectHints(wrappers, viewport, pass)
500
501 if pass == 'first'
502 vim._run(name, {pass: 'second'}, injectHints)
503
504 vim._run(name, {pass: 'auto'}, injectHints)
505
506
507 helper_add_user_context_id = (gBrowser, objectToAugment) ->
508 contextAttribute = gBrowser.selectedTab.attributes.getNamedItem(
509 USER_CONTEXT_ID_ATTRIBUTE_NAME)
510
511 # default has no context attribute so only set if it exists
512 if contextAttribute
513 objectToAugment.userContextId = contextAttribute.value
514
515 return objectToAugment
516
517
518 helper_follow_clickable = (options, args) ->
519 {vim} = args
520
521 callback = (marker, timesLeft, keyStr) ->
522 {inTab, inBackground} = options
523 {type, elementIndex} = marker.wrapper
524 isLast = (timesLeft == 1)
525 isLink = (type == 'link')
526 {window} = vim
527
528 switch
529 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
530 inTab = not inTab
531 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
532 inTab = true
533 inBackground = not inBackground
534 else
535 unless isLast
536 inTab = true
537 inBackground = true
538
539 inTab = false unless isLink
540
541 if type == 'text' or (isLink and not (inTab and inBackground))
542 isLast = true
543
544 vim._focusMarkerElement(elementIndex)
545
546 if inTab
547 utils.nextTick(window, ->
548 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
549 # links using the mouse. Using that instead of simply
550 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
551 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
552 referrerInfo = Cc['@mozilla.org/referrer-info;1']
553 .createInstance(Ci.nsIReferrerInfo)
554 referrerInfo.initWithDocument(window.document)
555 loadInBackground = prefs.root.get('browser.tabs.loadInBackground')
556
557 utils.contentAreaClick({
558 href: marker.wrapper.href
559 shiftKey: inBackground != loadInBackground
560 ctrlKey: true
561 metaKey: true
562 altKey: false
563 button: 0 # primary
564 csp: window.document.csp
565 referrerInfo
566 originAttributes: helper_add_user_context_id(
567 vim.browser.ownerGlobal.gBrowser,
568 window.document.nodePrincipal?.originAttributes ? {}
569 )
570 triggeringPrincipal: window.document.nodePrincipal
571 }, vim.browser)
572 )
573
574 # The point of “clicking” scrollable elements is focusing them (which is
575 # done above) so that scrolling commands may scroll them. Simulating a click
576 # here usually _unfocuses_ the element.
577 else if type != 'scrollable'
578 vim._run('click_marker_element', {
579 elementIndex, type
580 browserOffset: vim._getBrowserOffset()
581 preventTargetBlank: vim.options.prevent_target_blank
582 })
583
584 return not isLast
585
586 name = if options.inTab then 'follow_in_tab' else 'follow'
587 helper_follow({name, callback}, args)
588
589 commands.follow =
590 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
591
592 commands.follow_in_tab =
593 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
594
595 commands.follow_in_focused_tab =
596 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
597
598 helper_follow_in_window = (options, args) ->
599 {vim} = args
600
601 callback = (marker) ->
602 vim._focusMarkerElement(marker.wrapper.elementIndex)
603 {href} = marker.wrapper
604 options.triggeringPrincipal = vim.window.document.nodePrincipal
605 options = helper_add_user_context_id(vim.window.gBrowser, options)
606
607 vim.window.openLinkIn(href, 'window', options) if href
608 return false
609
610 helper_follow({name: 'follow_in_tab', callback}, args)
611
612 commands.follow_in_window =
613 helper_follow_in_window.bind(null, {})
614
615 commands.follow_in_private_window =
616 helper_follow_in_window.bind(null, {private: true})
617
618 commands.follow_multiple = (args) ->
619 args.count = Infinity
620 commands.follow(args)
621
622 commands.follow_copy = (args) ->
623 {vim} = args
624
625 callback = (marker) ->
626 property = switch marker.wrapper.type
627 when 'link'
628 'href'
629 when 'text'
630 'value'
631 when 'contenteditable', 'complementary'
632 '_selection'
633 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
634 return false
635
636 helper_follow({name: 'follow_copy', callback}, args)
637
638 commands.follow_focus = (args) ->
639 {vim} = args
640
641 callback = (marker) ->
642 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
643 return false
644
645 helper_follow({name: 'follow_focus', callback}, args)
646
647 commands.open_context_menu = (args) ->
648 {vim} = args
649
650 callback = (marker) ->
651 {type, elementIndex} = marker.wrapper
652 vim._run('click_marker_element', {
653 elementIndex, type
654 browserOffset: vim._getBrowserOffset()
655 })
656 return false
657
658 helper_follow({name: 'follow_context', callback}, args)
659
660 commands.click_browser_element = ({vim}) ->
661 {window} = vim
662 markerElements = []
663
664 getButtonMenu = (element) ->
665 if element.localName == 'dropmarker' and
666 element.parentNode?.localName == 'toolbarbutton'
667 return element.parentNode.querySelector('menupopup')
668 else
669 return null
670
671 filter = ({complementary}, element, getElementShape) ->
672 type = switch
673 when vim._state.scrollableElements.has(element)
674 'scrollable'
675 when getButtonMenu(element)
676 'dropmarker'
677 when utils.isFocusable(element) or element.onclick
678 'clickable'
679
680 if complementary
681 type = if type then null else 'complementary'
682
683 return unless type
684
685 # `getElementShape(element, -1)` is intentionally _not_ used in the
686 # `complementary` run, because it results in tons of useless hints for
687 # hidden context menus.
688 shape = getElementShape(element)
689 return unless shape.nonCoveredPoint
690
691 # The tabs and their close buttons as well as the tab bar scroll arrows get
692 # better hints, since switching or closing tabs is the most common use case
693 # for the `eb` command.
694 isTab = element.classList?.contains('tabbrowser-tab')
695 isPrioritized =
696 isTab or
697 element.classList?.contains('tab-close-button') or
698 element.classList?.contains('scrollbutton-up') or
699 element.classList?.contains('scrollbutton-down')
700
701 length = markerElements.push(element)
702 return {
703 type, shape, isTab, isPrioritized,
704 combinedArea: shape.area,
705 elementIndex: length - 1,
706 }
707
708 callback = (marker) ->
709 element = markerElements[marker.wrapper.elementIndex]
710 switch marker.wrapper.type
711 when 'scrollable'
712 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
713 when 'dropmarker'
714 getButtonMenu(element).openPopup(
715 element.parentNode, # Anchor node.
716 'after_end', # Position.
717 0, 0, # Offset.
718 false, # Isn’t a context menu.
719 true, # Allow the 'position' attribute to override the above position.
720 )
721 when 'clickable', 'complementary'
722 # VimFx’s own button won’t trigger unless the click is simulated in the
723 # next tick. This might be true for other buttons as well.
724 utils.nextTick(window, ->
725 utils.focusElement(element)
726 browserOffset = {x: window.screenX, y: window.screenY}
727 switch
728 when element.localName == 'tab'
729 # Only 'mousedown' seems to be able to activate tabs.
730 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
731 when element.closest('tab')
732 # If `.click()` is used on a tab close button, its tab will be
733 # selected first, which might cause the selected tab to change.
734 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
735 else
736 # `.click()` seems to trigger more buttons (such as NoScript’s
737 # button and Firefox’s “hamburger” menu button) than simulating
738 # 'click-xul'.
739 element.click()
740 utils.openDropdown(element)
741 )
742 return false
743
744 wrappers = markableElements.find(
745 window, filter.bind(null, {complementary: false})
746 )
747
748 if wrappers.length > 0
749 viewport = viewportUtils.getWindowViewport(window)
750
751 markerContainer = new MarkerContainer({
752 window
753 hintChars: vim.options['hints.chars']
754 adjustZoom: false
755 minWeightDiff: 0
756 getComplementaryWrappers: (callback) ->
757 newWrappers = markableElements.find(
758 window, filter.bind(null, {complementary: true})
759 )
760 callback({wrappers: newWrappers, viewport})
761 })
762 MarkerContainer.remove(window) # Better safe than sorry.
763 markerContainer.container.classList.add('ui')
764 mainWindow = window.document.body
765 mainWindow.insertBefore(
766 markerContainer.container,
767 mainWindow.firstChild
768 )
769
770 [firstWrappers, secondWrappers] =
771 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
772
773 numChars = markerContainer.alphabet.length
774 numPrimary = markerContainer.primaryHintChars.length
775 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
776 index = 0
777
778 for wrapper in firstWrappers
779 if wrapper.isTab
780 # Given the hint chars `abc de`, give the tabs weights so that the hints
781 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
782 # on. The rule is that the weight of a tab must be larger than the sum
783 # of all tabs with a longer hint. We start out at `1` and then use
784 # smaller and smaller fractions. This is to make sure that the tabs get
785 # consistent hints as the number of tabs or the size of the window
786 # changes.
787 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
788 wrapper.combinedArea = 1 / numChars ** exponent
789 index += 1
790 else
791 # Make sure that the tab close buttons and the tab bar scroll buttons
792 # come after all the tabs. Treating them all as the same size is fine.
793 # Their sum must be small enough in order not to affect the tab hints.
794 # It might look like using `0` is a good idea, but that results in
795 # increasingly worse hints the more tab close buttons there are.
796 wrapper.combinedArea = 1 / numChars ** numTabs
797
798 # Since most of the best hint characters might be used for the tabs, make
799 # sure that all other elements don’t get really bad hints. First, favor
800 # larger elements by sorting them. Then, give them all the same weight so
801 # that larger elements (such as the location bar, search bar, the web
802 # console input and other large areas in the devtools) don’t overpower the
803 # smaller ones. The usual “the larger the element, the better the hint” rule
804 # doesn’t really apply the same way for browser UI elements as in web pages.
805 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
806 for wrapper in secondWrappers
807 wrapper.combinedArea = 1
808
809 markerContainer.injectHints(firstWrappers, viewport, 'first')
810 markerContainer.injectHints(secondWrappers, viewport, 'second')
811 vim._enterMode('hints', {markerContainer, callback, matchText: false})
812
813 else
814 vim.notify(translate('notification.follow.none'))
815
816 helper_follow_pattern = (type, {vim}) ->
817 options = {
818 pattern_selector: vim.options.pattern_selector
819 pattern_attrs: vim.options.pattern_attrs
820 patterns: vim.options["#{type}_patterns"]
821 }
822 browserOffset = vim._getBrowserOffset()
823 vim._run('follow_pattern', {type, browserOffset, options})
824
825 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
826
827 commands.follow_next = helper_follow_pattern.bind(null, 'next')
828
829 commands.focus_text_input = ({vim, count}) ->
830 vim.markPageInteraction()
831 vim._run('focus_text_input', {count})
832
833 helper_follow_selectable = ({select}, args) ->
834 {vim} = args
835
836 callback = (marker) ->
837 vim._run('element_text_select', {
838 elementIndex: marker.wrapper.elementIndex
839 full: select
840 scroll: select
841 })
842 vim._enterMode('caret', {select})
843 return false
844
845 helper_follow({name: 'follow_selectable', callback}, args)
846
847 commands.element_text_caret =
848 helper_follow_selectable.bind(null, {select: false})
849
850 commands.element_text_select =
851 helper_follow_selectable.bind(null, {select: true})
852
853 commands.element_text_copy = (args) ->
854 {vim} = args
855
856 callback = (marker) ->
857 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
858 return false
859
860 helper_follow({name: 'follow_selectable', callback}, args)
861
862 helper_copy_marker_element = (vim, elementIndex, property) ->
863 if property == '_selection'
864 # Selecting the text and then copying that selection is better than copying
865 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
866 # and then includes those backticks in the compiled output (!), in hidden
867 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
868 # elements, text selection gives better whitespace than `.textContent`.
869 vim._run('element_text_select', {elementIndex, full: true}, ->
870 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
871 vim._run('clear_selection')
872 )
873 else
874 vim._run('copy_marker_element', {elementIndex, property})
875
876
877
878 findStorage = {
879 lastSearchString: ''
880 busy: false
881 }
882
883 helper_find_from_top_of_viewport = (vim, direction, callback) ->
884 if vim.options.find_from_top_of_viewport
885 vim._run('find_from_top_of_viewport', {direction}, ->
886 callback()
887 )
888 else
889 callback()
890
891 helper_find = ({highlight, linksOnly = false}, {vim}) ->
892 if findStorage.busy
893 # Make sure to enter find mode here, since that’s where `findStorage.busy`
894 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
895 vim._enterMode('find')
896 return
897
898 helpSearchInput = help.getSearchInput(vim.window)
899 if helpSearchInput
900 helpSearchInput.select()
901 return
902
903 # Important: Enter Find mode immediately. See `onInput` for Find mode.
904 findStorage.busy = true
905 vim._enterMode('find')
906
907 helper_mark_last_scroll_position(vim)
908 vim._run('mark_scroll_position', {
909 keyStr: vim.options['scroll.last_find_mark']
910 notify: false
911 })
912
913 helper_find_from_top_of_viewport(vim, FORWARD, ->
914 return unless vim.mode == 'find'
915 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
916 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
917 findBar.startFind(mode)
918 utils.focusElement(findBar._findField, {select: true})
919
920 return if linksOnly
921 return unless highlightButton = findBar.getElement('highlight')
922 if highlightButton.checked != highlight
923 highlightButton.click()
924 )
925 )
926
927 commands.find = helper_find.bind(null, {highlight: false})
928
929 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
930
931 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
932
933 helper_find_again = (direction, {vim}) ->
934 return if findStorage.busy
935
936 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
937 if findStorage.lastSearchString.length == 0
938 vim.notify(translate('notification.find_again.none'))
939 return
940
941 findStorage.busy = true
942
943 helper_mark_last_scroll_position(vim)
944 helper_find_from_top_of_viewport(vim, direction, ->
945 findBar._findField.value = findStorage.lastSearchString
946
947 # `.onFindResult` is temporarily hacked to be able to know when the
948 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
949 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
950 # hack that one too.
951 originalOnFindResult = findBar.onFindResult
952 originalUpdateControlState = findBar.updateControlState
953
954 findBar.onFindResult = (data) ->
955 # Prevent the find bar from re-opening if there are no matches.
956 data.storeResult = false
957 findBar.onFindResult = originalOnFindResult
958 findBar.updateControlState = originalUpdateControlState
959 findBar.onFindResult(data)
960 callback()
961
962 findBar.updateControlState = (args...) ->
963 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
964 # matches here, so no need to take care of that in this case.
965 findBar.onFindResult = originalOnFindResult
966 findBar.updateControlState = originalUpdateControlState
967 findBar.updateControlState(args...)
968 callback()
969
970 callback = ->
971 message = findBar._findStatusDesc.textContent
972 vim.notify(message) if message
973 findStorage.busy = false
974
975 findBar.onFindAgainCommand(not direction)
976 )
977 )
978
979 commands.find_next = helper_find_again.bind(null, FORWARD)
980
981 commands.find_previous = helper_find_again.bind(null, BACKWARD)
982
983
984
985 commands.window_new = ({vim}) ->
986 vim.window.OpenBrowserWindow()
987
988 commands.window_new_private = ({vim}) ->
989 vim.window.OpenBrowserWindow({private: true})
990
991 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
992 type = if blacklist then 'blacklist' else 'explicit'
993 vim._enterMode('ignore', {type})
994
995 # Quote next keypress (pass it through to the page).
996 commands.quote = ({vim, count = 1}) ->
997 vim._enterMode('ignore', {type: 'explicit', count})
998
999 commands.enter_reader_view = ({vim}) ->
1000 button = vim.window.document.getElementById('reader-mode-button')
1001 if not button?.hidden
1002 button.click()
1003 else
1004 vim.notify(translate('notification.enter_reader_view.none'))
1005
1006 commands.reload_config_file = ({vim}) ->
1007 vim._parent.emit('shutdown')
1008 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1009 when null
1010 vim.notify(translate('notification.reload_config_file.none'))
1011 when true
1012 vim.notify(translate('notification.reload_config_file.success'))
1013 else
1014 vim.notify(translate('notification.reload_config_file.failure'))
1015 )
1016
1017 commands.edit_blacklist = ({vim}) ->
1018 url = vim.browser.currentURI.spec
1019 location = new vim.window.URL(url)
1020 newPattern = if location.host then "*#{location.host}*" else location.href
1021 delimiter = ' '
1022 blacklistString = prefs.get('blacklist')
1023
1024 if vim._isBlacklisted(url)
1025 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1026 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1027 return vim.options.blacklist[index].test(url)
1028 )
1029 newBlacklistString = "
1030 #{matching.join(delimiter)}\
1031 #{delimiter.repeat(7)}\
1032 #{nonMatching.join(delimiter)}
1033 "
1034 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1035 else
1036 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1037 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1038
1039 message = """
1040 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1041
1042 #{extraMessage}
1043 """
1044
1045 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1046 return if input == null
1047 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1048 # and let the regular pref parsing take care of it.
1049 prefs.set('blacklist', input)
1050 vim._onLocationChange(url)
1051 )
1052
1053 commands.help = ({vim}) ->
1054 help.toggleHelp(vim.window, vim._parent)
1055
1056 commands.esc = ({vim}) ->
1057 vim._run('esc')
1058 vim.hideNotification()
1059
1060 # Firefox does things differently when blurring the location bar, depending on
1061 # whether the autocomplete popup is open or not. To be consistent, always
1062 # close the autocomplete popup before blurring.
1063 vim.window.gURLBar.view.close()
1064
1065 utils.blurActiveBrowserElement(vim)
1066 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1067
1068 # Better safe than sorry.
1069 MarkerContainer.remove(vim.window)
1070 vim._parent.resetCaretBrowsing()
1071
1072 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1073 help.removeHelp(vim.window)
1074
1075 vim._setFocusType('none') # Better safe than sorry.
1076
1077
1078
1079 module.exports = {
1080 commands
1081 findStorage
1082 }
Imprint / Impressum