]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Improve the help dialog UX
[VimFx.git] / extension / lib / commands.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015.
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 help = require('./help')
30 hints = require('./hints')
31 prefs = require('./prefs')
32 translate = require('./l10n')
33 utils = require('./utils')
34
35 commands = {}
36
37
38
39 commands.focus_location_bar = ({vim}) ->
40 # This function works even if the Address Bar has been removed.
41 vim.window.focusAndSelectUrlBar()
42
43 commands.focus_search_bar = ({vim, count}) ->
44 # The `.webSearch()` method opens a search engine in a tab if the Search Bar
45 # has been removed. Therefore we first check if it exists.
46 if vim.window.BrowserSearch.searchBar
47 vim.window.BrowserSearch.webSearch()
48
49 helper_paste_and_go = (props, {vim}) ->
50 {gURLBar} = vim.window
51 gURLBar.value = vim.window.readFromClipboard()
52 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
53
54 commands.paste_and_go = helper_paste_and_go.bind(null, null)
55
56 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
57
58 commands.copy_current_url = ({vim}) ->
59 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
60 vim.notify(translate('notification.copy_current_url'))
61
62 commands.go_up_path = ({vim, count}) ->
63 vim._run('go_up_path', {count})
64
65 # Go up to root of the URL hierarchy.
66 commands.go_to_root = ({vim}) ->
67 vim._run('go_to_root')
68
69 commands.go_home = ({vim}) ->
70 vim.window.BrowserHome()
71
72 helper_go_history = (direction, {vim, count = 1}) ->
73 {SessionStore, gBrowser} = vim.window
74
75 # TODO: When Firefox 43 is released, only use the `.getSessionHistory`
76 # version and bump the minimum Firefox version.
77 if SessionStore.getSessionHistory
78 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
79 {index} = sessionHistory
80 newIndex = index + count * (if direction == 'back' then -1 else 1)
81 newIndex = Math.max(newIndex, 0)
82 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
83 if newIndex == index
84 vim.notify(translate("notification.history_#{direction}.limit"))
85 else
86 gBrowser.gotoIndex(newIndex)
87 )
88 else
89 # Until then, fall back to a no-count version.
90 if direction == 'back' then gBrowser.goBack() else gBrowser.goForward()
91
92 commands.history_back = helper_go_history.bind(null, 'back')
93
94 commands.history_forward = helper_go_history.bind(null, 'forward')
95
96 commands.history_list = ({vim}) ->
97 menu = vim.window.document.getElementById('backForwardMenu')
98 utils.openPopup(menu)
99 vim.notify(translate('notification.history_list.none')) unless menu.open
100
101 commands.reload = ({vim}) ->
102 vim.window.BrowserReload()
103
104 commands.reload_force = ({vim}) ->
105 vim.window.BrowserReloadSkipCache()
106
107 commands.reload_all = ({vim}) ->
108 vim.window.gBrowser.reloadAllTabs()
109
110 commands.reload_all_force = ({vim}) ->
111 for tab in vim.window.gBrowser.visibleTabs
112 gBrowser = tab.linkedBrowser
113 consts = gBrowser.webNavigation
114 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
115 gBrowser.reload(flags)
116 return
117
118 commands.stop = ({vim}) ->
119 vim.window.BrowserStop()
120
121 commands.stop_all = ({vim}) ->
122 for tab in vim.window.gBrowser.visibleTabs
123 tab.linkedBrowser.stop()
124 return
125
126
127
128 helper_scroll = (vim, uiEvent, args...) ->
129 [
130 method, type, directions, amounts
131 properties = null, adjustment = 0, name = 'scroll'
132 ] = args
133 options = {
134 method, type, directions, amounts, properties, adjustment
135 smooth: (prefs.root.get('general.smoothScroll') and
136 prefs.root.get("general.smoothScroll.#{type}"))
137 }
138 reset = prefs.root.tmp(
139 'layout.css.scroll-behavior.spring-constant',
140 vim.options["smoothScroll.#{type}.spring-constant"]
141 )
142
143 helpContainer = help.getHelp(vim.window)
144 if uiEvent or helpContainer
145 activeElement = helpContainer or utils.getActiveElement(vim.window)
146 if vim._state.scrollableElements.has(activeElement) or helpContainer
147 utils.scroll(activeElement, options)
148 reset()
149 return
150
151 vim._run(name, options, reset)
152
153
154 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
155 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
156 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['left'],
157 [amount * distance * count * 5])
158
159 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
160 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
161 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['top'],
162 [amount * distance * count * 20])
163
164 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
165 adjustment = prefs.get("scroll.#{type}_page_adjustment")
166 helper_scroll(vim, uiEvent, 'scrollBy', 'pages', ['top'],
167 [amount * count], ['clientHeight'], adjustment)
168
169 helper_scrollToX = (amount, {vim, uiEvent}) ->
170 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['left'],
171 [amount], ['scrollLeftMax'])
172 helper_mark_last_scroll_position(vim)
173
174 helper_scrollToY = (amount, {vim, uiEvent}) ->
175 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['top'],
176 [amount], ['scrollTopMax'])
177 helper_mark_last_scroll_position(vim)
178
179 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
180 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
181 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
182 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
183 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
184 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
185 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
186 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
187 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
188 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
189 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
190 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
191
192 helper_mark_last_scroll_position = (vim) ->
193 keyStr = vim.options['scroll.last_position_mark']
194 vim._run('mark_scroll_position', {keyStr, notify: false})
195
196 commands.mark_scroll_position = ({vim}) ->
197 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
198
199 commands.scroll_to_mark = ({vim}) ->
200 vim.enterMode('marks', (keyStr) ->
201 unless keyStr == vim.options['scroll.last_position_mark']
202 helper_mark_last_scroll_position(vim)
203 helper_scroll(vim, 'scrollTo', 'other', ['top', 'left'], keyStr,
204 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
205 )
206
207
208
209 commands.tab_new = ({vim}) ->
210 utils.nextTick(vim.window, ->
211 vim.window.BrowserOpenTab()
212 )
213
214 commands.tab_duplicate = ({vim}) ->
215 {gBrowser} = vim.window
216 utils.nextTick(vim.window, ->
217 gBrowser.duplicateTab(gBrowser.selectedTab)
218 )
219
220 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
221 tabs = gBrowser.visibleTabs
222 {selectedTab} = gBrowser
223
224 currentIndex = tabs.indexOf(selectedTab)
225 absoluteIndex = currentIndex + relativeIndex
226 numTabsTotal = tabs.length
227 numPinnedTabs = gBrowser._numPinnedTabs
228
229 [numTabs, min] = switch
230 when not pinnedSeparate then [numTabsTotal, 0]
231 when selectedTab.pinned then [numPinnedTabs, 0]
232 else [numTabsTotal - numPinnedTabs, numPinnedTabs]
233
234 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
235 # current direction.
236 if (relativeIndex < 0 and currentIndex == min) or
237 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
238 if absoluteIndex < min
239 absoluteIndex += numTabs
240 else if absoluteIndex >= min + numTabs
241 absoluteIndex -= numTabs
242
243 absoluteIndex = Math.max(min, absoluteIndex)
244 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
245
246 return absoluteIndex
247
248 helper_switch_tab = (direction, {vim, count = 1}) ->
249 {gBrowser} = vim.window
250 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
251 utils.nextTick(vim.window, ->
252 gBrowser.selectTabAtIndex(index)
253 )
254
255 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
256
257 commands.tab_select_next = helper_switch_tab.bind(null, +1)
258
259 helper_move_tab = (direction, {vim, count = 1}) ->
260 {gBrowser} = vim.window
261 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
262 utils.nextTick(vim.window, ->
263 gBrowser.moveTabTo(gBrowser.selectedTab, index)
264 )
265
266 commands.tab_move_backward = helper_move_tab.bind(null, -1)
267
268 commands.tab_move_forward = helper_move_tab.bind(null, +1)
269
270 commands.tab_move_to_window = ({vim}) ->
271 {gBrowser} = vim.window
272 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
273
274 commands.tab_select_first = ({vim, count = 1}) ->
275 utils.nextTick(vim.window, ->
276 vim.window.gBrowser.selectTabAtIndex(count - 1)
277 )
278
279 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
280 firstNonPinned = vim.window.gBrowser._numPinnedTabs
281 utils.nextTick(vim.window, ->
282 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
283 )
284
285 commands.tab_select_last = ({vim, count = 1}) ->
286 utils.nextTick(vim.window, ->
287 vim.window.gBrowser.selectTabAtIndex(-count)
288 )
289
290 commands.tab_toggle_pinned = ({vim}) ->
291 currentTab = vim.window.gBrowser.selectedTab
292 if currentTab.pinned
293 vim.window.gBrowser.unpinTab(currentTab)
294 else
295 vim.window.gBrowser.pinTab(currentTab)
296
297 commands.tab_close = ({vim, count = 1}) ->
298 {gBrowser} = vim.window
299 return if gBrowser.selectedTab.pinned
300 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
301 utils.nextTick(vim.window, ->
302 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
303 gBrowser.removeTab(tab)
304 return
305 )
306
307 commands.tab_restore = ({vim, count = 1}) ->
308 utils.nextTick(vim.window, ->
309 for index in [0...count] by 1
310 restoredTab = vim.window.undoCloseTab()
311 if not restoredTab and index == 0
312 vim.notify(translate('notification.tab_restore.none'))
313 break
314 return
315 )
316
317 commands.tab_restore_list = ({vim}) ->
318 {window} = vim
319 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
320 window, 'menuitem'
321 )
322 if fragment.childElementCount == 0
323 vim.notify(translate('notification.tab_restore.none'))
324 else
325 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
326
327 commands.tab_close_to_end = ({vim}) ->
328 {gBrowser} = vim.window
329 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
330
331 commands.tab_close_other = ({vim}) ->
332 {gBrowser} = vim.window
333 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
334
335
336
337 helper_follow = (name, vim, callback, count = null) ->
338 vim.markPageInteraction()
339
340 # Enter hints mode immediately, with an empty set of markers. The user might
341 # press keys before the `vim._run` callback is invoked. Those key presses
342 # should be handled in hints mode, not normal mode.
343 initialMarkers = []
344 storage = vim.enterMode('hints', initialMarkers, callback, count)
345
346 vim._run(name, null, ({wrappers, viewport}) ->
347 # The user might have exited hints mode (and perhaps even entered it again)
348 # before this callback is invoked. If so, `storage.markers` has been
349 # cleared, or set to a new value. Only proceed if it is unchanged.
350 return unless storage.markers == initialMarkers
351
352 if wrappers.length > 0
353 markers = hints.injectHints(vim.window, wrappers, viewport, vim.options)
354 storage.markers = markers
355 else
356 vim.notify(translate('notification.follow.none'))
357 vim.enterMode('normal')
358 )
359
360 helper_follow_clickable = ({inTab, inBackground}, {vim, count = 1}) ->
361 callback = (marker, timesLeft, keyStr) ->
362 {type, elementIndex} = marker.wrapper
363 isLast = (timesLeft == 1)
364 isLink = (type == 'link')
365
366 switch
367 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
368 inTab = not inTab
369 when keyStr.startsWith(vim.options.hints_toggle_in_background)
370 inTab = true
371 inBackground = not inBackground
372 else
373 unless isLast
374 inTab = true
375 inBackground = true
376
377 inTab = false unless isLink
378
379 if type == 'text' or (isLink and not (inTab and inBackground))
380 isLast = true
381
382 vim._focusMarkerElement(elementIndex)
383
384 if inTab
385 utils.nextTick(vim.window, ->
386 utils.openTab(vim.window, marker.wrapper.href, {
387 inBackground
388 relatedToCurrent: true
389 })
390 )
391 else
392 vim._run('click_marker_element', {
393 elementIndex, type
394 preventTargetBlank: vim.options.prevent_target_blank
395 })
396
397 return not isLast
398
399 name = if inTab then 'follow_in_tab' else 'follow'
400 helper_follow(name, vim, callback, count)
401
402 # Follow links, focus text inputs and click buttons with hint markers.
403 commands.follow =
404 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
405
406 # Follow links in a new background tab with hint markers.
407 commands.follow_in_tab =
408 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
409
410 # Follow links in a new foreground tab with hint markers.
411 commands.follow_in_focused_tab =
412 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
413
414 # Follow links in a new window with hint markers.
415 commands.follow_in_window = ({vim}) ->
416 callback = (marker) ->
417 vim._focusMarkerElement(marker.wrapper.elementIndex)
418 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
419 helper_follow('follow_in_tab', vim, callback)
420
421 # Like command_follow but multiple times.
422 commands.follow_multiple = (args) ->
423 args.count = Infinity
424 commands.follow(args)
425
426 # Copy the URL or text of a markable element to the system clipboard.
427 commands.follow_copy = ({vim}) ->
428 callback = (marker) ->
429 {elementIndex} = marker.wrapper
430 property = switch marker.wrapper.type
431 when 'link' then 'href'
432 when 'text' then 'value'
433 when 'contenteditable' then 'textContent'
434 vim._run('copy_marker_element', {elementIndex, property})
435 helper_follow('follow_copy', vim, callback)
436
437 # Focus element with hint markers.
438 commands.follow_focus = ({vim}) ->
439 callback = (marker) ->
440 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
441 return helper_follow('follow_focus', vim, callback)
442
443 commands.click_browser_element = ({vim}) ->
444 markerElements = []
445
446 filter = (element, getElementShape) ->
447 document = element.ownerDocument
448 type = switch
449 when vim._state.scrollableElements.has(element)
450 'scrollable'
451 when element.tabIndex > -1 and
452 not (element.nodeName.endsWith('box') and
453 element.nodeName != 'checkbox') and
454 element.nodeName != 'tabs'
455 'clickable'
456 return unless type
457 return unless shape = getElementShape(element)
458 length = markerElements.push(element)
459 return {type, semantic: true, shape, elementIndex: length - 1}
460
461 callback = (marker) ->
462 element = markerElements[marker.wrapper.elementIndex]
463 switch marker.wrapper.type
464 when 'scrollable'
465 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
466 when 'clickable'
467 utils.focusElement(element)
468 utils.simulateClick(element)
469
470 {wrappers, viewport} =
471 hints.getMarkableElementsAndViewport(vim.window, filter)
472
473 if wrappers.length > 0
474 markers = hints.injectHints(vim.window, wrappers, viewport, {
475 hint_chars: vim.options.hint_chars
476 ui: true
477 })
478 vim.enterMode('hints', markers, callback)
479 else
480 vim.notify(translate('notification.follow.none'))
481
482 helper_follow_pattern = (type, {vim}) ->
483 options =
484 pattern_selector: vim.options.pattern_selector
485 pattern_attrs: vim.options.pattern_attrs
486 patterns: vim.options["#{type}_patterns"]
487 vim._run('follow_pattern', {type, options})
488
489 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
490
491 commands.follow_next = helper_follow_pattern.bind(null, 'next')
492
493 # Focus last focused or first text input.
494 commands.focus_text_input = ({vim, count}) ->
495 vim.markPageInteraction()
496 vim._run('focus_text_input', {count})
497
498
499
500 findStorage = {lastSearchString: ''}
501
502 helper_find = ({highlight, linksOnly = false}, {vim}) ->
503 helpSearchInput = help.getSearchInput(vim.window)
504 if helpSearchInput
505 helpSearchInput.select()
506 return
507
508 helper_mark_last_scroll_position(vim)
509 findBar = vim.window.gBrowser.getFindBar()
510
511 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
512 findBar.startFind(mode)
513 utils.focusElement(findBar._findField, {select: true})
514
515 return if linksOnly
516 return unless highlightButton = findBar.getElement('highlight')
517 if highlightButton.checked != highlight
518 highlightButton.click()
519
520 # Open the find bar, making sure that hightlighting is off.
521 commands.find = helper_find.bind(null, {highlight: false})
522
523 # Open the find bar, making sure that hightlighting is on.
524 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
525
526 # Open the find bar in links only mode.
527 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
528
529 helper_find_again = (direction, {vim}) ->
530 findBar = vim.window.gBrowser.getFindBar()
531 if findStorage.lastSearchString.length == 0
532 vim.notify(translate('notification.find_again.none'))
533 return
534 helper_mark_last_scroll_position(vim)
535 findBar._findField.value = findStorage.lastSearchString
536 findBar.onFindAgainCommand(direction)
537 message = findBar._findStatusDesc.textContent
538 vim.notify(message) if message
539
540 commands.find_next = helper_find_again.bind(null, false)
541
542 commands.find_previous = helper_find_again.bind(null, true)
543
544
545
546 commands.window_new = ({vim}) ->
547 vim.window.OpenBrowserWindow()
548
549 commands.window_new_private = ({vim}) ->
550 vim.window.OpenBrowserWindow({private: true})
551
552 commands.enter_mode_ignore = ({vim}) ->
553 vim.enterMode('ignore')
554
555 # Quote next keypress (pass it through to the page).
556 commands.quote = ({vim, count = 1}) ->
557 vim.enterMode('ignore', count)
558
559 commands.enter_reader_view = ({vim}) ->
560 button = vim.window.document.getElementById('reader-mode-button')
561 if not button?.hidden
562 button.click()
563 else
564 vim.notify(translate('notification.enter_reader_view.none'))
565
566 # Display the Help Dialog.
567 commands.help = ({vim}) ->
568 help.injectHelp(vim.window, vim._parent)
569
570 # Open and focus the Developer Toolbar.
571 commands.dev = ({vim}) ->
572 vim.window.DeveloperToolbar.show(true) # `true` to focus.
573
574 commands.esc = ({vim}) ->
575 vim._run('esc')
576 utils.blurActiveBrowserElement(vim)
577 vim.window.DeveloperToolbar.hide()
578 vim.window.gBrowser.getFindBar().close()
579 # TODO: Remove when Tab Groups have been removed.
580 vim.window.TabView?.hide()
581 hints.removeHints(vim.window) # Better safe than sorry.
582
583 unless help.getSearchInput(vim.window)?.getAttribute('focused')
584 help.removeHelp(vim.window)
585
586
587
588 module.exports = {
589 commands
590 findStorage
591 }
Imprint / Impressum