head.js (2425B)
1 /* Any copyright is dedicated to the Public Domain. 2 * http://creativecommons.org/publicdomain/zero/1.0/ */ 3 4 "use strict"; 5 6 /** 7 * Force focus to an element that isn't focusable. 8 * Toolbar buttons aren't focusable because if they were, clicking them would 9 * focus them, which is undesirable. Therefore, they're only made focusable 10 * when a user is navigating with the keyboard. This function forces focus as 11 * is done during toolbar keyboard navigation. 12 * It then runs the `activateMethod` passed in, and restores usual focus state 13 * afterwards. `activateMethod` can be async. 14 */ 15 async function focusAndActivateElement(elem, activateMethod) { 16 elem.setAttribute("tabindex", "-1"); 17 elem.focus(); 18 try { 19 await activateMethod(elem); 20 } finally { 21 elem.removeAttribute("tabindex"); 22 } 23 } 24 25 async function expectFocusAfterKey( 26 aKey, 27 aFocus, 28 aAncestorOk = false, 29 aWindow = window 30 ) { 31 let res = aKey.match(/^(Shift\+)?(?:(.)|(.+))$/); 32 let shift = Boolean(res[1]); 33 let key; 34 if (res[2]) { 35 key = res[2]; // Character. 36 } else { 37 key = "KEY_" + res[3]; // Tab, ArrowRight, etc. 38 } 39 let expected; 40 let friendlyExpected; 41 if (typeof aFocus == "string") { 42 expected = aWindow.document.getElementById(aFocus); 43 friendlyExpected = aFocus; 44 } else { 45 expected = aFocus; 46 if (aFocus == aWindow.gURLBar.inputField) { 47 friendlyExpected = "URL bar input"; 48 } else if (aFocus == aWindow.gBrowser.selectedBrowser) { 49 friendlyExpected = "Web document"; 50 } 51 } 52 info( 53 "Listening on item " + friendlyExpected || 54 expected.id || 55 expected.className || 56 expected.tagName 57 ); 58 let focused = BrowserTestUtils.waitForEvent(expected, "focus", aAncestorOk); 59 EventUtils.synthesizeKey(key, { shiftKey: shift }, aWindow); 60 let receivedEvent = await focused; 61 let friendlyReceived; 62 if (receivedEvent.target == aWindow.gURLBar.inputField) { 63 friendlyReceived = "URL bar input"; 64 } else if (receivedEvent.target == aWindow.gBrowser.selectedBrowser) { 65 friendlyReceived = "Web document"; 66 } 67 info( 68 "Got focus on item: " + 69 (friendlyReceived || 70 receivedEvent.target?.id || 71 receivedEvent.target?.className || 72 receivedEvent.target?.tagName) 73 ); 74 ok(true, friendlyExpected + " focused after " + aKey + " pressed"); 75 } 76 77 registerCleanupFunction(async () => { 78 await SidebarController.initializeUIState({ command: "" }); 79 });