]> git.gir.st - VimFx.git/blob - extension/lib/events-frame.coffee
Fix unmousable bottom-right corner of the page scrollbars
[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 @listen('overflow', (event) =>
119 target = event.originalTarget
120 @vim.state.scrollableElements.addChecked(target)
121 )
122
123 @listen('underflow', (event) =>
124 target = event.originalTarget
125 @vim.state.scrollableElements.deleteChecked(target)
126 )
127
128 @listen('submit', ((event) ->
129 return if event.defaultPrevented
130 target = event.originalTarget
131 {activeElement} = target.ownerDocument
132 if activeElement?.form == target and utils.isTypingElement(activeElement)
133 activeElement.blur()
134 ), false)
135
136 @listen('keydown', (event) =>
137 @keepInputs = false
138 )
139
140 @listen('keydown', ((event) =>
141 suppress = false
142
143 # This message _has_ to be synchronous so we can suppress the event if
144 # needed. To avoid sending a synchronous message on _every_ keydown, this
145 # hack of toggling a pref when a `<late>` shortcut is encountered is used.
146 if prefs.get('late')
147 suppress = messageManager.get('lateKeydown', {
148 defaultPrevented: event.defaultPrevented
149 })
150
151 if @vim.state.inputs and @vim.mode == 'normal' and not suppress and
152 not event.defaultPrevented
153 # There is no need to take `ignore_keyboard_layout` and `translations`
154 # into account here, since we want to override the _native_ `<tab>`
155 # behavior. Then, `event.key` is the way to go. (Unless the prefs are
156 # customized. YAGNI until requested.)
157 keyStr = notation.stringify(event)
158 direction = switch keyStr
159 when ''
160 null
161 when prefs.get('focus_previous_key')
162 -1
163 when prefs.get('focus_next_key')
164 +1
165 else
166 null
167 if direction?
168 suppress = commands.move_focus({@vim, direction})
169 @keepInputs = true
170
171 if suppress
172 utils.suppressEvent(event)
173 @listenOnce('keyup', utils.suppressEvent, false)
174 ), false)
175
176 @listen('mousedown', (event) =>
177 # Allow clicking on another text input without exiting “gi mode”. Listen
178 # for 'mousedown' instead of 'click', because only the former runs before
179 # the 'blur' event. Also, `event.originalTarget` does _not_ work here.
180 @keepInputs = (@vim.state.inputs and event.target in @vim.state.inputs)
181
182 # Clicks are always counted as page interaction. Listen for 'mousedown'
183 # instead of 'click' to mark the interaction as soon as possible.
184 @vim.markPageInteraction()
185
186 @vim.hideNotification()
187 )
188
189 messageManager.listen('browserRefocus', =>
190 # Suppress the next two focus events (for `document` and `window`; see
191 # `blurActiveBrowserElement`).
192 @numFocusToSuppress = 2
193 )
194
195 @listen('focus', (event) =>
196 target = event.originalTarget
197
198 if @numFocusToSuppress > 0
199 utils.suppressEvent(event)
200 @numFocusToSuppress -= 1
201 return
202
203 @vim.state.explicitBodyFocus = (target == @vim.content.document.body)
204
205 @sendFocusType()
206
207 # Reset `hasInteraction` when (re-)selecting a tab, or coming back from
208 # another window, in order to prevent the common “automatically re-focus
209 # when switching back to the tab” behaviour many sites have, unless a text
210 # input _should_ be re-focused when coming back to the tab (see the 'blur'
211 # event below).
212 if target == @vim.content.document
213 if @vim.state.shouldRefocus
214 @vim.state.hasInteraction = true
215 @vim.state.shouldRefocus = false
216 else
217 @vim.state.hasInteraction = false
218 return
219
220 if utils.isTextInputElement(target)
221 # Save the last focused text input regardless of whether that input
222 # might be blurred because of autofocus prevention.
223 @vim.state.lastFocusedTextInput = target
224 @vim.state.hasFocusedTextInput = true
225
226 if @vim.mode == 'caret' and not utils.isContentEditable(target)
227 @vim.enterMode('normal')
228
229 # Blur the focus target, if autofocus prevention is enabled…
230 if prefs.get('prevent_autofocus') and
231 @vim.mode in prefs.get('prevent_autofocus_modes').split(/\s+/) and
232 # …and the user has interacted with the page…
233 not @vim.state.hasInteraction and
234 # …and the event is programmatic (not caused by clicks or keypresses)…
235 nsIFocusManager.getLastFocusMethod(null) == 0 and
236 # …and the target may steal most keystrokes…
237 utils.isTypingElement(target) and
238 # …and the page isn’t a Firefox internal page (like `about:config`).
239 @vim.content.document not instanceof XULDocument
240 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
241 # causing an infinite loop of autofocus prevention and re-focusing.
242 # Therefore, blur events that happen just after an autofocus prevention
243 # are suppressed.
244 @listenOnce('blur', utils.suppressEvent)
245 target.blur()
246 @vim.state.hasFocusedTextInput = false
247 )
248
249 @listen('blur', (event) =>
250 target = event.originalTarget
251
252 @vim.clearHover() if target == @vim.state.lastHoveredElement
253
254 @vim.content.setTimeout((=>
255 @sendFocusType()
256 ), prefs.get('blur_timeout'))
257
258 # If a text input is blurred immediately before the document loses focus,
259 # it most likely means that the user switched tab, for example by pressing
260 # `<c-tab>`, or switched to another window, while the text input was
261 # focused. In this case, when switching back to that tab, the text input
262 # will, and should, be re-focused (because it was focused when you left
263 # the tab). This case is kept track of so that the autofocus prevention
264 # does not catch it.
265 if utils.isTypingElement(target)
266 utils.nextTick(@vim.content, =>
267 @vim.state.shouldRefocus = not @vim.content.document.hasFocus()
268
269 # “gi mode” ends when blurring a text input, unless `<tab>` was just
270 # pressed.
271 unless @vim.state.shouldRefocus or @keepInputs
272 commands.clear_inputs({@vim})
273 )
274 )
275
276 messageManager.listen('checkFocusType', @sendFocusType.bind(this))
277
278 sendFocusType: ({ignore = []} = {}) ->
279 return unless activeElement = utils.getActiveElement(@vim.content)
280 focusType = utils.getFocusType(activeElement)
281 messageManager.send('focusType', focusType) unless focusType in ignore
282
283 # If a text input is removed from the DOM while it is focused, no 'focus'
284 # or 'blur' events will be fired, making VimFx think that the text input is
285 # still focused. Therefore we add a temporary observer for the currently
286 # focused element and re-send the focusType if it gets removed.
287 @disconnectActiveElementObserver?()
288 @disconnectActiveElementObserver =
289 if focusType == 'none'
290 null
291 else
292 utils.onRemoved(activeElement, @sendFocusType.bind(this))
293
294 module.exports = FrameEventManager
Imprint / Impressum