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, isTypingElement, 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 = ({vim, method, type, direction, amount, property, smooth}) ->
43 activeElement = utils.getActiveElement(vim.content)
44 document = activeElement.ownerDocument
47 when vim.state.scrollableElements.has(activeElement)
49 # If the currently focused element isn’t scrollable, scroll the largest
50 # scrollable element instead, which usually means `<html>`.
51 when vim.state.scrollableElements.hasOrUpdateLargestScrollable()
52 {scrollableElements} = vim.state
53 # In quirks mode (when the page lacks a doctype) `<body>` is considered
54 # the root element rather than `<html>`. The 'overflow' event is triggered
55 # for `<html>` though (_not_ `<body>`!).
56 if scrollableElements.largest == document.documentElement and
57 document.compatMode == 'BackCompat' and document.body?
60 scrollableElements.largest
62 # This point should never be reached, but it’s better to be safe than
63 # sorry. Not being able to scroll is very annoying. Use the best bet.
64 document.documentElement
67 options[direction] = switch type
68 when 'lines' then amount
69 when 'pages' then amount * element[property]
70 when 'other' then Math.min(amount, element[property])
71 options.behavior = 'smooth' if smooth
73 element[method](options)
75 helper_follow = ({id, combine = true}, matcher, {vim}) ->
77 vim.state.markerElements = []
79 filter = (element, getElementShape) ->
80 {type, semantic} = matcher({vim, element, getElementShape})
82 customMatcher = FRAME_SCRIPT_ENVIRONMENT.VimFxHintMatcher
84 {type, semantic} = customMatcher(id, element, {type, semantic})
87 return unless shape = getElementShape(element)
89 length = vim.state.markerElements.push(element)
90 wrapper = {type, semantic, shape, elementIndex: length - 1}
92 # Combine links with the same href.
93 if combine and wrapper.type == 'link'
98 wrapper.parentIndex = parent.elementIndex
99 parent.shape.area += wrapper.shape.area
102 wrapper.numChildren = 0
103 hrefs[href] = wrapper
107 return hints.getMarkableElementsAndViewport(vim.content, filter)
109 commands.follow = helper_follow.bind(null, {id: 'normal'},
110 ({vim, element, getElementShape}) ->
111 document = element.ownerDocument
112 isXUL = (document instanceof XULDocument)
116 when isProperLink(element)
118 when isTypingElement(element) or isContentEditable(element)
120 when element.tabIndex > -1 and
121 not (isXUL and element.nodeName.endsWith('box') and
122 element.nodeName != 'checkbox')
124 unless isXUL or element.nodeName in ['A', 'INPUT', 'BUTTON']
126 when element != document.documentElement and
127 vim.state.scrollableElements.has(element)
129 when element.hasAttribute('onclick') or
130 element.hasAttribute('onmousedown') or
131 element.hasAttribute('onmouseup') or
132 element.hasAttribute('oncommand') or
133 element.getAttribute('role') in ['link', 'button'] or
134 # Twitter special-case.
135 element.classList.contains('js-new-tweets-bar') or
136 # Feedly special-case.
137 element.hasAttribute('data-app-action') or
138 element.hasAttribute('data-uri') or
139 element.hasAttribute('data-page-action')
142 # Facebook special-case (comment fields).
143 when element.parentElement?.classList.contains('UFIInputContainer')
144 type = 'clickable-special'
145 # Putting markers on `<label>` elements is generally redundant, because
146 # its `<input>` gets one. However, some sites hide the actual `<input>`
147 # but keeps the `<label>` to click, either for styling purposes or to keep
148 # the `<input>` hidden until it is used. In those cases we should add a
149 # marker for the `<label>`.
150 when element.nodeName == 'LABEL'
153 document.getElementById(element.htmlFor)
155 element.querySelector('input, textarea, select')
156 if input and not getElementShape(input)
158 # Elements that have “button” somewhere in the class might be clickable,
159 # unless they contain a real link or button or yet an element with
160 # “button” somewhere in the class, in which case they likely are
161 # “button-wrapper”s. (`<SVG element>.className` is not a string!)
162 when not isXUL and typeof element.className == 'string' and
163 element.className.toLowerCase().includes('button')
164 unless element.querySelector('a, button, [class*=button]')
167 # When viewing an image it should get a marker to toggle zoom.
168 when document.body?.childElementCount == 1 and
169 element.nodeName == 'IMG' and
170 (element.classList.contains('overflowing') or
171 element.classList.contains('shrinkToFit'))
173 return {type, semantic}
176 commands.follow_in_tab = helper_follow.bind(null, {id: 'tab'},
178 type = if isProperLink(element) then 'link' else null
179 return {type, semantic: true}
182 commands.follow_copy = helper_follow.bind(null, {id: 'copy'},
185 when isProperLink(element) then 'link'
186 when isTypingElement(element) then 'text'
187 when isContentEditable(element) then 'contenteditable'
189 return {type, semantic: true}
192 commands.follow_focus = helper_follow.bind(null, {id: 'focus', combine: false},
195 when element.tabIndex > -1
197 when element != element.ownerDocument.documentElement and
198 vim.state.scrollableElements.has(element)
202 return {type, semantic: true}
205 commands.focus_marker_element = ({vim, elementIndex, options}) ->
206 element = vim.state.markerElements[elementIndex]
207 utils.focusElement(element, options)
209 commands.click_marker_element = (args) ->
210 {vim, elementIndex, preventTargetBlank, type} = args
211 element = vim.state.markerElements[elementIndex]
212 if element.target == '_blank' and preventTargetBlank
213 targetReset = element.target
215 if type == 'clickable-special'
218 utils.simulateClick(element)
219 element.target = targetReset if targetReset
221 commands.copy_marker_element = ({vim, elementIndex, property}) ->
222 element = vim.state.markerElements[elementIndex]
223 utils.writeToClipboard(element[property])
225 commands.follow_pattern = ({vim, type, options}) ->
226 {document} = vim.content
228 # If there’s a `<link rel=prev/next>` element we use that.
229 for link in document.head?.getElementsByTagName('link')
230 # Also support `rel=previous`, just like Google.
231 if type == link.rel.toLowerCase().replace(/^previous$/, 'prev')
232 vim.content.location.href = link.href
235 # Otherwise we look for a link or button on the page that seems to go to the
236 # previous or next page.
237 candidates = document.querySelectorAll(options.pattern_selector)
239 # Note: Earlier patterns should be favored.
242 # Search for the prev/next patterns in the following attributes of the
243 # element. `rel` should be kept as the first attribute, since the standard way
244 # of marking up prev/next links (`rel="prev"` and `rel="next"`) should be
245 # favored. Even though some of these attributes only allow a fixed set of
246 # keywords, we pattern-match them anyways since lots of sites don’t follow the
247 # spec and use the attributes arbitrarily.
248 attrs = options.pattern_attrs
251 # First search in attributes (favoring earlier attributes) as it's likely
252 # that they are more specific than text contexts.
254 for regex in patterns
255 for element in candidates
256 return element if regex.test(element.getAttribute(attr))
258 # Then search in element contents.
259 for regex in patterns
260 for element in candidates
261 return element if regex.test(element.textContent)
265 utils.simulateClick(matchingLink) if matchingLink
267 commands.focus_text_input = ({vim, count = null}) ->
268 {lastFocusedTextInput} = vim.state
269 inputs = Array.filter(
270 utils.querySelectorAllDeep(vim.content, 'input, textarea'), (element) ->
271 return isTextInputElement(element) and utils.area(element) > 0
273 if lastFocusedTextInput and lastFocusedTextInput not in inputs
274 inputs.push(lastFocusedTextInput)
275 return unless inputs.length > 0
276 inputs.sort((a, b) -> a.tabIndex - b.tabIndex)
279 if lastFocusedTextInput
280 inputs.indexOf(lastFocusedTextInput) + 1
283 index = Math.min(count, inputs.length) - 1
284 utils.focusElement(inputs[index], {select: true})
285 vim.state.inputs = inputs
287 commands.clear_inputs = ({vim}) ->
288 vim.state.inputs = null
290 commands.move_focus = ({vim, direction}) ->
291 return false unless vim.state.inputs
292 index = vim.state.inputs.indexOf(utils.getActiveElement(vim.content))
293 # If there’s only one input, `<tab>` would cycle to itself, making it feel
294 # like `<tab>` was not working. Then it’s better to let `<tab>` work as it
296 if index == -1 or vim.state.inputs.length <= 1
297 vim.state.inputs = null
301 nextInput = inputs[(index + direction) %% inputs.length]
302 utils.focusElement(nextInput, {select: true})
305 commands.esc = (args) ->
306 commands.blur_active_element(args)
308 {document} = args.vim.content
309 if document.exitFullscreen
310 document.exitFullscreen()
312 document.mozCancelFullScreen()
314 commands.blur_active_element = ({vim}) ->
315 utils.blurActiveElement(vim.content)
317 module.exports = commands