]> git.gir.st - VimFx.git/blob - extension/lib/vim.coffee
Fix lint errors
[VimFx.git] / extension / lib / vim.coffee
1 # This file defines the `vim` API, available to all modes and commands. There is
2 # one `Vim` instance for each tab. Most importantly, it provides access to the
3 # owning Firefox window and the current mode, and allows you to change mode.
4 # `vim` objects are exposed by the config file API. Underscored names are
5 # private and should not be used by API consumers.
6
7 messageManager = require('./message-manager')
8 ScrollableElements = require('./scrollable-elements')
9 utils = require('./utils')
10
11 ChromeWindow = Ci.nsIDOMChromeWindow
12
13 class Vim
14 constructor: (browser, @_parent) ->
15 @mode = undefined
16 @focusType = 'none'
17 @_setBrowser(browser, {addListeners: false})
18 @_storage = {}
19
20 @_resetState()
21
22 Object.defineProperty(this, 'options', {
23 get: => @_parent.options
24 enumerable: true
25 })
26
27 _start: ->
28 @_onLocationChange(@browser.currentURI.spec)
29 @_addListeners()
30 focusType = utils.getFocusType(utils.getActiveElement(@window))
31 @_setFocusType(focusType)
32
33 _addListeners: ->
34 # Require the subset of the options needed to be listed explicitly (as
35 # opposed to sending _all_ options) for performance. Each option access
36 # might trigger an optionOverride.
37 @_listen('options', ({prefs}) =>
38 options = {}
39 for pref in prefs
40 options[pref] = @options[pref]
41 return options
42 )
43
44 @_listen('vimMethod', ({method, args = []}, callback = null) =>
45 result = this[method](args...)
46 callback?(result)
47 )
48
49 @_listen('vimMethodSync', ({method, args = []}) =>
50 return this[method](args...)
51 )
52
53 @_listen('locationChange', @_onLocationChange.bind(this))
54
55 @_listen('frameCanReceiveEvents', (value) =>
56 @_state.frameCanReceiveEvents = value
57 )
58
59 @_listen('focusType', (focusType) =>
60 # If the focus moves from a web page element to a browser UI element, the
61 # focus and blur events happen in the expected order, but the message from
62 # the frame script arrives too late. Therefore, check that the currently
63 # active element isn’t a browser UI element first.
64 unless @_isUIElement(utils.getActiveElement(@window))
65 @_setFocusType(focusType)
66 )
67
68 _setBrowser: (@browser, {addListeners = true} = {}) ->
69 @window = @browser.ownerGlobal
70 @_messageManager = @browser.messageManager
71
72 @_addListeners() if addListeners
73
74 _resetState: ->
75 @_state = {
76 frameCanReceiveEvents: false
77 scrollableElements: new ScrollableElements(@window)
78 lastNotification: null
79 persistentNotification: null
80 enteredKeys: []
81 enteredKeysTimeout: null
82 }
83
84 _isBlacklisted: (url) -> @options.blacklist.some((regex) -> regex.test(url))
85
86 isUIEvent: (event) ->
87 return not @_state.frameCanReceiveEvents or
88 @_isUIElement(event.originalTarget)
89
90 _isUIElement: (element) ->
91 return element.ownerGlobal instanceof ChromeWindow and
92 element != @window.gBrowser.selectedBrowser
93
94 # `args...` is passed to the mode's `onEnter` method.
95 _enterMode: (mode, args...) ->
96 return if @mode == mode
97
98 unless utils.has(@_parent.modes, mode)
99 modes = Object.keys(@_parent.modes).join(', ')
100 throw new Error(
101 "VimFx: Unknown mode. Available modes are: #{modes}. Got: #{mode}"
102 )
103
104 @_call('onLeave') if @mode?
105 @mode = mode
106 @_call('onEnter', null, args...)
107 @_parent.emit('modeChange', {vim: this})
108 @_send('modeChange', {mode})
109
110 _consumeKeyEvent: (event) ->
111 match = @_parent.consumeKeyEvent(event, this)
112 return match if not match or typeof match == 'boolean'
113
114 if @options.notify_entered_keys
115 if match.type in ['none', 'full'] or match.likelyConflict
116 @_clearEnteredKeys()
117 else
118 @_pushEnteredKey(match.keyStr)
119 else
120 @hideNotification()
121
122 return match
123
124 _onInput: (match, event) ->
125 suppress = @_call('onInput', {event, count: match.count}, match)
126 return suppress
127
128 _onLocationChange: (url) ->
129 switch
130 when @_isBlacklisted(url)
131 @_enterMode('ignore', {type: 'blacklist'})
132 when (@mode == 'ignore' and @_storage.ignore.type == 'blacklist') or
133 not @mode
134 @_enterMode('normal')
135 @_parent.emit('locationChange', {vim: this, location: new @window.URL(url)})
136
137 _call: (method, data = {}, extraArgs...) ->
138 args = Object.assign({vim: this, storage: @_storage[@mode] ?= {}}, data)
139 currentMode = @_parent.modes[@mode]
140 return currentMode[method].call(currentMode, args, extraArgs...)
141
142 _run: (name, data = {}, callback = null) ->
143 @_send('runCommand', {name, data}, callback)
144
145 _messageManagerOptions: (options) ->
146 return Object.assign({
147 messageManager: @_messageManager
148 }, options)
149
150 _listen: (name, listener, options = {}) ->
151 messageManager.listen(name, listener, @_messageManagerOptions(options))
152
153 _listenOnce: (name, listener, options = {}) ->
154 messageManager.listenOnce(name, listener, @_messageManagerOptions(options))
155
156 _send: (name, data, callback = null, options = {}) ->
157 messageManager.send(name, data, callback, @_messageManagerOptions(options))
158
159 notify: (message) ->
160 @_state.lastNotification = message
161 @_parent.emit('notification', {vim: this, message})
162 if @options.notifications_enabled
163 @window.StatusPanel._label = message
164
165 _notifyPersistent: (message) ->
166 @_state.persistentNotification = message
167 @notify(message)
168
169 _refreshPersistentNotification: ->
170 @notify(@_state.persistentNotification) if @_state.persistentNotification
171
172 hideNotification: ->
173 @_parent.emit('hideNotification', {vim: this})
174 @window.StatusPanel._label = '' # or .update()
175 @_state.lastNotification = null
176 @_state.persistentNotification = null
177
178 _clearEnteredKeys: ->
179 @_clearEnteredKeysTimeout()
180 return unless @_state.enteredKeys.length > 0
181
182 @_state.enteredKeys = []
183 if @_state.persistentNotification
184 @notify(@_state.persistentNotification)
185 else
186 @hideNotification()
187
188 _pushEnteredKey: (keyStr) ->
189 @_state.enteredKeys.push(keyStr)
190 @_clearEnteredKeysTimeout()
191 @notify(@_state.enteredKeys.join(''))
192 clear = @_clearEnteredKeys.bind(this)
193 @_state.enteredKeysTimeout =
194 @window.setTimeout((-> clear()), @options.timeout)
195
196 _clearEnteredKeysTimeout: ->
197 if @_state.enteredKeysTimeout?
198 @window.clearTimeout(@_state.enteredKeysTimeout)
199 @_state.enteredKeysTimeout = null
200
201 _modal: (type, args, callback = null) ->
202 @_run('modal', {type, args}, callback)
203
204 markPageInteraction: (value = null) -> @_send('markPageInteraction', value)
205
206 _focusMarkerElement: (elementIndex, options = {}) ->
207 # If you, for example, focus the location bar, unfocus it by pressing
208 # `<esc>` and then try to focus a link or text input in a web page the focus
209 # won’t work unless `@browser` is focused first.
210 @browser.focus()
211 browserOffset = @_getBrowserOffset()
212 @_run('focus_marker_element', {elementIndex, browserOffset, options})
213
214 _setFocusType: (focusType) ->
215 return if focusType == @focusType
216 @focusType = focusType
217 switch
218 when @focusType == 'ignore'
219 @_enterMode('ignore', {type: 'focusType'})
220 when @mode == 'ignore' and @_storage.ignore.type == 'focusType'
221 @_enterMode('normal')
222 when @mode == 'normal' and @focusType == 'findbar'
223 @_enterMode('find')
224 when @mode == 'find' and @focusType != 'findbar'
225 @_enterMode('normal')
226 @_parent.emit('focusTypeChange', {vim: this})
227
228 _getBrowserOffset: ->
229 browserRect = @browser.getBoundingClientRect()
230 return {
231 x: @window.screenX + browserRect.left
232 y: @window.screenY + browserRect.top
233 }
234
235 module.exports = Vim
Imprint / Impressum