Bug 1461522 - Add focus() and focusEnd() methods to HTMLTooltip; r=jdescottes
authorBrian Birtles <birtles@gmail.com>
Thu, 28 Jun 2018 15:10:42 +0900
changeset 814151 c4f83d8e4596b759c26072ee7959d90650b3ee50
parent 814150 dd9b63632e1982b37fcd4eff8cee95df9e064001
child 814152 28e68f45879e0c9b4ad061d043d4b4f241572d60
push id115123
push userjdescottes@mozilla.com
push dateWed, 04 Jul 2018 17:42:29 +0000
reviewersjdescottes
bugs1461522
milestone63.0a1
Bug 1461522 - Add focus() and focusEnd() methods to HTMLTooltip; r=jdescottes We will use these methods later when we put menu content inside HTMLTooltip in order to set the initial focus. MozReview-Commit-ID: HR02wg543gP
devtools/client/shared/widgets/tooltip/HTMLTooltip.js
--- a/devtools/client/shared/widgets/tooltip/HTMLTooltip.js
+++ b/devtools/client/shared/widgets/tooltip/HTMLTooltip.js
@@ -542,17 +542,19 @@ HTMLTooltip.prototype = {
 
     this.container.classList.add("tooltip-visible");
 
     // Keep a pointer on the focused element to refocus it when hiding the tooltip.
     this._focusedElement = this.doc.activeElement;
 
     this.doc.defaultView.clearTimeout(this.attachEventsTimer);
     this.attachEventsTimer = this.doc.defaultView.setTimeout(() => {
-      this._maybeFocusTooltip();
+      if (this.autofocus) {
+        this.focus();
+      }
       // Update the top window reference each time in case the host changes.
       this.topWindow = this._getTopWindow();
       this.topWindow.addEventListener("click", this._onClick, true);
       this.emit("shown");
     }, 0);
   },
 
   /**
@@ -755,24 +757,39 @@ HTMLTooltip.prototype = {
 
   _onXulPanelHidden: function() {
     if (this.isVisible()) {
       this.hide();
     }
   },
 
   /**
-   * If the tooltip is configured to autofocus and a focusable element can be
-   * found, focus it.
+   * Focus on the first focusable item in the tooltip.
+   *
+   * Returns true if we found something to focus on, false otherwise.
    */
-  _maybeFocusTooltip: function() {
+  focus: function() {
     const focusableElement = this.panel.querySelector(focusableSelector);
-    if (this.autofocus && focusableElement) {
+    if (focusableElement) {
       focusableElement.focus();
     }
+    return !!focusableElement;
+  },
+
+  /**
+   * Focus on the last focusable item in the tooltip.
+   *
+   * Returns true if we found something to focus on, false otherwise.
+   */
+  focusEnd: function() {
+    const focusableElements = this.panel.querySelectorAll(focusableSelector);
+    if (focusableElements.length) {
+      focusableElements[focusableElements.length - 1].focus();
+    }
+    return focusableElements.length !== 0;
   },
 
   _getTopWindow: function() {
     return this.doc.defaultView.top;
   },
 
   /**
    * Check if the tooltip's owner document is a XUL document.