]> git.gir.st - VimFx.git/blob - extension/lib/events-frame.coffee
Merge branch 'master' into develop
[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.
63 (topDocument.readyState == 'loading' and oldUrl == null)
64 messageManager.send('locationChange', @currentUrl)
65
66 when 'complete'
67 if target == topDocument
68 messageManager.send('frameCanReceiveEvents', true)
69 )
70
71 @listen('pageshow', (event) =>
72 [oldUrl, @currentUrl] = [@currentUrl, @vim.content.location.href]
73
74 # When navigating the history, `event.persisted` is `true` (meaning that
75 # the page loaded from cache) and 'readystatechange' won’t be fired, so
76 # send a 'locationChange' message to make sure that the blacklist is
77 # applied etc. The reason we don’t simply _always_ do this on the
78 # 'pageshow' event, is because it usually fires too late. However, it also
79 # fires after having moved a tab to another window. In that case it is
80 # _not_ a location change; the blacklist should not be applied.
81 if event.persisted
82 url = @vim.content.location.href
83 messageManager.send('cachedPageshow', null, (movedToNewTab) =>
84 if not movedToNewTab and oldUrl != @currentUrl
85 messageManager.send('locationChange', @currentUrl)
86 )
87 )
88
89 @listen('pagehide', (event) =>
90 target = event.originalTarget
91 @currentUrl = null
92
93 if target == @vim.content.document
94 messageManager.send('frameCanReceiveEvents', false)
95
96 # If the target isn’t the topmost document, it means that a frame has
97 # changed: It could have been removed or its `src` attribute could have
98 # been changed. If the frame contains other frames, 'pagehide' events have
99 # already been fired for them.
100 @vim.resetState(target)
101 )
102
103 messageManager.listen('getMarkableElementsMovements', (data, callback) =>
104 diffs = @vim.state.markerElements.map(({element, originalRect}) ->
105 newRect = element.getBoundingClientRect()
106 return {
107 dx: newRect.left - originalRect.left
108 dy: newRect.top - originalRect.top
109 }
110 )
111 callback(diffs)
112 )
113
114 @listen('overflow', (event) =>
115 target = event.originalTarget
116 @vim.state.scrollableElements.addChecked(target)
117 )
118
119 @listen('underflow', (event) =>
120 target = event.originalTarget
121 @vim.state.scrollableElements.deleteChecked(target)
122 )
123
124 @listen('keydown', (event) =>
125 @keepInputs = false
126 )
127
128 @listen('keydown', ((event) =>
129 suppress = false
130
131 # This message _has_ to be synchronous so we can suppress the event if
132 # needed. To avoid sending a synchronous message on _every_ keydown, this
133 # hack of toggling a pref when a `<late>` shortcut is encountered is used.
134 if prefs.get('late')
135 suppress = messageManager.get('lateKeydown', {
136 defaultPrevented: event.defaultPrevented
137 })
138
139 if @vim.state.inputs and @vim.mode == 'normal' and not suppress and
140 not event.defaultPrevented
141 # There is no need to take `ignore_keyboard_layout` and `translations`
142 # into account here, since we want to override the _native_ `<tab>`
143 # behavior. Then, `event.key` is the way to go. (Unless the prefs are
144 # customized. YAGNI until requested.)
145 keyStr = notation.stringify(event)
146 direction = switch keyStr
147 when ''
148 null
149 when prefs.get('focus_previous_key')
150 -1
151 when prefs.get('focus_next_key')
152 +1
153 else
154 null
155 if direction?
156 suppress = commands.move_focus({@vim, direction})
157 @keepInputs = true
158
159 if suppress
160 utils.suppressEvent(event)
161 @listenOnce('keyup', utils.suppressEvent, false)
162 ), false)
163
164 @listen('mousedown', (event) =>
165 # Allow clicking on another text input without exiting “gi mode”. Listen
166 # for 'mousedown' instead of 'click', because only the former runs before
167 # the 'blur' event. Also, `event.originalTarget` does _not_ work here.
168 @keepInputs = (@vim.state.inputs and event.target in @vim.state.inputs)
169
170 # Clicks are always counted as page interaction. Listen for 'mousedown'
171 # instead of 'click' to mark the interaction as soon as possible.
172 @vim.markPageInteraction()
173 )
174
175 messageManager.listen('browserRefocus', =>
176 # Suppress the next two focus events (for `document` and `window`; see
177 # `blurActiveBrowserElement`).
178 @numFocusToSuppress = 2
179 )
180
181 @listen('focus', (event) =>
182 target = event.originalTarget
183
184 if @numFocusToSuppress > 0
185 utils.suppressEvent(event)
186 @numFocusToSuppress -= 1
187 return
188
189 @vim.state.explicitBodyFocus = (target == @vim.content.document.body)
190
191 @sendFocusType()
192
193 # Reset `hasInteraction` when (re-)selecting a tab, or coming back from
194 # another window, in order to prevent the common “automatically re-focus
195 # when switching back to the tab” behaviour many sites have, unless a text
196 # input _should_ be re-focused when coming back to the tab (see the 'blur'
197 # event below).
198 if target == @vim.content.document
199 if @vim.state.shouldRefocus
200 @vim.state.hasInteraction = true
201 @vim.state.shouldRefocus = false
202 else
203 @vim.state.hasInteraction = false
204 return
205
206 # Save the last focused text input regardless of whether that input might
207 # be blurred because of autofocus prevention.
208 if utils.isTextInputElement(target)
209 @vim.state.lastFocusedTextInput = target
210 @vim.state.hasFocusedTextInput = true
211
212 # Blur the focus target, if autofocus prevention is enabled…
213 if prefs.get('prevent_autofocus') and
214 @vim.mode in prefs.get('prevent_autofocus_modes').split(/\s+/) and
215 # …and the user has interacted with the page…
216 not @vim.state.hasInteraction and
217 # …and the event is programmatic (not caused by clicks or keypresses)…
218 nsIFocusManager.getLastFocusMethod(null) == 0 and
219 # …and the target may steal most keystrokes…
220 utils.isTypingElement(target) and
221 # …and the page isn’t a Firefox internal page (like `about:config`).
222 @vim.content.document not instanceof XULDocument
223 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
224 # causing an infinite loop of autofocus prevention and re-focusing.
225 # Therefore, blur events that happen just after an autofocus prevention
226 # are suppressed.
227 @listenOnce('blur', utils.suppressEvent)
228 target.blur()
229 @vim.state.hasFocusedTextInput = false
230 )
231
232 @listen('blur', (event) =>
233 target = event.originalTarget
234
235 @sendFocusType()
236
237 # If a text input is blurred immediately before the document loses focus,
238 # it most likely means that the user switched tab, for example by pressing
239 # `<c-tab>`, or switched to another window, while the text input was
240 # focused. In this case, when switching back to that tab, the text input
241 # will, and should, be re-focused (because it was focused when you left
242 # the tab). This case is kept track of so that the autofocus prevention
243 # does not catch it.
244 if utils.isTypingElement(target)
245 utils.nextTick(@vim.content, =>
246 @vim.state.shouldRefocus = not @vim.content.document.hasFocus()
247
248 # “gi mode” ends when blurring a text input, unless `<tab>` was just
249 # pressed.
250 unless @vim.state.shouldRefocus or @keepInputs
251 commands.clear_inputs({@vim})
252 )
253 )
254
255 sendFocusType: ({ignore = []} = {}) ->
256 return unless activeElement = utils.getActiveElement(@vim.content)
257 focusType = utils.getFocusType(activeElement)
258 messageManager.send('focusType', focusType) unless focusType in ignore
259
260 # If a text input is removed from the DOM while it is focused, no 'focus'
261 # or 'blur' events will be fired, making VimFx think that the text input is
262 # still focused. Therefore we add a temporary observer for the currently
263 # focused element and re-send the focusType if it gets removed.
264 @disconnectActiveElementObserver?()
265 @disconnectActiveElementObserver =
266 if focusType == 'none'
267 null
268 else
269 utils.onRemoved(activeElement, @sendFocusType.bind(this))
270
271 module.exports = FrameEventManager
Imprint / Impressum