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