2 # Copyright Simon Lydell 2015.
4 # This file is part of VimFx.
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.
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.
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/>.
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.
25 hints = require('./hints')
26 utils = require('./utils')
28 { isProperLink, isTextInputElement, isContentEditable } = utils
30 XULDocument = Ci.nsIDOMXULDocument
34 commands.go_up_path = ({ vim, count = 1 }) ->
35 vim.content.location.pathname = vim.content.location.pathname.replace(
36 /// (?: /[^/]+ ){1,#{ count }} /?$ ///, ''
39 commands.go_to_root = ({ vim }) ->
40 vim.content.location.href = vim.content.location.origin
42 commands.scroll = (args) ->
43 { vim, method, type, direction, amount, property, smooth } = args
44 activeElement = utils.getActiveElement(vim.content)
45 document = activeElement.ownerDocument
47 if vim.state.scrollableElements.has(activeElement)
48 element = activeElement
51 # In quirks mode (when the page lacks a doctype) `<body>` is considered
52 # the root element rather than `<html>`.
53 if document.compatMode == 'BackCompat' and document.body?
56 document.documentElement
57 # If the entire page isn’t scrollable, scroll the largest scrollable element
59 if element.scrollHeight <= element.clientHeight and
60 vim.state.largestScrollableElement
61 element = vim.state.largestScrollableElement
64 options[direction] = switch type
65 when 'lines' then amount
66 when 'pages' then amount * element[property]
67 when 'other' then Math.min(amount, element[property])
68 options.behavior = 'smooth' if smooth
70 element[method](options)
72 # Combine links with the same href.
73 combine = (hrefs, element, wrapper) ->
74 if wrapper.type == 'link'
79 wrapper.parentIndex = parent.elementIndex
80 parent.shape.area += wrapper.shape.area
83 wrapper.numChildren = 0
87 commands.follow = ({ vim, storage }) ->
89 storage.markerElements = []
90 filter = (element, getElementShape) ->
91 document = element.ownerDocument
92 isXUL = (document instanceof XULDocument)
95 when isProperLink(element)
97 when isTextInputElement(element) or isContentEditable(element)
99 when element.tabIndex > -1 and
100 not (isXUL and element.nodeName.endsWith('box') and
101 element.nodeName != 'checkbox')
103 unless isXUL or element.nodeName in ['A', 'INPUT', 'BUTTON']
105 when element != document.documentElement and
106 vim.state.scrollableElements.has(element)
108 when element.hasAttribute('onclick') or
109 element.hasAttribute('onmousedown') or
110 element.hasAttribute('onmouseup') or
111 element.hasAttribute('oncommand') or
112 element.getAttribute('role') in ['link', 'button'] or
113 # Twitter special-case.
114 element.classList.contains('js-new-tweets-bar') or
115 # Feedly special-case.
116 element.hasAttribute('data-app-action') or
117 element.hasAttribute('data-uri') or
118 element.hasAttribute('data-page-action')
121 # Putting markers on `<label>` elements is generally redundant, because
122 # its `<input>` gets one. However, some sites hide the actual `<input>`
123 # but keeps the `<label>` to click, either for styling purposes or to keep
124 # the `<input>` hidden until it is used. In those cases we should add a
125 # marker for the `<label>`.
126 when element.nodeName == 'LABEL'
129 document.getElementById(element.htmlFor)
131 element.querySelector('input, textarea, select')
132 if input and not getElementShape(input)
134 # Elements that have “button” somewhere in the class might be clickable,
135 # unless they contain a real link or button or yet an element with
136 # “button” somewhere in the class, in which case they likely are
137 # “button-wrapper”s. (`<SVG element>.className` is not a string!)
138 when not isXUL and typeof element.className == 'string' and
139 element.className.toLowerCase().includes('button')
140 unless element.querySelector('a, button, [class*=button]')
143 # When viewing an image it should get a marker to toggle zoom.
144 when document.body?.childElementCount == 1 and
145 element.nodeName == 'IMG' and
146 (element.classList.contains('overflowing') or
147 element.classList.contains('shrinkToFit'))
150 return unless shape = getElementShape(element)
151 length = storage.markerElements.push(element)
153 hrefs, element, {elementIndex: length - 1, shape, semantic, type}
156 return hints.getMarkableElementsAndViewport(vim.content, filter)
158 commands.follow_in_tab = ({ vim, storage }) ->
160 storage.markerElements = []
161 filter = (element, getElementShape) ->
162 return unless isProperLink(element)
163 return unless shape = getElementShape(element)
164 length = storage.markerElements.push(element)
167 {elementIndex: length - 1, shape, semantic: true, type: 'link'}
170 return hints.getMarkableElementsAndViewport(vim.content, filter)
172 commands.follow_copy = ({ vim, storage }) ->
174 storage.markerElements = []
175 filter = (element, getElementShape) ->
177 when isProperLink(element) then 'link'
178 when isTextInputElement(element) then 'textInput'
179 when isContentEditable(element) then 'contenteditable'
181 return unless shape = getElementShape(element)
182 length = storage.markerElements.push(element)
184 hrefs, element, {elementIndex: length - 1, shape, semantic: true, type}
187 return hints.getMarkableElementsAndViewport(vim.content, filter)
189 commands.follow_focus = ({ vim, storage }) ->
190 storage.markerElements = []
191 filter = (element, getElementShape) ->
193 when element.tabIndex > -1
195 when element != element.ownerDocument.documentElement and
196 vim.state.scrollableElements.has(element)
199 return unless shape = getElementShape(element)
200 length = storage.markerElements.push(element)
201 return {elementIndex: length - 1, shape, semantic: true, type}
203 return hints.getMarkableElementsAndViewport(vim.content, filter)
205 commands.focus_marker_element = ({ storage, elementIndex, options }) ->
206 element = storage.markerElements[elementIndex]
207 utils.focusElement(element, options)
209 commands.click_marker_element = (args) ->
210 { vim, storage, elementIndex, preventTargetBlank } = args
211 element = storage.markerElements[elementIndex]
212 if element.target == '_blank' and preventTargetBlank
213 targetReset = element.target
215 utils.simulateClick(element)
216 element.target = targetReset if targetReset
218 commands.copy_marker_element = ({ storage, elementIndex, property }) ->
219 element = storage.markerElements[elementIndex]
220 utils.writeToClipboard(element[property])
222 commands.follow_pattern = ({ vim, type, options }) ->
223 { document } = vim.content
225 # If there’s a `<link rel=prev/next>` element we use that.
226 for link in document.head?.getElementsByTagName('link')
227 # Also support `rel=previous`, just like Google.
228 if type == link.rel.toLowerCase().replace(/^previous$/, 'prev')
229 vim.content.location.href = link.href
232 # Otherwise we look for a link or button on the page that seems to go to the
233 # previous or next page.
234 candidates = document.querySelectorAll(options.pattern_selector)
236 # Note: Earlier patterns should be favored.
237 { patterns } = options
239 # Search for the prev/next patterns in the following attributes of the
240 # element. `rel` should be kept as the first attribute, since the standard way
241 # of marking up prev/next links (`rel="prev"` and `rel="next"`) should be
242 # favored. Even though some of these attributes only allow a fixed set of
243 # keywords, we pattern-match them anyways since lots of sites don’t follow the
244 # spec and use the attributes arbitrarily.
245 attrs = options.pattern_attrs
248 # First search in attributes (favoring earlier attributes) as it's likely
249 # that they are more specific than text contexts.
251 for regex in patterns
252 for element in candidates
253 return element if regex.test(element.getAttribute(attr))
255 # Then search in element contents.
256 for regex in patterns
257 for element in candidates
258 return element if regex.test(element.textContent)
262 utils.simulateClick(matchingLink) if matchingLink
264 commands.focus_text_input = ({ vim, storage, count = null }) ->
265 { lastFocusedTextInput } = vim.state
266 inputs = Array.filter(
267 vim.content.document.querySelectorAll('input, textarea'), (element) ->
268 return utils.isTextInputElement(element) and utils.area(element) > 0
270 if lastFocusedTextInput and lastFocusedTextInput not in inputs
271 inputs.push(lastFocusedTextInput)
272 return unless inputs.length > 0
273 inputs.sort((a, b) -> a.tabIndex - b.tabIndex)
276 if lastFocusedTextInput
277 inputs.indexOf(lastFocusedTextInput) + 1
280 index = Math.min(count, inputs.length) - 1
281 utils.focusElement(inputs[index], {select: true})
282 storage.inputs = inputs
284 commands.clear_inputs = ({ storage }) ->
285 storage.inputs = null
287 commands.move_focus = ({ vim, storage, direction }) ->
289 index = storage.inputs.indexOf(utils.getActiveElement(vim.content))
291 storage.inputs = null
294 nextInput = inputs[(index + direction) %% inputs.length]
295 utils.focusElement(nextInput, {select: true})
298 utils.moveFocus(direction)
300 commands.esc = (args) ->
301 commands.blur_active_element(args)
303 { document } = args.vim.content
304 if document.exitFullscreen
305 document.exitFullscreen()
307 document.mozCancelFullScreen()
309 commands.blur_active_element = ({ vim }) ->
310 utils.blurActiveElement(vim.content, vim.state.scrollableElements)
312 module.exports = commands