Bug 1477673: Refactor PanelMultiView keyboard navigation to use a TreeWalker. r=Gijs,johannh
☠☠ backed out by a8e6fd651ef2 ☠ ☠
authorJames Teh <jteh@mozilla.com>
Tue, 09 Apr 2019 09:54:39 +0000
changeset 468507 69db665d8263b26b401fdfad83b235feba1592d7
parent 468506 878f78400ed7123ddfc8b431c9dfc6225dfcbc1b
child 468508 eca8a6e641c0248dc064050b2767d87aa9f1b4c6
push id82636
push userjteh@mozilla.com
push dateTue, 09 Apr 2019 09:56:22 +0000
treeherderautoland@eca8a6e641c0 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersGijs, johannh
bugs1477673, 1522092, 1489874, 1539976, 1539984
milestone68.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1477673: Refactor PanelMultiView keyboard navigation to use a TreeWalker. r=Gijs,johannh Previously, this code cached a list of controls on first use and used that for navigation. This refactor addresses several issues: 1. There is now a separate focus order for tab/shift+tab and down/up arrows. This allows menulists, textboxes, etc. which use the arrow keys themselves to be focused with tab, but skipped with the arrows. This means the user won't fall into these controls when using the up/down arrow keys and be confused by the subsequent arrowing behaviour. 2. When a menulist, textbox, etc. is focused, the arrow keys, space and enter are now passed to the control. This is a better fix for handling of the arrow keys by menulists (bug 1522092). It also fixes left arrow in a textarea moving to the previous view instead of moving the caret (bug 1489874). 3. This improves handling of dynamic updates to the panel. For example, elements that are initially disabled and enabled later will be navigable. This is because the next element is determined dynamically by the TreeWalker, rather than using a cached list. 4. The interim fix for bug 1522092 disabled PanelMultiView keyboard navigation. This caused some regressions, including arrow keys/activation on the Site Identity Report a Problem link (bug 1539976) and some controls not being navigable if the Site Identity panel is opened using the mouse (bug 1539984). With the above fixes, we can now re-enable PanelMultiView keyboard navigation in the Site identity panel and thus fix these regressions. 5. Previously, PanelMultiView keyboard navigation was disabled in the main toolbar overflow menu. This is because the search box can be added to the overflow menu, which previously caused problems for the arrow keys. With the above fixes, we can now safely enable PanelMultiView keyboard navigation in the overflow menu. 6. PanelMultiView keyboard tests have been added. Previously, we relied on tests specific to various panels to exercise this functionality. Differential Revision: https://phabricator.services.mozilla.com/D25905
browser/components/controlcenter/content/panel.inc.xul
browser/components/customizableui/PanelMultiView.jsm
browser/components/customizableui/content/panelUI.inc.xul
browser/components/customizableui/test/browser.ini
browser/components/customizableui/test/browser_PanelMultiView_keyboard.js
--- a/browser/components/controlcenter/content/panel.inc.xul
+++ b/browser/components/controlcenter/content/panel.inc.xul
@@ -8,18 +8,17 @@
        photon="true"
        role="alertdialog"
        aria-labelledby="identity-popup-mainView-panel-header-span"
        onpopupshown="gIdentityHandler.onPopupShown(event);"
        onpopuphidden="gIdentityHandler.onPopupHidden(event);"
        orient="vertical">
 
   <panelmultiview id="identity-popup-multiView"
-                  mainViewId="identity-popup-mainView"
-                  disablekeynav="true">
+                  mainViewId="identity-popup-mainView">
     <panelview id="identity-popup-mainView"
                descriptionheightworkaround="true">
       <vbox id="identity-popup-mainView-panel-header">
         <label>
           <html:span id="identity-popup-mainView-panel-header-span"/>
         </label>
       </vbox>
 
