]> git.gir.st - VimFx.git/blob - extension/lib/events-frame.coffee
Implement filtering hints by text and related changes
[VimFx.git] / extension / lib / events-frame.coffee
1 ###
2 # Copyright Simon Lydell 2015, 2016.
3 #
4 # This file is part of VimFx.
5 #
6 # VimFx is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # VimFx is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
18 ###
19
20 # This file is the equivalent to events.coffee, but for frame scripts.
21
22 notation = require('vim-like-key-notation')
23 commands = require('./commands-frame')
24 messageManager = require('./message-manager')
25 prefs = require('./prefs')
26 utils = require('./utils')
27
28 nsIFocusManager = Cc['@mozilla.org/focus-manager;1']
29 .getService(Ci.nsIFocusManager)
30
31 XULDocument = Ci.nsIDOMXULDocument
32
33 class FrameEventManager
34 constructor: (@vim) ->
35 @numFocusToSuppress = 0
36 @keepInputs = false
37 @currentUrl = false
38 @disconnectActiveElementObserver = null
39
40 listen: utils.listen.bind(null, FRAME_SCRIPT_ENVIRONMENT)
41 listenOnce: utils.listenOnce.bind(null, FRAME_SCRIPT_ENVIRONMENT)
42
43 addListeners: ->
44 # If the page already was loaded when VimFx was initialized, send the
45 # 'frameCanReceiveEvents' message straight away.
46 if @vim.content.document.readyState == 'complete'
47 messageManager.send('frameCanReceiveEvents', true)
48
49 @listen('readystatechange', (event) =>
50 target = event.originalTarget
51 topDocument = @vim.content.document
52 [oldUrl, @currentUrl] = [@currentUrl, @vim.content.location.href]
53
54 switch target.readyState
55 when 'interactive'
56 if target == topDocument or
57 # When loading the editor on codepen.io, a frame gets
58 # 'readystatechange' → 'interactive' quite a bit before the
59 # toplevel document does. Checking for this case lets us send
60 # 'locationChange' earlier, allowing to enter Ignore mode earlier,
61 # for example. Be careful not to trigger a 'locationChange' for
62 # frames loading _after_ the toplevel document, though. Finally,
63 # checking for 'uninitialized' is needed to be able to blacklist
64 # some XUL pages.
65 (topDocument.readyState in ['loading', 'uninitialized'] and
66 oldUrl == null)
67 messageManager.send('locationChange', @currentUrl)
68
69 when 'complete'
70 if target == topDocument
71 messageManager.send('frameCanReceiveEvents', true)
72 )
73
74 @listen('pageshow', (event) =>
75 [oldUrl, @currentUrl] = [@currentUrl, @vim.content.location.href]
76
77 # When navigating the history, `event.persisted` is `true` (meaning that
78 # the page loaded from cache) and 'readystatechange' won’t be fired, so
79 # send a 'locationChange' message to make sure that the blacklist is
80 # applied etc. The reason we don’t simply _always_ do this on the
81 # 'pageshow' event, is because it usually fires too late. However, it also
82 # fires after having moved a tab to another window. In that case it is
83 # _not_ a location change; the blacklist should not be applied.
84 if event.persisted
85 url = @vim.content.location.href
86 messageManager.send('cachedPageshow', null, (movedToNewTab) =>
87 if not movedToNewTab and oldUrl != @currentUrl
88 messageManager.send('locationChange', @currentUrl)
89 )
90 )
91
92 @listen('pagehide', (event) =>
93 target = event.originalTarget
94 @currentUrl = null
95
96 if target == @vim.content.document
97 messageManager.send('frameCanReceiveEvents', false)
98 @vim._enterMode('normal') if @vim.mode == 'hints'
99
100 # If the target isn’t the topmost document, it means that a frame has
101 # changed: It could have been removed or its `src` attribute could have
102 # been changed. If the frame contains other frames, 'pagehide' events have
103 # already been fired for them.
104 @vim.resetState(target)
105 )
106
107 messageManager.listen('getMarkableElementsMovements', (data, callback) =>
108 diffs = @vim.state.markerElements.map(({element, originalRect}) ->
109 newRect = element.getBoundingClientRect()
110 return {
111 dx: newRect.left - originalRect.left
112 dy: newRect.top - originalRect.top
113 }
114 )
115 callback(diffs)
116 )
117
118 messageManager.listen('highlightMarkableElements', (data) =>
119 {elementIndices, strings} = data
120 utils.clearSelectionDeep(@vim.content)
121 return if strings.length == 0
122 for elementIndex in elementIndices
123 {element} = @vim.state.markerElements[elementIndex]
124 for string in strings
125 utils.selectAllSubstringMatches(
126 element, string, {caseSensitive: false}
127 )
128 return
129 )
130
131 @listen('overflow', (event) =>
132 target = event.originalTarget
133 @vim.state.scrollableElements.addChecked(target)
134 )
135
136 @listen('underflow', (event) =>
137 target = event.originalTarget
138 @vim.state.scrollableElements.deleteChecked(target)
139 )
140
141 @listen('submit', ((event) ->
142 return if event.defaultPrevented
143 target = event.originalTarget
144 {activeElement} = target.ownerDocument
145 if activeElement?.form == target and utils.isTypingElement(activeElement)
146 activeElement.blur()
147 ), false)
148
149 @listen('keydown', (event) =>
150 @keepInputs = false
151 )
152
153 @listen('keydown', ((event) =>
154 suppress = false
155
156 # This message _has_ to be synchronous so we can suppress the event if
157 # needed. To avoid sending a synchronous message on _every_ keydown, this
158 # hack of toggling a pref when a `<late>` shortcut is encountered is used.
159 if prefs.get('late')
160 suppress = messageManager.get('lateKeydown', {
161 defaultPrevented: event.defaultPrevented
162 })
163
164 if @vim.state.inputs and @vim.mode == 'normal' and not suppress and
165 not event.defaultPrevented
166 # There is no need to take `ignore_keyboard_layout` and `translations`
167 # into account here, since we want to override the _native_ `<tab>`
168 # behavior. Then, `event.key` is the way to go. (Unless the prefs are
169 # customized. YAGNI until requested.) Also, since 'keydown' is fired so
170 # often the options are read directly from the prefs system for
171 # performance. That means you can’t override them with
172 # `vimfx.addOptionOverrides`. YAGNI until requested.
173 keyStr = notation.stringify(event)
174 direction = switch keyStr
175 when ''
176 null
177 when prefs.get('focus_previous_key')
178 -1
179 when prefs.get('focus_next_key')
180 +1
181 else
182 null
183 if direction?
184 suppress = commands.move_focus({@vim, direction})
185 @keepInputs = true
186
187 if suppress
188 utils.suppressEvent(event)
189 @listenOnce('keyup', utils.suppressEvent, false)
190 ), false)
191
192 @listen('mousedown', (event) =>
193 # Allow clicking on another text input without exiting “gi mode”. Listen
194 # for 'mousedown' instead of 'click', because only the former runs before
195 # the 'blur' event. Also, `event.originalTarget` does _not_ work here.
196 @keepInputs = (@vim.state.inputs and event.target in @vim.state.inputs)
197
198 # Clicks are always counted as page interaction. Listen for 'mousedown'
199 # instead of 'click' to mark the interaction as soon as possible.
200 @vim.markPageInteraction()
201
202 @vim.hideNotification()
203 )
204
205 messageManager.listen('browserRefocus', =>
206 # Suppress the next two focus events (for `document` and `window`; see
207 # `blurActiveBrowserElement`).
208 @numFocusToSuppress = 2
209 )
210
211 @listen('focus', (event) =>
212 target = event.originalTarget
213
214 if @numFocusToSuppress > 0
215 utils.suppressEvent(event)
216 @numFocusToSuppress -= 1
217 return
218
219 @vim.state.explicitBodyFocus = (target == @vim.content.document.body)
220
221 @sendFocusType()
222
223 # Reset `hasInteraction` when (re-)selecting a tab, or coming back from
224 # another window, in order to prevent the common “automatically re-focus
225 # when switching back to the tab” behaviour many sites have, unless a text
226 # input _should_ be re-focused when coming back to the tab (see the 'blur'
227 # event below).
228 if target == @vim.content.document
229 if @vim.state.shouldRefocus
230 @vim.state.hasInteraction = true
231 @vim.state.shouldRefocus = false
232 else
233 @vim.state.hasInteraction = false
234 return
235
236 if utils.isTextInputElement(target)
237 # Save the last focused text input regardless of whether that input
238 # might be blurred because of autofocus prevention.
239 @vim.state.lastFocusedTextInput = target
240 @vim.state.hasFocusedTextInput = true
241
242 if @vim.mode == 'caret' and not utils.isContentEditable(target)
243 @vim._enterMode('normal')
244
245 # When moving a tab to another window, there is a short period of time
246 # when there’s no listener for this call.
247 return unless options = @vim.options(
248 ['prevent_autofocus', 'prevent_autofocus_modes']
249 )
250
251 # Blur the focus target, if autofocus prevention is enabled…
252 if options.prevent_autofocus and
253 @vim.mode in options.prevent_autofocus_modes and
254 # …and the user has interacted with the page…
255 not @vim.state.hasInteraction and
256 # …and the event is programmatic (not caused by clicks or keypresses)…
257 nsIFocusManager.getLastFocusMethod(null) == 0 and
258 # …and the target may steal most keystrokes…
259 utils.isTypingElement(target) and
260 # …and the page isn’t a Firefox internal page (like `about:config`).
261 @vim.content.document not instanceof XULDocument
262 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
263 # causing an infinite loop of autofocus prevention and re-focusing.
264 # Therefore, blur events that happen just after an autofocus prevention
265 # are suppressed.
266 @listenOnce('blur', utils.suppressEvent)
267 target.blur()
268 @vim.state.hasFocusedTextInput = false
269 )
270
271 @listen('blur', (event) =>
272 target = event.originalTarget
273
274 @vim.clearHover() if target == @vim.state.lastHover.element
275
276 @vim.content.setTimeout((=>
277 @sendFocusType()
278 ), prefs.get('blur_timeout'))
279
280 # If a text input is blurred immediately before the document loses focus,
281 # it most likely means that the user switched tab, for example by pressing
282 # `<c-tab>`, or switched to another window, while the text input was
283 # focused. In this case, when switching back to that tab, the text input
284 # will, and should, be re-focused (because it was focused when you left
285 # the tab). This case is kept track of so that the autofocus prevention
286 # does not catch it.
287 if utils.isTypingElement(target)
288 utils.nextTick(@vim.content, =>
289 @vim.state.shouldRefocus = not @vim.content.document.hasFocus()
290
291 # “gi mode” ends when blurring a text input, unless `<tab>` was just
292 # pressed.
293 unless @vim.state.shouldRefocus or @keepInputs
294 commands.clear_inputs({@vim})
295 )
296 )
297
298 messageManager.listen('checkFocusType', @sendFocusType.bind(this))
299
300 sendFocusType: ({ignore = []} = {}) ->
301 return unless activeElement = utils.getActiveElement(@vim.content)
302 focusType = utils.getFocusType(activeElement)
303 messageManager.send('focusType', focusType) unless focusType in ignore
304
305 # If a text input is removed from the DOM while it is focused, no 'focus'
306 # or 'blur' events will be fired, making VimFx think that the text input is
307 # still focused. Therefore we add a temporary observer for the currently
308 # focused element and re-send the focusType if it gets removed.
309 @disconnectActiveElementObserver?()
310 @disconnectActiveElementObserver =
311 if focusType == 'none'
312 null
313 else
314 utils.onRemoved(activeElement, @sendFocusType.bind(this))
315
316 module.exports = FrameEventManager
Imprint / Impressum