]> git.gir.st - VimFx.git/blob - extension/lib/commands-frame.coffee
Enhance detection of `<label>`s with hidden `<input>`
[VimFx.git] / extension / lib / commands-frame.coffee
1 ###
2 # Copyright Simon Lydell 2015.
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 commands.coffee, but for frame scripts,
21 # allowing interaction with web page content. Most “commands” here have the
22 # same name as the command in commands.coffee that calls it. There are also a
23 # few more generalized “commands” used in more than one place.
24
25 hints = require('./hints')
26 utils = require('./utils')
27
28 { isProperLink, isTextInputElement, isContentEditable } = utils
29
30 XULDocument = Ci.nsIDOMXULDocument
31
32 commands = {}
33
34 commands.go_up_path = ({ vim, count = 1 }) ->
35 vim.content.location.pathname = vim.content.location.pathname.replace(
36 /// (?: /[^/]+ ){1,#{ count }} /?$ ///, ''
37 )
38
39 commands.go_to_root = ({ vim }) ->
40 vim.content.location.href = vim.content.location.origin
41
42 commands.scroll = (args) ->
43 { vim, method, type, direction, amount, property, smooth } = args
44 activeElement = utils.getActiveElement(vim.content)
45 document = activeElement.ownerDocument
46 element =
47 if vim.state.scrollableElements.has(activeElement)
48 activeElement
49 else
50 document.documentElement
51
52 options = {}
53 options[direction] = switch type
54 when 'lines' then amount
55 when 'pages' then amount * element[property]
56 when 'other' then Math.min(amount, element[property])
57 options.behavior = 'smooth' if smooth
58
59 element[method](options)
60 # When scrolling the whole page, the body sometimes needs to be scrolled
61 # too.
62 if element == document.documentElement
63 document.body?[method](options)
64
65 # Combine links with the same href.
66 combine = (hrefs, element, wrapper) ->
67 if wrapper.type == 'link'
68 { href } = element
69 wrapper.href = href
70 if href of hrefs
71 parent = hrefs[href]
72 wrapper.parentIndex = parent.elementIndex
73 parent.shape.area += wrapper.shape.area
74 parent.numChildren++
75 else
76 wrapper.numChildren = 0
77 hrefs[href] = wrapper
78 return wrapper
79
80 commands.follow = ({ vim, storage }) ->
81 hrefs = {}
82 storage.markerElements = []
83 filter = (element, getElementShape) ->
84 document = element.ownerDocument
85 isXUL = (document instanceof XULDocument)
86 semantic = true
87 switch
88 when isProperLink(element)
89 type = 'link'
90 when isTextInputElement(element) or isContentEditable(element)
91 type = 'text'
92 when element.tabIndex > -1 and
93 not (isXUL and element.nodeName.endsWith('box'))
94 type = 'clickable'
95 unless isXUL or element.nodeName in ['A', 'INPUT', 'BUTTON']
96 semantic = false
97 when element != document.documentElement and
98 vim.state.scrollableElements.has(element)
99 type = 'scrollable'
100 when element.hasAttribute('onclick') or
101 element.hasAttribute('onmousedown') or
102 element.hasAttribute('onmouseup') or
103 element.hasAttribute('oncommand') or
104 element.getAttribute('role') in ['link', 'button'] or
105 # Twitter special-case.
106 element.classList.contains('js-new-tweets-bar') or
107 # Feedly special-case.
108 element.hasAttribute('data-app-action') or
109 element.hasAttribute('data-uri') or
110 element.hasAttribute('data-page-action')
111 type = 'clickable'
112 semantic = false
113 # Putting markers on `<label>` elements is generally redundant, because
114 # its `<input>` gets one. However, some sites hide the actual `<input>`
115 # but keeps the `<label>` to click, either for styling purposes or to keep
116 # the `<input>` hidden until it is used. In those cases we should add a
117 # marker for the `<label>`.
118 when element.nodeName == 'LABEL'
119 input =
120 if element.htmlFor
121 document.getElementById(element.htmlFor)
122 else
123 element.querySelector('input, textarea, select')
124 if input and not getElementShape(input)
125 type = 'clickable'
126 # Elements that have “button” somewhere in the class might be clickable,
127 # unless they contain a real link or button or yet an element with
128 # “button” somewhere in the class, in which case they likely are
129 # “button-wrapper”s. (`<SVG element>.className` is not a string!)
130 when not isXUL and typeof element.className == 'string' and
131 element.className.toLowerCase().includes('button')
132 unless element.querySelector('a, button, [class*=button]')
133 type = 'clickable'
134 semantic = false
135 # When viewing an image it should get a marker to toggle zoom.
136 when document.body?.childElementCount == 1 and
137 element.nodeName == 'IMG' and
138 (element.classList.contains('overflowing') or
139 element.classList.contains('shrinkToFit'))
140 type = 'clickable'
141 return unless type
142 return unless shape = getElementShape(element)
143 length = storage.markerElements.push(element)
144 return combine(
145 hrefs, element, {elementIndex: length - 1, shape, semantic, type}
146 )
147
148 return hints.getMarkableElementsAndViewport(vim.content, filter)
149
150 commands.follow_in_tab = ({ vim, storage }) ->
151 hrefs = {}
152 storage.markerElements = []
153 filter = (element, getElementShape) ->
154 return unless isProperLink(element)
155 return unless shape = getElementShape(element)
156 length = storage.markerElements.push(element)
157 return combine(
158 hrefs, element,
159 {elementIndex: length - 1, shape, semantic: true, type: 'link'}
160 )
161
162 return hints.getMarkableElementsAndViewport(vim.content, filter)
163
164 commands.follow_copy = ({ vim, storage }) ->
165 hrefs = {}
166 storage.markerElements = []
167 filter = (element, getElementShape) ->
168 type = switch
169 when isProperLink(element) then 'link'
170 when isTextInputElement(element) then 'textInput'
171 when isContentEditable(element) then 'contenteditable'
172 return unless type
173 return unless shape = getElementShape(element)
174 length = storage.markerElements.push(element)
175 return combine(
176 hrefs, element, {elementIndex: length - 1, shape, semantic: true, type}
177 )
178
179 return hints.getMarkableElementsAndViewport(vim.content, filter)
180
181 commands.follow_focus = ({ vim, storage }) ->
182 storage.markerElements = []
183 filter = (element, getElementShape) ->
184 type = switch
185 when element.tabIndex > -1
186 'focusable'
187 when element != element.ownerDocument.documentElement and
188 vim.state.scrollableElements.has(element)
189 'scrollable'
190 return unless type
191 return unless shape = getElementShape(element)
192 length = storage.markerElements.push(element)
193 return {elementIndex: length - 1, shape, semantic: true, type}
194
195 return hints.getMarkableElementsAndViewport(vim.content, filter)
196
197 commands.focus_marker_element = ({ storage, elementIndex, options }) ->
198 element = storage.markerElements[elementIndex]
199 utils.focusElement(element, options)
200
201 commands.click_marker_element = (args) ->
202 { vim, storage, elementIndex, preventTargetBlank } = args
203 element = storage.markerElements[elementIndex]
204 if element.target == '_blank' and preventTargetBlank
205 targetReset = element.target
206 element.target = ''
207 utils.simulateClick(element)
208 element.target = targetReset if targetReset
209
210 commands.copy_marker_element = ({ storage, elementIndex, property }) ->
211 element = storage.markerElements[elementIndex]
212 utils.writeToClipboard(element[property])
213
214 commands.follow_pattern = ({ vim, type, options }) ->
215 { document } = vim.content
216
217 # If there’s a `<link rel=prev/next>` element we use that.
218 for link in document.head?.getElementsByTagName('link')
219 # Also support `rel=previous`, just like Google.
220 if type == link.rel.toLowerCase().replace(/^previous$/, 'prev')
221 vim.content.location.href = link.href
222 return
223
224 # Otherwise we look for a link or button on the page that seems to go to the
225 # previous or next page.
226 candidates = document.querySelectorAll(options.pattern_selector)
227
228 # Note: Earlier patterns should be favored.
229 { patterns } = options
230
231 # Search for the prev/next patterns in the following attributes of the
232 # element. `rel` should be kept as the first attribute, since the standard way
233 # of marking up prev/next links (`rel="prev"` and `rel="next"`) should be
234 # favored. Even though some of these attributes only allow a fixed set of
235 # keywords, we pattern-match them anyways since lots of sites don’t follow the
236 # spec and use the attributes arbitrarily.
237 attrs = options.pattern_attrs
238
239 matchingLink = do ->
240 # Helper function that matches a string against all the patterns.
241 matches = (text) -> patterns.some((regex) -> regex.test(text))
242
243 # First search in attributes (favoring earlier attributes) as it's likely
244 # that they are more specific than text contexts.
245 for attr in attrs
246 for element in candidates
247 return element if matches(element.getAttribute(attr))
248
249 # Then search in element contents.
250 for element in candidates
251 return element if matches(element.textContent)
252
253 return null
254
255 utils.simulateClick(matchingLink) if matchingLink
256
257 commands.focus_text_input = ({ vim, storage, count = null }) ->
258 { lastFocusedTextInput } = vim.state
259 inputs = Array.filter(
260 vim.content.document.querySelectorAll('input, textarea'), (element) ->
261 return utils.isTextInputElement(element) and utils.area(element) > 0
262 )
263 if lastFocusedTextInput and lastFocusedTextInput not in inputs
264 inputs.push(lastFocusedTextInput)
265 return unless inputs.length > 0
266 inputs.sort((a, b) -> a.tabIndex - b.tabIndex)
267 unless count?
268 count =
269 if lastFocusedTextInput
270 inputs.indexOf(lastFocusedTextInput) + 1
271 else
272 1
273 index = Math.min(count, inputs.length) - 1
274 utils.focusElement(inputs[index], {select: true})
275 storage.inputs = inputs
276
277 commands.clear_inputs = ({ storage }) ->
278 storage.inputs = null
279
280 commands.move_focus = ({ vim, storage, direction }) ->
281 if storage.inputs
282 index = storage.inputs.indexOf(utils.getActiveElement(vim.content))
283 if index == -1
284 storage.inputs = null
285 else
286 { inputs } = storage
287 nextInput = inputs[(index + direction) %% inputs.length]
288 utils.focusElement(nextInput, {select: true})
289 return
290
291 utils.moveFocus(direction)
292
293 commands.esc = ({ vim }) ->
294 utils.blurActiveElement(vim.content)
295
296 { document } = vim.content
297 if document.exitFullscreen
298 document.exitFullscreen()
299 else
300 document.mozCancelFullScreen()
301
302 commands.blur_active_element = ({ vim }) ->
303 utils.blurActiveElement(vim.content)
304
305 module.exports = commands
Imprint / Impressum