--- a/browser/components/customizableui/PanelMultiView.jsm
+++ b/browser/components/customizableui/PanelMultiView.jsm
@@ -1395,130 +1395,146 @@ var PanelView = class extends Associated
     // Now we can make all the necessary DOM changes at once.
     for (let { element, bounds } of items) {
       gMultiLineElementsMap.set(element, { bounds, textContent: element.textContent });
       element.style.height = bounds.height + "px";
     }
   }
 
   /**
-   * Array of enabled elements that can be selected with the keyboard. This
-   * means all buttons, menulists, and text links including the back button.
-   *
-   * This list is cached until the view is closed, so elements that become
-   * enabled later may not be navigable.
+   * Determine whether an element can only be navigated to with tab/shift+tab,
+   * not the arrow keys.
    */
-  get _navigableElements() {
-    if (this.__navigableElements) {
-      return this.__navigableElements;
-    }
+  _isNavigableWithTabOnly(element) {
+    let tag = element.localName;
+    return tag == "menulist" || tag == "textbox" || tag == "input"
+           || tag == "textarea";
+  }
 
-    let navigableElements = Array.from(this.node.querySelectorAll(
-      ":-moz-any(button,toolbarbutton,menulist,.text-link,.navigable):not([disabled])"));
-    return this.__navigableElements = navigableElements.filter(element => {
-      // Set the "tabindex" attribute to make sure the element is focusable.
-      if (!element.hasAttribute("tabindex")) {
-        element.setAttribute("tabindex", "0");
+  /**
+   * Make a TreeWalker for keyboard navigation.
+   *
+   * @param {Boolean} arrowKey If `true`, elements only navigable with tab are
+   *        excluded.
+   */
+  _makeNavigableTreeWalker(arrowKey) {
+    let filter = node => {
+      if (node.disabled) {
+        return NodeFilter.FILTER_REJECT;
+      }
+      let bounds = this._getBoundsWithoutFlushing(node);
+      if (bounds.width == 0 || bounds.height == 0) {
+        return NodeFilter.FILTER_REJECT;
+      }
+      if (node.tagName == "button" || node.tagName == "toolbarbutton" ||
+          node.classList.contains("text-link") ||
+          node.classList.contains("navigable") ||
+          (!arrowKey && this._isNavigableWithTabOnly(node))) {
+        // Set the tabindex attribute to make sure the node is focusable.
+        if (!node.hasAttribute("tabindex")) {
+          node.setAttribute("tabindex", "-1");
+        }
+        return NodeFilter.FILTER_ACCEPT;
       }
-      if (element.hasAttribute("disabled")) {
-        return false;
-      }
-      let bounds = this._getBoundsWithoutFlushing(element);
-      return bounds.width > 0 && bounds.height > 0;
-    });
+      return NodeFilter.FILTER_SKIP;
+    };
+    return this.document.createTreeWalker(this.node, NodeFilter.SHOW_ELEMENT,
+      filter);
+  }
+
+  /**
+   * Get a TreeWalker which finds elements navigable with tab/shift+tab.
+   */
+  get _tabNavigableWalker() {
+    if (!this.__tabNavigableWalker) {
+      this.__tabNavigableWalker = this._makeNavigableTreeWalker(false);
+    }
+    return this.__tabNavigableWalker;
+  }
+
+  /**
+   * Get a TreeWalker which finds elements navigable with up/down arrow keys.
+   */
+  get _arrowNavigableWalker() {
+    if (!this.__arrowNavigableWalker) {
+      this.__arrowNavigableWalker = this._makeNavigableTreeWalker(true);
+    }
+    return this.__arrowNavigableWalker;
   }
 
   /**
    * Element that is currently selected with the keyboard, or null if no element
    * is selected. Since the reference is held weakly, it can become null or
    * undefined at any time.
-   *
-   * The element is usually, but not necessarily, among the _navigableElements.
    */
   get selectedElement() {
     return this._selectedElement && this._selectedElement.get();
   }
   set selectedElement(value) {
     if (!value) {
       delete this._selectedElement;
     } else {
       this._selectedElement = Cu.getWeakReference(value);
     }
   }
 
   /**
    * Focuses and moves keyboard selection to the first navigable element.
    * This is a no-op if there are no navigable elements.
+   *
+   * @param {Boolean} homeKey   `true` if this is for the home key.
    */
-  focusFirstNavigableElement() {
-    this.selectedElement = this._navigableElements[0];
+  focusFirstNavigableElement(homeKey = false) {
+    // The home key is conceptually similar to the up/down arrow keys.
+    let walker = homeKey ?
+      this._arrowNavigableWalker : this._tabNavigableWalker;
+    walker.currentNode = walker.root;
+    this.selectedElement = walker.firstChild();
     this.focusSelectedElement();
   }
 
   /**
    * Focuses and moves keyboard selection to the last navigable element.
    * This is a no-op if there are no navigable elements.
+   *
+   * @param {Boolean} endKey   `true` if this is for the end key.
    */
-  focusLastNavigableElement() {
-    this.selectedElement = this._navigableElements[this._navigableElements.length - 1];
+  focusLastNavigableElement(endKey = false) {
+    // The end key is conceptually similar to the up/down arrow keys.
+    let walker = endKey ?
+      this._arrowNavigableWalker : this._tabNavigableWalker;
+    walker.currentNode = walker.root;
+    this.selectedElement = walker.lastChild();
     this.focusSelectedElement();
   }
 
   /**
    * Based on going up or down, select the previous or next focusable element.
    *
    * @param {Boolean} isDown   whether we're going down (true) or up (false).
+   * @param {Boolean} arrowKey   `true` if this is for the up/down arrow keys.
    *
    * @return {DOMNode} the element we selected.
    */
-  moveSelection(isDown) {
-    let buttons = this._navigableElements;
-    let lastSelected = this.selectedElement;
-    let newButton = null;
-    let maxIdx = buttons.length - 1;
-    if (lastSelected) {
-      let buttonIndex = buttons.indexOf(lastSelected);
-      if (buttonIndex != -1) {
-        // Buttons may get selected whilst the panel is shown, so add an extra
-        // check here.
-        do {
-          buttonIndex = buttonIndex + (isDown ? 1 : -1);
-        } while (buttons[buttonIndex] && buttons[buttonIndex].disabled);
-        if (isDown && buttonIndex > maxIdx)
-          buttonIndex = 0;
-        else if (!isDown && buttonIndex < 0)
-          buttonIndex = maxIdx;
-        newButton = buttons[buttonIndex];
-      } else {
-        // The previously selected item is no longer selectable. Find the next item:
-        let allButtons = lastSelected.closest("panelview").getElementsByTagName("toolbarbutton");
-        let maxAllButtonIdx = allButtons.length - 1;
-        let allButtonIndex = allButtons.indexOf(lastSelected);
-        while (allButtonIndex >= 0 && allButtonIndex <= maxAllButtonIdx) {
-          allButtonIndex++;
-          // Check if the next button is in the list of focusable buttons.
-          buttonIndex = buttons.indexOf(allButtons[allButtonIndex]);
-          if (buttonIndex != -1) {
-            // If it is, just use that button if we were going down, or the previous one
-            // otherwise. If this was the first button, newButton will end up undefined,
-            // which is fine because we'll fall back to using the last button at the
-            // bottom of this method.
-            newButton = buttons[isDown ? buttonIndex : buttonIndex - 1];
-            break;
-          }
-        }
-      }
+  moveSelection(isDown, arrowKey = false) {
+    let walker = arrowKey ?
+      this._arrowNavigableWalker : this._tabNavigableWalker;
+    let oldSel = this.selectedElement;
+    let newSel;
+    if (oldSel) {
+      walker.currentNode = oldSel;
+      newSel = isDown ? walker.nextNode() : walker.previousNode();
     }
-
     // If we couldn't find something, select the first or last item:
-    if (!newButton) {
-      newButton = buttons[isDown ? 0 : maxIdx];
+    if (!newSel) {
+      walker.currentNode = walker.root;
+      newSel = isDown ? walker.firstChild() : walker.lastChild();
     }
-    this.selectedElement = newButton;
-    return newButton;
+    this.selectedElement = newSel;
+    return newSel;
   }
 
   /**
    * Allow for navigating subview buttons using the arrow keys and the Enter key.
    * The Up and Down keys can be used to navigate the list up and down and the
    * Enter, Right or Left - depending on the text direction - key can be used to
    * simulate a click on the currently selected button.
    * The Right or Left key - depending on the text direction - can be used to
@@ -1533,64 +1549,99 @@ var PanelView = class extends Associated
    *
    * @param {KeyEvent} event
    */
   keyNavigation(event) {
     if (!this.active) {
       return;
     }
 
-    let buttons = this._navigableElements;
-    if (!buttons.length) {
-      return;
-    }
-
     let stop = () => {
       event.stopPropagation();
       event.preventDefault();
     };
 
+    // If the focused element is only navigable with tab, it wants the arrow
+    // keys, etc. We shouldn't handle any keys except tab and shift+tab.
+    // We make a function for this for performance reasons: we only want to
+    // check this for keys we potentially care about, not *all* keys.
+    let tabOnly = () => {
+      // We use the real focus rather than this.selectedElement because focus
+      // might have been moved without keyboard navigation (e.g. mouse click)
+      // and this.selectedElement is only updated for keyboard navigation.
+      let focus = this.document.activeElement;
+      if (!focus) {
+        return false;
+      }
+      // Make sure the focus is actually inside the panel.
+      // (It might not be if the panel was opened with the mouse.)
+      // We use Node.compareDocumentPosition because Node.contains doesn't
+      // behave as expected for anonymous content; e.g. the input inside a
+      // textbox.
+      if (!(this.node.compareDocumentPosition(focus)
+            & Node.DOCUMENT_POSITION_CONTAINED_BY)) {
+        return false;
+      }
+      return this._isNavigableWithTabOnly(focus);
+    };
+
     let keyCode = event.code;
     switch (keyCode) {
       case "ArrowDown":
       case "ArrowUp":
+        if (tabOnly()) {
+          break;
+        }
+        // Fall-through...
       case "Tab": {
         stop();
         let isDown = (keyCode == "ArrowDown") ||
                      (keyCode == "Tab" && !event.shiftKey);
-        let button = this.moveSelection(isDown);
+        let button = this.moveSelection(isDown, keyCode != "Tab");
         button.focus();
         break;
       }
       case "Home":
+        if (tabOnly()) {
+          break;
+        }
         stop();
-        this.focusFirstNavigableElement();
+        this.focusFirstNavigableElement(true);
         break;
       case "End":
+        if (tabOnly()) {
+          break;
+        }
         stop();
-        this.focusLastNavigableElement();
+        this.focusLastNavigableElement(true);
         break;
       case "ArrowLeft":
       case "ArrowRight": {
+        if (tabOnly()) {
+          break;
+        }
         stop();
         if ((!this.window.RTL_UI && keyCode == "ArrowLeft") ||
             (this.window.RTL_UI && keyCode == "ArrowRight")) {
           this.node.panelMultiView.goBack();
           break;
         }
         // If the current button is _not_ one that points to a subview, pressing
         // the arrow key shouldn't do anything.
         let button = this.selectedElement;
         if (!button || !button.classList.contains("subviewbutton-nav")) {
           break;
         }
         // Fall-through...
       }
       case "Space":
       case "Enter": {
+        if (tabOnly()) {
+          break;
+        }
         let button = this.selectedElement;
         if (!button)
           break;
         stop();
 
         // Unfortunately, 'tabindex' doesn't execute the default action, so
         // we explicitly do this here.
         // We are sending a command event and then a click event.
@@ -1613,16 +1664,15 @@ var PanelView = class extends Associated
       selected.focus();
     }
   }
 
   /**
    * Clear all traces of keyboard navigation happening right now.
    */
   clearNavigation() {
-    delete this.__navigableElements;
     let selected = this.selectedElement;
     if (selected) {
       selected.blur();
       this.selectedElement = null;
     }
   }
 };
--- a/browser/components/customizableui/content/panelUI.inc.xul
+++ b/browser/components/customizableui/content/panelUI.inc.xul
@@ -4,17 +4,17 @@
 
 <panel id="widget-overflow"
        role="group"
        type="arrow"
        noautofocus="true"
        position="bottomcenter topright"
        photon="true"
        hidden="true">
-  <panelmultiview mainViewId="widget-overflow-mainView" disablekeynav="true">
+  <panelmultiview mainViewId="widget-overflow-mainView">
     <panelview id="widget-overflow-mainView"
                context="toolbar-context-menu">
       <vbox class="panel-subview-body">
         <vbox id="widget-overflow-list" class="widget-overflow-list"
               overflowfortoolbar="nav-bar"/>
         <toolbarseparator id="widget-overflow-fixed-separator" hidden="true"/>
         <vbox id="widget-overflow-fixed-list" class="widget-overflow-list" hidden="true" />
       </vbox>
--- a/browser/components/customizableui/test/browser.ini
+++ b/browser/components/customizableui/test/browser.ini
@@ -169,16 +169,17 @@ tags = fullscreen
 [browser_backfwd_enabled_post_customize.js]
 [browser_check_tooltips_in_navbar.js]
 [browser_editcontrols_update.js]
 subsuite = clipboard
 [browser_customization_context_menus.js]
 [browser_newtab_button_customizemode.js]
 [browser_open_from_popup.js]
 [browser_PanelMultiView_focus.js]
+[browser_PanelMultiView_keyboard.js]
 [browser_sidebar_toggle.js]
 skip-if = verify
 [browser_tabbar_big_widgets.js]
 [browser_remote_tabs_button.js]
 skip-if = (verify && debug && (os == 'linux' || os == 'mac'))
 [browser_widget_animation.js]
 [browser_lwt_telemetry.js]
 
new file mode 100644
--- /dev/null
+++ b/browser/components/customizableui/test/browser_PanelMultiView_keyboard.js
@@ -0,0 +1,239 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test the keyboard behavior of PanelViews.
+ */
+
+const {PanelMultiView} = ChromeUtils.import("resource:///modules/PanelMultiView.jsm");
+
+let gAnchor;
+let gPanel;
+let gPanelMultiView;
+let gMainView;
+let gMainButton1;
+let gMainMenulist;
+let gMainTextbox;
+let gMainButton2;
+let gMainButton3;
+let gMainTabOrder;
+let gMainArrowOrder;
+let gSubView;
+let gSubButton;
+let gSubTextarea;
+
+async function openPopup() {
+  let shown = BrowserTestUtils.waitForEvent(gMainView, "ViewShown");
+  PanelMultiView.openPopup(gPanel, gAnchor, "bottomcenter topright");
+  await shown;
+}
+
+async function hidePopup() {
+  let hidden = BrowserTestUtils.waitForEvent(gPanel, "popuphidden");
+  PanelMultiView.hidePopup(gPanel);
+  await hidden;
+}
+
+async function showSubView() {
+  let shown = BrowserTestUtils.waitForEvent(gSubView, "ViewShown");
+  gPanelMultiView.showSubView(gSubView);
+  await shown;
+}
+
+async function expectFocusAfterKey(aKey, aFocus) {
+  let res = aKey.match(/^(Shift\+)?(.+)$/);
+  let shift = Boolean(res[1]);
+  let key;
+  if (res[2].length == 1) {
+    key = res[2]; // Character.
+  } else {
+    key = "KEY_" + res[2]; // Tab, ArrowRight, etc.
+  }
+  info("Waiting for focus on " + aFocus.id);
+  let focused = BrowserTestUtils.waitForEvent(aFocus, "focus");
+  EventUtils.synthesizeKey(key, {shiftKey: shift});
+  await focused;
+  ok(true, aFocus.id + " focused after " + aKey + " pressed");
+}
+
+add_task(async function setup() {
+  let navBar = document.getElementById("nav-bar");
+  gAnchor = document.createXULElement("toolbarbutton");
+  navBar.appendChild(gAnchor);
+  gPanel = document.createXULElement("panel");
+  navBar.appendChild(gPanel);
+  gPanelMultiView = document.createXULElement("panelmultiview");
+  gPanelMultiView.setAttribute("mainViewId", "testMainView");
+  gPanel.appendChild(gPanelMultiView);
+
+  gMainView = document.createXULElement("panelview");
+  gMainView.id = "testMainView";
+  gPanelMultiView.appendChild(gMainView);
+  gMainButton1 = document.createXULElement("button");
+  gMainButton1.id = "gMainButton1";
+  gMainView.appendChild(gMainButton1);
+  gMainMenulist = document.createXULElement("menulist");
+  gMainMenulist.id = "gMainMenulist";
+  gMainView.appendChild(gMainMenulist);
+  let menuPopup = document.createXULElement("menupopup");
+  gMainMenulist.appendChild(menuPopup);
+  let item = document.createXULElement("menuitem");
+  item.setAttribute("value", "1");
+  item.setAttribute("selected", "true");
+  menuPopup.appendChild(item);
+  item = document.createXULElement("menuitem");
+  item.setAttribute("value", "2");
+  menuPopup.appendChild(item);
+  gMainTextbox = document.createXULElement("textbox");
+  gMainTextbox.id = "gMainTextbox";
+  gMainView.appendChild(gMainTextbox);
+  gMainTextbox.setAttribute("value", "value");
+  gMainButton2 = document.createXULElement("button");
+  gMainButton2.id = "gMainButton2";
+  gMainView.appendChild(gMainButton2);
+  gMainButton3 = document.createXULElement("button");
+  gMainButton3.id = "gMainButton3";
+  gMainView.appendChild(gMainButton3);
+  gMainTabOrder = [gMainButton1, gMainMenulist, gMainTextbox, gMainButton2,
+                   gMainButton3];
+  gMainArrowOrder = [gMainButton1, gMainButton2, gMainButton3];
+
+  gSubView = document.createXULElement("panelview");
+  gSubView.id = "testSubView";
+  gPanelMultiView.appendChild(gSubView);
+  gSubButton = document.createXULElement("button");
+  gSubView.appendChild(gSubButton);
+  gSubTextarea = document.createElementNS("http://www.w3.org/1999/xhtml",
+                                          "textarea");
+  gSubTextarea.id = "gSubTextarea";
+  gSubView.appendChild(gSubTextarea);
+  gSubTextarea.value = "value";
+
+  registerCleanupFunction(() => {
+    gAnchor.remove();
+    gPanel.remove();
+  });
+});
+
+// Test that the tab key focuses all expected controls.
+add_task(async function testTab() {
+  await openPopup();
+  for (let elem of gMainTabOrder) {
+    await expectFocusAfterKey("Tab", elem);
+  }
+  // Wrap around.
+  await expectFocusAfterKey("Tab", gMainTabOrder[0]);
+  await hidePopup();
+});
+
+// Test that the shift+tab key focuses all expected controls.
+add_task(async function testShiftTab() {
+  await openPopup();
+  for (let i = gMainTabOrder.length - 1; i >= 0; --i) {
+    await expectFocusAfterKey("Shift+Tab", gMainTabOrder[i]);
+  }
+  // Wrap around.
+  await expectFocusAfterKey("Shift+Tab",
+                            gMainTabOrder[gMainTabOrder.length - 1]);
+  await hidePopup();
+});
+
+// Test that the down arrow key skips menulists and textboxes.
+add_task(async function testDownArrow() {
+  await openPopup();
+  for (let elem of gMainArrowOrder) {
+    await expectFocusAfterKey("ArrowDown", elem);
+  }
+  // Wrap around.
+  await expectFocusAfterKey("ArrowDown", gMainArrowOrder[0]);
+  await hidePopup();
+});
+
+// Test that the up arrow key skips menulists and textboxes.
+add_task(async function testUpArrow() {
+  await openPopup();
+  for (let i = gMainArrowOrder.length - 1; i >= 0; --i) {
+    await expectFocusAfterKey("ArrowUp", gMainArrowOrder[i]);
+  }
+  // Wrap around.
+  await expectFocusAfterKey("ArrowUp",
+                            gMainArrowOrder[gMainArrowOrder.length - 1]);
+  await hidePopup();
+});
+
+// Test that the home/end keys move to the first/last controls.
+add_task(async function testHomeEnd() {
+  await openPopup();
+  await expectFocusAfterKey("Home", gMainArrowOrder[0]);
+  await expectFocusAfterKey("End",
+                            gMainArrowOrder[gMainArrowOrder.length - 1]);
+  await hidePopup();
+});
+
+// Test that the up/down arrow keys adjust the value of menulists.
+add_task(async function testArrowsMenulist() {
+  await openPopup();
+  gMainMenulist.focus();
+  is(document.activeElement, gMainMenulist, "menulist focused");
+  is(gMainMenulist.value, "1", "menulist initial value 1");
+  EventUtils.synthesizeKey("KEY_ArrowDown");
+  is(document.activeElement, gMainMenulist,
+     "menulist still focused after ArrowDown");
+  is(gMainMenulist.value, "2", "menulist value 2 after ArrowDown");
+  EventUtils.synthesizeKey("KEY_ArrowUp");
+  is(document.activeElement, gMainMenulist,
+     "menulist still focused after ArrowUp");
+  is(gMainMenulist.value, "1", "menulist value 1 after ArrowUp");
+  await hidePopup();
+});
+
+// Test that pressing space in a textbox inserts a space (instead of trying to
+// activate the control).
+add_task(async function testSpaceTextbox() {
+  await openPopup();
+  gMainTextbox.focus();
+  EventUtils.synthesizeKey("KEY_Home");
+  EventUtils.synthesizeKey(" ");
+  is(gMainTextbox.value, " value", "Space typed into textbox");
+  gMainTextbox.value = "value";
+  await hidePopup();
+});
+
+// Tests that the left arrow key normally moves back to the previous view.
+add_task(async function testLeftArrow() {
+  await openPopup();
+  await showSubView();
+  let shown = BrowserTestUtils.waitForEvent(gMainView, "ViewShown");
+  EventUtils.synthesizeKey("KEY_ArrowLeft");
+  await shown;
+  ok("Moved to previous view after ArrowLeft");
+  await hidePopup();
+});
+
+// Tests that the left arrow key moves the caret in a textarea in a subview
+// (instead of going back to the previous view).
+add_task(async function testLeftArrowTextarea() {
+  await openPopup();
+  await showSubView();
+  gSubTextarea.focus();
+  is(document.activeElement, gSubTextarea, "textarea focused");
+  EventUtils.synthesizeKey("KEY_End");
+  is(gSubTextarea.selectionStart, 5, "selectionStart 5 after End");
+  EventUtils.synthesizeKey("KEY_ArrowLeft");
+  is(gSubTextarea.selectionStart, 4, "selectionStart 4 after ArrowLeft");
+  is(document.activeElement, gSubTextarea, "textarea still focused");
+  await hidePopup();
+});
+
+// Test navigation to a button which is initially disabled and later enabled.
+add_task(async function testDynamicButton() {
+  gMainButton2.disabled = true;
+  await openPopup();
+  await expectFocusAfterKey("ArrowDown", gMainButton1);
+  await expectFocusAfterKey("ArrowDown", gMainButton3);
+  gMainButton2.disabled = false;
+  await expectFocusAfterKey("ArrowUp", gMainButton2);
+  await hidePopup();
+});