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 nsIDomUtils = Cc['@mozilla.org/inspector/dom-utils;1']
8 .getService(Ci.inIDOMUtils)
9 nsIEventListenerService = Cc['@mozilla.org/eventlistenerservice;1']
10 .getService(Ci.nsIEventListenerService)
11 nsIFocusManager = Cc['@mozilla.org/focus-manager;1']
12 .getService(Ci.nsIFocusManager)
13 nsIStyleSheetService = Cc['@mozilla.org/content/style-sheet-service;1']
14 .getService(Ci.nsIStyleSheetService)
15 nsIWindowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
16 .getService(Ci.nsIWindowMediator)
18 # For XUL, `instanceof` checks are often better than `.localName` checks,
19 # because some of the below interfaces are extended by many elements.
20 XULDocument = Ci.nsIDOMXULDocument
21 XULButtonElement = Ci.nsIDOMXULButtonElement
22 XULControlElement = Ci.nsIDOMXULControlElement
23 XULMenuListElement = Ci.nsIDOMXULMenuListElement
24 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
26 # Full chains of events for different mouse actions. Note: 'click' is fired
27 # by Firefox automatically after 'mousedown' and 'mouseup'. Similarly,
28 # 'command' is fired automatically after 'click' on xul pages.
29 EVENTS_CLICK = ['mousedown', 'mouseup']
30 EVENTS_CLICK_XUL = ['click']
31 EVENTS_CONTEXT = ['contextmenu']
32 EVENTS_HOVER_START = ['mouseover', 'mouseenter', 'mousemove']
33 EVENTS_HOVER_END = ['mouseout', 'mouseleave']
37 # Element classification helpers
39 hasMarkableTextNode = (element) ->
40 return Array.some(element.childNodes, (node) ->
41 # Ignore whitespace-only text nodes, and single-letter ones (which are
42 # common in many syntax highlighters).
43 return node.nodeType == 3 and node.data.trim().length > 1
46 isActivatable = (element) ->
47 return element.localName in ['a', 'button'] or
48 (element.localName == 'input' and element.type in [
49 'button', 'submit', 'reset', 'image'
51 element instanceof XULButtonElement
53 isAdjustable = (element) ->
54 return element.localName == 'input' and element.type in [
55 'checkbox', 'radio', 'file', 'color'
56 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
58 element.localName in ['video', 'audio', 'embed', 'object'] or
59 element instanceof XULControlElement or
60 # Custom video players.
61 includes(element.className, 'video') or
62 includes(element.className, 'player') or
63 # Youtube special case.
64 element.classList?.contains('ytp-button') or
65 # Allow navigating object inspection trees in th devtools with the
66 # arrow keys, even if the arrow keys are used as VimFx shortcuts.
67 isDevtoolsElement(element)
69 isContentEditable = (element) ->
70 return element.isContentEditable or
71 isIframeEditor(element) or
73 element.getAttribute?('g_editable') == 'true' or
74 element.ownerDocument?.body?.getAttribute?('g_editable') == 'true' or
75 # Codeacademy terminals.
76 element.classList?.contains('real-terminal')
78 isDevtoolsElement = (element) ->
79 return false unless element.ownerGlobal
80 return Array.some(element.ownerGlobal.top.frames, isDevtoolsWindow)
82 isDevtoolsWindow = (window) ->
83 return window.location?.href in [
84 'about:devtools-toolbox'
85 'chrome://devtools/content/framework/toolbox.xul'
88 isFocusable = (element) ->
89 # Focusable elements have `.tabIndex > 1` (but not necessarily a
90 # `tabindex="…"` attribute) …
91 return (element.tabIndex > -1 or
92 # … or an explicit `tabindex="-1"` attribute (which means that it is
93 # focusable, but not reachable with `<tab>`).
94 element.getAttribute?('tabindex') == '-1') and
95 not (element.localName?.endsWith?('box') and
96 element.localName != 'checkbox') and
97 not (element.localName == 'toolbarbutton' and
98 element.parentNode?.localName == 'toolbarbutton') and
99 element.localName not in ['tabs', 'menuitem', 'menuseparator']
101 isIframeEditor = (element) ->
102 return false unless element.localName == 'body'
105 element.id == 'innerdocbody' or
107 (element.classList?.contains('xe_content') and
108 element.classList?.contains('editable')) or
110 element.classList?.contains('wysiwyg') or
112 element.classList?.contains('htmlarea-content-body') or
113 # The wasavi extension.
114 element.hasAttribute?('data-wasavi-state')
116 isIgnoreModeFocusType = (element) ->
118 # The wasavi extension.
119 element.hasAttribute?('data-wasavi-state') or
120 element.closest?('#wasavi_container') or
121 # CodeMirror in Vim mode.
122 (element.localName == 'textarea' and
123 element.closest?('.CodeMirror') and _hasVimEventListener(element))
125 # CodeMirror’s Vim mode is really sucky to detect. The only way seems to be to
126 # check if the there are any event listener functions with Vim-y words in them.
127 _hasVimEventListener = (element) ->
128 for listener in nsIEventListenerService.getListenerInfoFor(element)
129 if listener.listenerObject and
130 /\bvim\b|insertmode/i.test(String(listener.listenerObject))
134 isProperLink = (element) ->
135 # `.getAttribute` is used below instead of `.hasAttribute` to exclude `<a
136 # href="">`s used as buttons on some sites.
137 return element.getAttribute?('href') and
138 (element.localName == 'a' or
139 element.ownerDocument instanceof XULDocument) and
140 not element.href?.endsWith?('#') and
141 not element.href?.endsWith?('#?') and
142 not element.href?.startsWith?('javascript:')
144 isTextInputElement = (element) ->
145 return (element.localName == 'input' and element.type in [
146 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
148 element.localName == 'textarea' or
149 element instanceof XULTextBoxElement or
150 isContentEditable(element)
152 isTypingElement = (element) ->
153 return isTextInputElement(element) or
154 # `<select>` elements can also receive text input: You may type the
155 # text of an item to select it.
156 element.localName == 'select' or
157 element instanceof XULMenuListElement
161 # Active/focused element helpers
163 blurActiveBrowserElement = (vim) ->
164 # - Blurring in the next tick allows to pass `<escape>` to the location bar to
165 # reset it, for example.
166 # - Focusing the current browser afterwards allows to pass `<escape>` as well
167 # as unbound keys to the page. However, focusing the browser also triggers
168 # focus events on `document` and `window` in the current page. Many pages
169 # re-focus some text input on those events, making it impossible to blur
170 # those! Therefore we tell the frame script to suppress those events.
172 activeElement = getActiveElement(window)
173 activeElement.closest('tabmodalprompt')?.abortPrompt()
174 vim._send('browserRefocus')
177 window.gBrowser.selectedBrowser.focus()
180 blurActiveElement = (window) ->
181 # Blurring a frame element also blurs any active elements inside it. Recursing
182 # into the frames and blurring the “real” active element directly would give
183 # focus to the `<body>` of its containing frame, while blurring the top-most
184 # frame gives focus to the top-most `<body>`. This allows to blur fancy text
185 # editors which use an `<iframe>` as their text area.
186 window.document.activeElement?.blur()
188 # Focus an element and tell Firefox that the focus happened because of a user
189 # action (not just because some random programmatic focus). `.FLAG_BYKEY` might
190 # look more appropriate, but it unconditionally selects all text, which
191 # `.FLAG_BYMOUSE` does not.
192 focusElement = (element, options = {}) ->
193 nsIFocusManager.setFocus(element, options.flag ? 'FLAG_BYMOUSE')
194 element.select?() if options.select
196 # NOTE: In frame scripts, `document.activeElement` may be `null` when the page
197 # is loading. Therefore always check if anything was returned, such as:
199 # return unless activeElement = utils.getActiveElement(window)
200 getActiveElement = (window) ->
201 {activeElement} = window.document
202 return null unless activeElement
203 # If the active element is a frame, recurse into it. The easiest way to detect
204 # a frame that works both in browser UI and in web page content is to check
205 # for the presence of `.contentWindow`. However, in non-multi-process,
206 # `<browser>` (sometimes `<xul:browser>`) elements have a `.contentWindow`
207 # pointing to the web page content `window`, which we don’t want to recurse
208 # into. The problem is that there are _some_ `<browser>`s which we _want_ to
209 # recurse into, such as the sidebar (for instance the history sidebar), and
210 # dialogs in `about:preferences`. Checking the `contextmenu` attribute seems
211 # to be a reliable test, catching both the main tab `<browser>`s and bookmarks
212 # opened in the sidebar.
213 if (activeElement.localName == 'browser' and
214 activeElement.getAttribute?('contextmenu') == 'contentAreaContextMenu') or
215 not activeElement.contentWindow
218 return getActiveElement(activeElement.contentWindow)
220 getFocusType = (element) -> switch
221 when isIgnoreModeFocusType(element)
223 when isTypingElement(element)
224 if element.closest?('findbar') then 'findbar' else 'editable'
225 when isActivatable(element)
227 when isAdjustable(element)
236 listen = (element, eventName, listener, useCapture = true) ->
237 element.addEventListener(eventName, listener, useCapture)
239 element.removeEventListener(eventName, listener, useCapture)
242 listenOnce = (element, eventName, listener, useCapture = true) ->
245 element.removeEventListener(eventName, fn, useCapture)
246 listen(element, eventName, fn, useCapture)
248 onRemoved = (element, fn) ->
249 window = element.ownerGlobal
253 return if disconnected
255 mutationObserver.disconnect() unless Cu.isDeadWrapper(mutationObserver)
257 mutationObserver = new window.MutationObserver((changes) ->
258 for change in changes then for removedElement in change.removedNodes
259 if removedElement.contains?(element)
264 mutationObserver.observe(window.document.documentElement, {
268 module.onShutdown(disconnect)
272 simulateMouseEvents = (element, sequence, browserOffset) ->
273 window = element.ownerGlobal
274 rect = element.getBoundingClientRect()
275 topOffset = getTopOffset(element)
277 eventSequence = switch sequence
291 for type in eventSequence
293 when type in EVENTS_CONTEXT
295 when type in EVENTS_CLICK
300 mouseEvent = new window.MouseEvent(type, {
301 # Let the event bubble in order to trigger delegated event listeners.
302 bubbles: type not in ['mouseenter', 'mouseleave']
303 # Make the event cancelable so that `<a href="#">` can be used as a
304 # JavaScript-powered button without scrolling to the top of the page.
305 cancelable: type not in ['mouseenter', 'mouseleave']
306 # These properties are just here for mimicing a real click as much as
311 # `page{X,Y}` are set automatically to the correct values when setting
312 # `client{X,Y}`. `{offset,layer,movement}{X,Y}` are not worth the trouble
315 clientY: rect.top + rect.height / 2
316 screenX: browserOffset.x + topOffset.x
317 screenY: browserOffset.y + topOffset.y + rect.height / 2
320 if type == 'mousemove'
321 # If the below technique is used for this event, the “URL popup” (shown
322 # when hovering or focusing links) does not appear.
323 element.dispatchEvent(mouseEvent)
325 # The last `true` below marks the event as trusted, which some APIs
326 # require, such as `requestFullscreen()`.
327 # (`element.dispatchEvent(mouseEvent)` is not able to do this.)
329 .QueryInterface(Ci.nsIInterfaceRequestor)
330 .getInterface(Ci.nsIDOMWindowUtils)
331 .dispatchDOMEventViaPresShell(element, mouseEvent, true)
335 suppressEvent = (event) ->
336 event.preventDefault()
337 event.stopPropagation()
344 return element.clientWidth * element.clientHeight
346 checkElementOrAncestor = (element, fn) ->
347 window = element.ownerGlobal
348 while element.parentElement
349 return true if fn(element)
350 element = element.parentElement
353 clearSelectionDeep = (window, {blur = true} = {}) ->
354 # The selection might be `null` in hidden frames.
355 selection = window.getSelection()
356 selection?.removeAllRanges()
357 for frame in window.frames
358 clearSelectionDeep(frame, {blur})
359 # Allow parents to re-gain control of text selection.
360 frame.frameElement.blur() if blur
363 containsDeep = (parent, element) ->
364 parentWindow = parent.ownerGlobal
365 elementWindow = element.ownerGlobal
367 # Owner windows might be missing when opening the devtools.
368 while elementWindow and parentWindow and
369 elementWindow != parentWindow and elementWindow.top != elementWindow
370 element = elementWindow.frameElement
371 elementWindow = element.ownerGlobal
373 return parent.contains(element)
375 createBox = (document, className = '', parent = null, text = null) ->
376 box = document.createElement('box')
377 box.className = "#{className} vimfx-box"
378 box.textContent = text if text?
379 parent.appendChild(box) if parent?
382 # In quirks mode (when the page lacks a doctype), such as on Hackernews,
383 # `<body>` is considered the root element rather than `<html>`.
384 getRootElement = (document) ->
385 if document.compatMode == 'BackCompat' and document.body?
388 return document.documentElement
390 getText = (element) ->
391 text = element.textContent or element.value or element.placeholder or ''
392 return text.trim().replace(/\s+/, ' ')
394 getTopOffset = (element) ->
395 window = element.ownerGlobal
397 {left: x, top: y} = element.getBoundingClientRect()
398 while window.frameElement
399 frame = window.frameElement
400 frameRect = frame.getBoundingClientRect()
404 computedStyle = frame.ownerGlobal.getComputedStyle(frame)
407 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
408 parseFloat(computedStyle.getPropertyValue('padding-left'))
410 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
411 parseFloat(computedStyle.getPropertyValue('padding-top'))
413 window = window.parent
416 injectTemporaryPopup = (document, contents) ->
417 popup = document.createElement('menupopup')
418 popup.appendChild(contents)
419 document.getElementById('mainPopupSet').appendChild(popup)
420 listenOnce(popup, 'popuphidden', popup.remove.bind(popup))
423 insertText = (input, value) ->
424 {selectionStart, selectionEnd} = input
426 input.value[0...selectionStart] + value + input.value[selectionEnd..]
427 input.selectionStart = input.selectionEnd = selectionStart + value.length
429 isDetached = (element) ->
430 return not element.ownerDocument?.documentElement?.contains?(element)
432 isNonEmptyTextNode = (node) ->
433 return node.nodeType == 3 and node.data.trim() != ''
435 querySelectorAllDeep = (window, selector) ->
436 elements = Array.from(window.document.querySelectorAll(selector))
437 for frame in window.frames
438 elements.push(querySelectorAllDeep(frame, selector)...)
441 selectAllSubstringMatches = (element, substring, {caseSensitive = true} = {}) ->
442 window = element.ownerGlobal
443 selection = window.getSelection()
444 {textContent} = element
446 format = (string) -> if caseSensitive then string else string.toLowerCase()
448 getAllNonOverlappingRangeOffsets(format(textContent), format(substring))
449 offsetsLength = offsets.length
450 return if offsetsLength == 0
454 [currentOffset] = offsets
455 searchIndex = currentOffset.start
458 walkTextNodes(element, (textNode) ->
459 {length} = textNode.data
460 return false if length == 0
462 while textIndex + length > searchIndex
464 range = window.document.createRange()
465 range.setStart(start.textNode, start.offset)
466 range.setEnd(textNode, currentOffset.end - textIndex)
467 selection.addRange(range)
470 return true if offsetsIndex >= offsetsLength
471 currentOffset = offsets[offsetsIndex]
474 searchIndex = currentOffset.start
477 start = {textNode, offset: currentOffset.start - textIndex}
478 searchIndex = currentOffset.end - 1
484 selectElement = (element) ->
485 window = element.ownerGlobal
486 selection = window.getSelection()
487 range = window.document.createRange()
488 range.selectNodeContents(element)
489 selection.addRange(range)
491 setAttributes = (element, attributes) ->
492 for attribute, value of attributes
493 element.setAttribute(attribute, value)
496 setHover = (element, hover) ->
497 method = if hover then 'addPseudoClassLock' else 'removePseudoClassLock'
498 while element.parentElement
499 nsIDomUtils[method](element, ':hover')
500 element = element.parentElement
503 walkTextNodes = (element, fn) ->
504 for node in element.childNodes then switch node.nodeType
509 stop = walkTextNodes(node, fn)
518 constructor: ({start: @value = 0, @step = 1}) ->
519 tick: -> @value += @step
525 on: (event, listener) ->
526 (@listeners[event] ?= new Set()).add(listener)
528 off: (event, listener) ->
529 @listeners[event]?.delete(listener)
531 emit: (event, data) ->
532 @listeners[event]?.forEach((listener) ->
536 # Returns `[nonMatch, adjacentMatchAfter]`, where `adjacentMatchAfter - nonMatch
537 # == 1`. `fn(n)` is supposed to return `false` for `n <= nonMatch` and `true`
538 # for `n >= adjacentMatchAfter`. Both `nonMatch` and `adjacentMatchAfter` may be
539 # `null` if they cannot be found. Otherwise they’re in the range `min <= n <=
540 # max`. `[null, null]` is returned in non-sensical cases. This function is
541 # intended to be used as a faster alternative to something like this:
543 # adjacentMatchAfter = null
544 # for n in [min..max]
546 # adjacentMatchAfter = n
548 bisect = (min, max, fn) ->
549 return [null, null] unless max - min >= 0 and min % 1 == 0 and max % 1 == 0
552 mid = min + (max - min) // 2
563 when matchMin and matchMax
565 when not matchMin and not matchMax
567 when not matchMin and matchMax
572 getAllNonOverlappingRangeOffsets = (string, substring) ->
574 return [] if length == 0
577 lastOffset = {start: -Infinity, end: -Infinity}
581 index = string.indexOf(substring, index + 1)
583 if index > lastOffset.end
584 lastOffset = {start: index, end: index + length}
585 offsets.push(lastOffset)
587 lastOffset.end = index + length
591 has = (obj, prop) -> Object::hasOwnProperty.call(obj, prop)
593 # Check if `search` exists in `string` (case insensitively). Returns `false` if
594 # `string` doesn’t exist or isn’t a string, such as `<SVG element>.className`.
595 includes = (string, search) ->
596 return false unless typeof string == 'string'
597 return string.toLowerCase().includes(search)
599 # Calls `fn` repeatedly, with at least `interval` ms between each call.
600 interval = (window, interval, fn) ->
602 currentIntervalId = null
605 currentIntervalId = window.setTimeout((-> fn(next)), interval)
608 window.clearTimeout(currentIntervalId)
612 nextTick = (window, fn) -> window.setTimeout((-> fn()) , 0)
614 overlaps = (rectA, rectB) ->
616 Math.round(rectA.right) >= Math.round(rectB.left) and
617 Math.round(rectA.left) <= Math.round(rectB.right) and
618 Math.round(rectA.bottom) >= Math.round(rectB.top) and
619 Math.round(rectA.top) <= Math.round(rectB.bottom)
621 partition = (array, fn) ->
624 for item, index in array
625 if fn(item, index, array)
628 nonMatching.push(item)
629 return [matching, nonMatching]
631 regexEscape = (s) -> s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
633 removeDuplicateChars = (string) -> removeDuplicates(string.split('')).join('')
635 removeDuplicates = (array) -> Array.from(new Set(array))
637 sum = (numbers) -> numbers.reduce(((sum, number) -> sum + number), 0)
643 expandPath = (path) ->
644 if path.startsWith('~/') or path.startsWith('~\\')
645 return OS.Constants.Path.homeDir + path[1..]
649 getCurrentLocation = ->
650 return unless window = getCurrentWindow()
651 return new window.URL(window.gBrowser.selectedBrowser.currentURI.spec)
653 # This function might return `null` on startup.
654 getCurrentWindow = -> nsIWindowMediator.getMostRecentWindow('navigator:browser')
656 hasEventListeners = (element, type) ->
657 for listener in nsIEventListenerService.getListenerInfoFor(element)
658 if listener.listenerObject and listener.type == type
662 loadCss = (uriString) ->
663 uri = Services.io.newURI(uriString, null, null)
664 method = nsIStyleSheetService.AUTHOR_SHEET
665 unless nsIStyleSheetService.sheetRegistered(uri, method)
666 nsIStyleSheetService.loadAndRegisterSheet(uri, method)
668 nsIStyleSheetService.unregisterSheet(uri, method)
671 observe = (topic, observer) ->
672 observer = {observe: observer} if typeof observer == 'function'
673 Services.obs.addObserver(observer, topic, false)
675 Services.obs.removeObserver(observer, topic, false)
678 # Try to open a button’s dropdown menu, if any.
679 openDropdown = (element) ->
680 if element.ownerDocument instanceof XULDocument and
681 element.getAttribute?('type') == 'menu' and
682 element.open == false # Only change `.open` if it is already a boolean.
685 openPopup = (popup) ->
686 window = popup.ownerGlobal
687 # Show the popup so it gets a height and width.
688 popup.openPopupAtScreen(0, 0)
689 # Center the popup inside the window.
691 window.screenX + window.outerWidth / 2 - popup.clientWidth / 2,
692 window.screenY + window.outerHeight / 2 - popup.clientHeight / 2
695 writeToClipboard = (text) -> nsIClipboardHelper.copyString(text)
708 isIgnoreModeFocusType
713 blurActiveBrowserElement
726 checkElementOrAncestor
738 selectAllSubstringMatches
747 getAllNonOverlappingRangeOffsets