Bug 1461522 - Add focus() and focusEnd() methods to HTMLTooltip; r?jdescottes draft
authorBrian Birtles <birtles@gmail.com>
Thu, 28 Jun 2018 15:10:42 +0900
changeset 813900 09e2cec1dac879fcf503cbc799bdc5f5f794b65e
parent 813899 04040a4a430c590cfe90525c894abe685428ed9c
child 813901 b12188aa6424b28932fd16f2d06b0984e711fe96
push id115042
push userbbirtles@mozilla.com
push dateWed, 04 Jul 2018 04:36:27 +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.