1 # This file contains lots of different helper functions.
3 {OS} = Components.utils.import('resource://gre/modules/osfile.jsm', {})
5 nsIClipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
6 .getService(Ci.nsIClipboardHelper)
7 nsIEventListenerService = Cc['@mozilla.org/eventlistenerservice;1']
8 .getService(Ci.nsIEventListenerService)
9 nsIFocusManager = Cc['@mozilla.org/focus-manager;1']
10 .getService(Ci.nsIFocusManager)
11 nsIStyleSheetService = Cc['@mozilla.org/content/style-sheet-service;1']
12 .getService(Ci.nsIStyleSheetService)
13 nsIWindowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
14 .getService(Ci.nsIWindowMediator)
16 # This interface was removed from Firefox with no alternative. Try to use it if
17 # available but otherwise just ignore it. Code in this module handles this
18 # variable being `null`.
21 Cc['@mozilla.org/inspector/dom-utils;1']
22 .getService(Ci.inIDOMUtils)
26 # For XUL, `instanceof` checks are often better than `.localName` checks,
27 # because some of the below interfaces are extended by many elements.
28 XULButtonElement = Ci.nsIDOMXULButtonElement
29 XULControlElement = Ci.nsIDOMXULControlElement
30 XULMenuListElement = Ci.nsIDOMXULMenuListElement
31 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
33 isXULDocument = (doc) ->
34 doc.toString() == '[object XULDocument]'
36 # Full chains of events for different mouse actions. Note: 'click' is fired
37 # by Firefox automatically after 'mousedown' and 'mouseup'. Similarly,
38 # 'command' is fired automatically after 'click' on xul pages.
39 EVENTS_CLICK = ['mousedown', 'mouseup']
40 EVENTS_CLICK_XUL = ['click']
41 EVENTS_CONTEXT = ['contextmenu']
42 EVENTS_HOVER_START = ['mouseover', 'mouseenter', 'mousemove']
43 EVENTS_HOVER_END = ['mouseout', 'mouseleave']
47 # Element classification helpers
49 hasMarkableTextNode = (element) ->
50 return Array.some(element.childNodes, (node) ->
51 # Ignore whitespace-only text nodes, and single-letter ones (which are
52 # common in many syntax highlighters).
53 return node.nodeType == 3 and node.data.trim().length > 1
56 isActivatable = (element) ->
57 return element.localName in ['a', 'button'] or
58 (element.localName == 'input' and element.type in [
59 'button', 'submit', 'reset', 'image'
61 element instanceof XULButtonElement
63 isAdjustable = (element) ->
64 return element.localName == 'input' and element.type in [
65 'checkbox', 'radio', 'file', 'color'
66 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
68 element.localName in ['video', 'audio', 'embed', 'object'] or
69 element instanceof XULControlElement or
70 # Custom video players.
71 includes(element.className, 'video') or
72 includes(element.className, 'player') or
73 # Youtube special case.
74 element.classList?.contains('ytp-button') or
75 # Allow navigating object inspection trees in th devtools with the
76 # arrow keys, even if the arrow keys are used as VimFx shortcuts.
77 isDevtoolsElement(element)
79 isContentEditable = (element) ->
80 return element.isContentEditable or
81 isIframeEditor(element) or
83 element.getAttribute?('g_editable') == 'true' or
84 element.ownerDocument?.body?.getAttribute?('g_editable') == 'true' or
85 # Codeacademy terminals.
86 element.classList?.contains('real-terminal')
88 isDevtoolsElement = (element) ->
89 return false unless element.ownerGlobal
90 return Array.some(element.ownerGlobal.top.frames, isDevtoolsWindow)
92 isDevtoolsWindow = (window) ->
93 return window.location?.href in [
94 'about:devtools-toolbox'
95 'chrome://devtools/content/framework/toolbox.xul'
98 isFocusable = (element) ->
99 # Focusable elements have `.tabIndex > 1` (but not necessarily a
100 # `tabindex="…"` attribute) …
101 return (element.tabIndex > -1 or
102 # … or an explicit `tabindex="-1"` attribute (which means that it is
103 # focusable, but not reachable with `<tab>`).
104 element.getAttribute?('tabindex') == '-1') and
105 not (element.localName?.endsWith?('box') and
106 element.localName != 'checkbox') and
107 not (element.localName == 'toolbarbutton' and
108 element.parentNode?.localName == 'toolbarbutton') and
109 element.localName not in ['tabs', 'menuitem', 'menuseparator']
111 isIframeEditor = (element) ->
112 return false unless element.localName == 'body'
115 element.id == 'innerdocbody' or
117 (element.classList?.contains('xe_content') and
118 element.classList?.contains('editable')) or
120 element.classList?.contains('wysiwyg') or
122 element.classList?.contains('htmlarea-content-body') or
123 # The wasavi extension.
124 element.hasAttribute?('data-wasavi-state')
126 isIgnoreModeFocusType = (element) ->
128 # The wasavi extension.
129 element.hasAttribute?('data-wasavi-state') or
130 element.closest?('#wasavi_container') or
131 # CodeMirror in Vim mode.
132 (element.localName == 'textarea' and
133 element.closest?('.CodeMirror') and _hasVimEventListener(element))
135 # CodeMirror’s Vim mode is really sucky to detect. The only way seems to be to
136 # check if the there are any event listener functions with Vim-y words in them.
137 _hasVimEventListener = (element) ->
138 for listener in nsIEventListenerService.getListenerInfoFor(element)
139 if listener.listenerObject and
140 /\bvim\b|insertmode/i.test(String(listener.listenerObject))
144 isProperLink = (element) ->
145 # `.getAttribute` is used below instead of `.hasAttribute` to exclude `<a
146 # href="">`s used as buttons on some sites.
147 return element.getAttribute?('href') and
148 (element.localName == 'a' or
149 isXULDocument(element.ownerDocument)) and
150 not element.href?.endsWith?('#') and
151 not element.href?.endsWith?('#?') and
152 not element.href?.startsWith?('javascript:')
154 isTextInputElement = (element) ->
155 return (element.localName == 'input' and element.type in [
156 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
158 element.localName == 'textarea' or
159 element instanceof XULTextBoxElement or
160 isContentEditable(element)
162 isTypingElement = (element) ->
163 return isTextInputElement(element) or
164 # `<select>` elements can also receive text input: You may type the
165 # text of an item to select it.
166 element.localName == 'select' or
167 element instanceof XULMenuListElement
171 # Active/focused element helpers
173 blurActiveBrowserElement = (vim) ->
174 # - Blurring in the next tick allows to pass `<escape>` to the location bar to
175 # reset it, for example.
176 # - Focusing the current browser afterwards allows to pass `<escape>` as well
177 # as unbound keys to the page. However, focusing the browser also triggers
178 # focus events on `document` and `window` in the current page. Many pages
179 # re-focus some text input on those events, making it impossible to blur
180 # those! Therefore we tell the frame script to suppress those events.
182 activeElement = getActiveElement(window)
183 activeElement.closest('tabmodalprompt')?.abortPrompt()
184 vim._send('browserRefocus')
187 window.gBrowser.selectedBrowser.focus()
190 blurActiveElement = (window) ->
191 # Blurring a frame element also blurs any active elements inside it. Recursing
192 # into the frames and blurring the “real” active element directly would give
193 # focus to the `<body>` of its containing frame, while blurring the top-most
194 # frame gives focus to the top-most `<body>`. This allows to blur fancy text
195 # editors which use an `<iframe>` as their text area.
196 window.document.activeElement?.blur()
198 # Focus an element and tell Firefox that the focus happened because of a user
199 # action (not just because some random programmatic focus). `.FLAG_BYKEY` might
200 # look more appropriate, but it unconditionally selects all text, which
201 # `.FLAG_BYMOUSE` does not.
202 focusElement = (element, options = {}) ->
203 nsIFocusManager.setFocus(element, options.flag ? 'FLAG_BYMOUSE')
204 element.select?() if options.select
206 # NOTE: In frame scripts, `document.activeElement` may be `null` when the page
207 # is loading. Therefore always check if anything was returned, such as:
209 # return unless activeElement = utils.getActiveElement(window)
210 getActiveElement = (window) ->
211 {activeElement} = window.document
212 return null unless activeElement
213 # If the active element is a frame, recurse into it. The easiest way to detect
214 # a frame that works both in browser UI and in web page content is to check
215 # for the presence of `.contentWindow`. However, in non-multi-process,
216 # `<browser>` (sometimes `<xul:browser>`) elements have a `.contentWindow`
217 # pointing to the web page content `window`, which we don’t want to recurse
218 # into. The problem is that there are _some_ `<browser>`s which we _want_ to
219 # recurse into, such as the sidebar (for instance the history sidebar), and
220 # dialogs in `about:preferences`. Checking the `contextmenu` attribute seems
221 # to be a reliable test, catching both the main tab `<browser>`s and bookmarks
222 # opened in the sidebar.
223 if (activeElement.localName == 'browser' and
224 activeElement.getAttribute?('contextmenu') == 'contentAreaContextMenu') or
225 not activeElement.contentWindow
228 return getActiveElement(activeElement.contentWindow)
230 getFocusType = (element) -> switch
231 when isIgnoreModeFocusType(element)
233 when isTypingElement(element)
234 if element.closest?('findbar') then 'findbar' else 'editable'
235 when isActivatable(element)
237 when isAdjustable(element)
246 listen = (element, eventName, listener, useCapture = true) ->
247 element.addEventListener(eventName, listener, useCapture)
249 element.removeEventListener(eventName, listener, useCapture)
252 listenOnce = (element, eventName, listener, useCapture = true) ->
255 element.removeEventListener(eventName, fn, useCapture)
256 listen(element, eventName, fn, useCapture)
258 onRemoved = (element, fn) ->
259 window = element.ownerGlobal
263 return if disconnected
265 mutationObserver.disconnect() unless Cu.isDeadWrapper(mutationObserver)
267 mutationObserver = new window.MutationObserver((changes) ->
268 for change in changes then for removedElement in change.removedNodes
269 if removedElement.contains?(element)
274 mutationObserver.observe(window.document.documentElement, {
278 module.onShutdown(disconnect)
282 simulateMouseEvents = (element, sequence, browserOffset) ->
283 window = element.ownerGlobal
284 rect = element.getBoundingClientRect()
285 topOffset = getTopOffset(element)
287 eventSequence = switch sequence
301 for type in eventSequence
303 when type in EVENTS_CONTEXT
305 when type in EVENTS_CLICK
310 mouseEvent = new window.MouseEvent(type, {
311 # Let the event bubble in order to trigger delegated event listeners.
312 bubbles: type not in ['mouseenter', 'mouseleave']
313 # Make the event cancelable so that `<a href="#">` can be used as a
314 # JavaScript-powered button without scrolling to the top of the page.
315 cancelable: type not in ['mouseenter', 'mouseleave']
316 # These properties are just here for mimicing a real click as much as
321 # `page{X,Y}` are set automatically to the correct values when setting
322 # `client{X,Y}`. `{offset,layer,movement}{X,Y}` are not worth the trouble
325 clientY: rect.top + rect.height / 2
326 screenX: browserOffset.x + topOffset.x
327 screenY: browserOffset.y + topOffset.y + rect.height / 2
330 if type == 'mousemove'
331 # If the below technique is used for this event, the “URL popup” (shown
332 # when hovering or focusing links) does not appear.
333 element.dispatchEvent(mouseEvent)
335 # The last `true` below marks the event as trusted, which some APIs
336 # require, such as `requestFullscreen()`.
337 # (`element.dispatchEvent(mouseEvent)` is not able to do this.)
339 .QueryInterface(Ci.nsIInterfaceRequestor)
340 .getInterface(Ci.nsIDOMWindowUtils)
341 .dispatchDOMEventViaPresShell(element, mouseEvent, true)
345 suppressEvent = (event) ->
346 event.preventDefault()
347 event.stopPropagation()
354 return element.clientWidth * element.clientHeight
356 checkElementOrAncestor = (element, fn) ->
357 window = element.ownerGlobal
358 while element.parentElement
359 return true if fn(element)
360 element = element.parentElement
363 clearSelectionDeep = (window, {blur = true} = {}) ->
364 # The selection might be `null` in hidden frames.
365 selection = window.getSelection()
366 selection?.removeAllRanges()
367 for frame in window.frames
368 clearSelectionDeep(frame, {blur})
369 # Allow parents to re-gain control of text selection.
370 frame.frameElement.blur() if blur
373 containsDeep = (parent, element) ->
374 parentWindow = parent.ownerGlobal
375 elementWindow = element.ownerGlobal
377 # Owner windows might be missing when opening the devtools.
378 while elementWindow and parentWindow and
379 elementWindow != parentWindow and elementWindow.top != elementWindow
380 element = elementWindow.frameElement
381 elementWindow = element.ownerGlobal
383 return parent.contains(element)
385 createBox = (document, className = '', parent = null, text = null) ->
386 box = document.createElement('box')
387 box.className = "#{className} vimfx-box"
388 box.textContent = text if text?
389 parent.appendChild(box) if parent?
392 # In quirks mode (when the page lacks a doctype), such as on Hackernews,
393 # `<body>` is considered the root element rather than `<html>`.
394 getRootElement = (document) ->
395 if document.compatMode == 'BackCompat' and document.body?
398 return document.documentElement
400 getText = (element) ->
401 text = element.textContent or element.value or element.placeholder or ''
402 return text.trim().replace(/\s+/, ' ')
404 getTopOffset = (element) ->
405 window = element.ownerGlobal
407 {left: x, top: y} = element.getBoundingClientRect()
408 while window.frameElement
409 frame = window.frameElement
410 frameRect = frame.getBoundingClientRect()
414 computedStyle = frame.ownerGlobal.getComputedStyle(frame)
417 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
418 parseFloat(computedStyle.getPropertyValue('padding-left'))
420 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
421 parseFloat(computedStyle.getPropertyValue('padding-top'))
423 window = window.parent
426 injectTemporaryPopup = (document, contents) ->
427 popup = document.createElement('menupopup')
428 popup.appendChild(contents)
429 document.getElementById('mainPopupSet').appendChild(popup)
430 listenOnce(popup, 'popuphidden', popup.remove.bind(popup))
433 insertText = (input, value) ->
434 {selectionStart, selectionEnd} = input
436 input.value[0...selectionStart] + value + input.value[selectionEnd..]
437 input.selectionStart = input.selectionEnd = selectionStart + value.length
439 isDetached = (element) ->
440 return not element.ownerDocument?.documentElement?.contains?(element)
442 isNonEmptyTextNode = (node) ->
443 return node.nodeType == 3 and node.data.trim() != ''
445 querySelectorAllDeep = (window, selector) ->
446 elements = Array.from(window.document.querySelectorAll(selector))
447 for frame in window.frames
448 elements.push(querySelectorAllDeep(frame, selector)...)
451 selectAllSubstringMatches = (element, substring, {caseSensitive = true} = {}) ->
452 window = element.ownerGlobal
453 selection = window.getSelection()
454 {textContent} = element
456 format = (string) -> if caseSensitive then string else string.toLowerCase()
458 getAllNonOverlappingRangeOffsets(format(textContent), format(substring))
459 offsetsLength = offsets.length
460 return if offsetsLength == 0
464 [currentOffset] = offsets
465 searchIndex = currentOffset.start
468 walkTextNodes(element, (textNode) ->
469 {length} = textNode.data
470 return false if length == 0
472 while textIndex + length > searchIndex
474 range = window.document.createRange()
475 range.setStart(start.textNode, start.offset)
476 range.setEnd(textNode, currentOffset.end - textIndex)
477 selection.addRange(range)
480 return true if offsetsIndex >= offsetsLength
481 currentOffset = offsets[offsetsIndex]
484 searchIndex = currentOffset.start
487 start = {textNode, offset: currentOffset.start - textIndex}
488 searchIndex = currentOffset.end - 1
494 selectElement = (element) ->
495 window = element.ownerGlobal
496 selection = window.getSelection()
497 range = window.document.createRange()
498 range.selectNodeContents(element)
499 selection.addRange(range)
501 setAttributes = (element, attributes) ->
502 for attribute, value of attributes
503 element.setAttribute(attribute, value)
506 setHover = (element, hover) ->
507 return unless nsIDomUtils
509 method = if hover then 'addPseudoClassLock' else 'removePseudoClassLock'
510 while element.parentElement
511 nsIDomUtils[method](element, ':hover')
512 element = element.parentElement
515 walkTextNodes = (element, fn) ->
516 for node in element.childNodes then switch node.nodeType
521 stop = walkTextNodes(node, fn)
530 constructor: ({start: @value = 0, @step = 1}) ->
531 tick: -> @value += @step
537 on: (event, listener) ->
538 (@listeners[event] ?= new Set()).add(listener)
540 off: (event, listener) ->
541 @listeners[event]?.delete(listener)
543 emit: (event, data) ->
544 @listeners[event]?.forEach((listener) ->
548 # Returns `[nonMatch, adjacentMatchAfter]`, where `adjacentMatchAfter - nonMatch
549 # == 1`. `fn(n)` is supposed to return `false` for `n <= nonMatch` and `true`
550 # for `n >= adjacentMatchAfter`. Both `nonMatch` and `adjacentMatchAfter` may be
551 # `null` if they cannot be found. Otherwise they’re in the range `min <= n <=
552 # max`. `[null, null]` is returned in non-sensical cases. This function is
553 # intended to be used as a faster alternative to something like this:
555 # adjacentMatchAfter = null
556 # for n in [min..max]
558 # adjacentMatchAfter = n
560 bisect = (min, max, fn) ->
561 return [null, null] unless max - min >= 0 and min % 1 == 0 and max % 1 == 0
564 mid = min + (max - min) // 2
575 when matchMin and matchMax
577 when not matchMin and not matchMax
579 when not matchMin and matchMax
584 getAllNonOverlappingRangeOffsets = (string, substring) ->
586 return [] if length == 0
589 lastOffset = {start: -Infinity, end: -Infinity}
593 index = string.indexOf(substring, index + 1)
595 if index > lastOffset.end
596 lastOffset = {start: index, end: index + length}
597 offsets.push(lastOffset)
599 lastOffset.end = index + length
603 has = (obj, prop) -> Object::hasOwnProperty.call(obj, prop)
605 # Check if `search` exists in `string` (case insensitively). Returns `false` if
606 # `string` doesn’t exist or isn’t a string, such as `<SVG element>.className`.
607 includes = (string, search) ->
608 return false unless typeof string == 'string'
609 return string.toLowerCase().includes(search)
611 # Calls `fn` repeatedly, with at least `interval` ms between each call.
612 interval = (window, interval, fn) ->
614 currentIntervalId = null
617 currentIntervalId = window.setTimeout((-> fn(next)), interval)
620 window.clearTimeout(currentIntervalId)
624 nextTick = (window, fn) -> window.setTimeout((-> fn()) , 0)
626 overlaps = (rectA, rectB) ->
628 Math.round(rectA.right) >= Math.round(rectB.left) and
629 Math.round(rectA.left) <= Math.round(rectB.right) and
630 Math.round(rectA.bottom) >= Math.round(rectB.top) and
631 Math.round(rectA.top) <= Math.round(rectB.bottom)
633 partition = (array, fn) ->
636 for item, index in array
637 if fn(item, index, array)
640 nonMatching.push(item)
641 return [matching, nonMatching]
643 regexEscape = (s) -> s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
645 removeDuplicateChars = (string) -> removeDuplicates(string.split('')).join('')
647 removeDuplicates = (array) -> Array.from(new Set(array))
649 sum = (numbers) -> numbers.reduce(((sum, number) -> sum + number), 0)
655 expandPath = (path) ->
656 if path.startsWith('~/') or path.startsWith('~\\')
657 return OS.Constants.Path.homeDir + path[1..]
661 getCurrentLocation = ->
662 return unless window = getCurrentWindow()
663 return new window.URL(window.gBrowser.selectedBrowser.currentURI.spec)
665 # This function might return `null` on startup.
666 getCurrentWindow = -> nsIWindowMediator.getMostRecentWindow('navigator:browser')
668 hasEventListeners = (element, type) ->
669 for listener in nsIEventListenerService.getListenerInfoFor(element)
670 if listener.listenerObject and listener.type == type
674 loadCss = (uriString) ->
675 uri = Services.io.newURI(uriString, null, null)
676 method = nsIStyleSheetService.AUTHOR_SHEET
677 unless nsIStyleSheetService.sheetRegistered(uri, method)
678 nsIStyleSheetService.loadAndRegisterSheet(uri, method)
680 nsIStyleSheetService.unregisterSheet(uri, method)
683 observe = (topic, observer) ->
684 observer = {observe: observer} if typeof observer == 'function'
685 Services.obs.addObserver(observer, topic, false)
687 Services.obs.removeObserver(observer, topic, false)
690 # Try to open a button’s dropdown menu, if any.
691 openDropdown = (element) ->
692 if isXULDocument(element.ownerDocument) and
693 element.getAttribute?('type') == 'menu' and
694 element.open == false # Only change `.open` if it is already a boolean.
697 openPopup = (popup) ->
698 window = popup.ownerGlobal
699 # Show the popup so it gets a height and width.
700 popup.openPopupAtScreen(0, 0)
701 # Center the popup inside the window.
703 window.screenX + window.outerWidth / 2 - popup.clientWidth / 2,
704 window.screenY + window.outerHeight / 2 - popup.clientHeight / 2
707 writeToClipboard = (text) -> nsIClipboardHelper.copyString(text)
720 isIgnoreModeFocusType
725 blurActiveBrowserElement
738 checkElementOrAncestor
750 selectAllSubstringMatches
759 getAllNonOverlappingRangeOffsets