diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b21e3074..224d12df 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -21,7 +21,7 @@ jobs: uses: actions/checkout@v7 - name: Set up Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v7 with: node-version: 24 cache: npm diff --git a/src/js/background/background.js b/src/js/background/background.js index eca991ad..8756061e 100644 --- a/src/js/background/background.js +++ b/src/js/background/background.js @@ -12,6 +12,9 @@ import trackers from "@/background/page-trackers"; import { isPopupWindow } from "@/background/popup-utils"; import handleStartup from "@/background/startup"; import checkMenuPick from "@/background/check-menu-pick"; +import watchForDoublePress from "@/background/double-press"; +import getChromeShortcuts from "@/background/get-chrome-shortcuts"; +import { CommandIDs } from "@/background/constants"; import log from "@/background/persistent-log"; import initEventController from "@/shared/eventController"; import { toggleRecentTabs } from "@/shared/commandHandlers"; @@ -25,9 +28,6 @@ if (globalThis.DEBUG) { // relaunch woke the worker at all, and whether onStartup fired after it log("service worker loaded"); - // if the popup is opened and closed within this time, switch to the - // previous tab -const MaxPopupLifetime = 450; const RestartDelay = 60 * 1000; // how long the tab handlers stay quiet after a restart if nothing else // clears the flag. generous, since a big profile can take over a minute to @@ -52,6 +52,15 @@ function delay( } + // the shortcut Chrome currently has for opening the menu, to tell a second + // press of it from the other keys the menu page reports +function getMenuShortcut() +{ + return getChromeShortcuts() + .then((shortcuts) => shortcuts.find(({ id }) => id == CommandIDs.OpenMenuCommand)); +} + + const ports = {}; //let startingUp = false; // handleStartup() reads the reason synchronously to decide whether this @@ -153,15 +162,9 @@ chrome.runtime.onConnect.addListener(port => { } //console.log("---- background: onConnect", port?.name); - // if sw.js is replaying a connect that arrived while this worker was - // still starting, use when it arrived. the time of the replay would - // make a menu that had been open through a slow start look like it had - // only just opened, and closing it would be taken for a double-press. - const connectTime = globalThis.replayedEventTime ?? Date.now(); // the port this worker made for itself at startup, below, rather than // one a page opened in init.js const isStandIn = port.isStandIn === true; - let closedOnPurpose = false; // the window the menu opened over, so a failed pick can say whether it // was of a tab in another window. kept as a promise, since a quick // pick can arrive before it resolves. @@ -188,13 +191,12 @@ DEBUG && console.log("== onConnect", port.name, state.startingUp); // TODO: this only needs to be done for the menu case port.onMessage.addListener(message => { //console.log("---- background: onMessage", port.name, message); - // the page says when it's closing because of something the user - // did in it, either pressing esc or picking an item. a pick of a - // tab comes as an object with its ID. + // the menu says when it's closing because the user picked an + // item. a pick of a tab comes as an object with its ID. + // double-press.js listens for the same messages, to tell a pick + // or esc from a second press of the shortcut. const name = message?.message ?? message; - closedOnPurpose = (name == "closedByEsc" || name == "pickedItem"); - if (port.name == "menu" && name == "pickedItem" && typeof message?.tabID == "number") { // the menu can't see whether its pick worked, since its page // may be destroyed before the tab is activated. start watching @@ -215,19 +217,32 @@ DEBUG && console.log("== onConnect", port.name, state.startingUp); popupWindow.close("popup-port-disconnected"); // } } - - // a stand-in port can't be a double-press: it's made when the worker - // starts, not when the user opens anything. it drops right away if - // the popup page was already closing, such as after a hide behavior - // change, which woke the worker and then switched to the previous tab. - // nor can a menu that said it was closing: without that, picking a - // tab within MaxPopupLifetime of opening the menu switched to it - // and then toggled straight back. - if (!isStandIn && !closedOnPurpose && Date.now() - connectTime < MaxPopupLifetime) { - // this was a double-press of alt-Q, so toggle the tabs - toggleRecentTabs(); - } }); + + // a popup window or menu that's closed by a second press of its + // shortcut is a double-press, so toggle the tabs. the worker does + // that even when the popup window's page has control: the menu + // connecting always wakes the worker, its timing of the port doesn't + // depend on a hidden page that can be slow to hear about the close, + // and for the popup window, its own page is the one going away. + // the menu's page reports the keys it sees, so a second press can be + // timed from the key going down rather than from the port closing. + // a stand-in port can't be a double-press: it's made when the worker + // starts, not when the user opens anything. it drops right away if + // the popup page was already closing, such as after a hide behavior + // change, which woke the worker and then switched to the previous tab. + if (!isStandIn) { + watchForDoublePress( + port, + ({ pressTime, lifetime }) => { + log("double-press of the", port.name, "shortcut:", pressTime !== undefined + ? `key down ${pressTime} ms after the page started` + : `closed after ${lifetime} ms`); + toggleRecentTabs(); + }, + port.name == "menu" ? getMenuShortcut : undefined + ); + } }); diff --git a/src/js/background/double-press.js b/src/js/background/double-press.js new file mode 100644 index 00000000..32230570 --- /dev/null +++ b/src/js/background/double-press.js @@ -0,0 +1,156 @@ + // pressing the shortcut for the menu or the popup window again right after + // it opens closes it, and that double-press toggles to the previous tab. + // Chrome doesn't tell the extension about either press of the menu's + // shortcut, and the popup window's page is the one going away, so the + // worker has to work it out from the page's port. + + // if the popup or menu is opened and closed within this time, it's taken + // for a second press of the shortcut that opened it +const MaxPopupLifetime = 450; + // when the menu's page saw the second press itself, how long after the + // page started the key can have gone down. the port's lifetime is a poor + // measure of the time between the presses: it starts when the page + // connects, some 70-110 ms after the page starts, and ends when the page + // has gone, which was 230-350 ms after the second press on a fast machine + // with few tabs, and longer the busier the page is. so the same pair of + // presses could land on either side of MaxPopupLifetime. + // the page starts some tens of ms after the first press, so this allows + // a little over half a second between the presses, about the default + // double-click time on Windows. it was 300 at first, which is what + // MaxPopupLifetime allowed at its best, and that turned out to be right + // in the middle of an unhurried double-press: in one run of ten, the key + // went down 242-335 ms after the page started, and only half toggled. + // it can be this generous because only a second press of the menu's own + // shortcut counts. a click outside the menu or a slow page can't. +const MaxPressGap = 500; + +const ModifierFlags = ["altKey", "ctrlKey", "shiftKey", "metaKey"]; + // the names get-chrome-shortcuts.js gives the modifiers, on any platform +const FlagsByModifier = { + alt: "altKey", + opt: "altKey", + ctrl: "ctrlKey", + shift: "shiftKey", + cmd: "metaKey", + search: "metaKey" +}; +const KeyNames = { + " ": "space" +}; + // the letter or digit on a key, whatever a modifier turned it into +const CodePattern = /^(?:Key|Digit)(.)$/; + + + // whether a keydown the menu page reported is the given shortcut, which is + // an entry from get-chrome-shortcuts.js. the modifiers have to match + // exactly, since Chrome wouldn't take anything else for the shortcut. +export function isShortcutKey( + { type, repeat, key, code, ...flags }, + shortcut) +{ + const { baseKey, modifiers = [] } = shortcut || {}; + + if (type !== "keydown" || repeat || !baseKey || !modifiers.length) { + return false; + } + + const shortcutFlags = modifiers.map((modifier) => FlagsByModifier[modifier]); + const lcKey = String(key).toLowerCase(); + // with a modifier down, the key can be a different character, like ! + // for shift-1, or a dead key for opt-E on a Mac, so check the code too + const names = [KeyNames[lcKey] || lcKey, CodePattern.exec(code)?.[1].toLowerCase()]; + + return !shortcutFlags.includes(undefined) + && ModifierFlags.every((flag) => Boolean(flags[flag]) == shortcutFlags.includes(flag)) + && names.includes(baseKey); +} + + + // call onDoublePress if the page behind port was closed by a second press + // of the shortcut that opened it. call this from an onConnect handler, + // since the port's lifetime is counted from the call. + // + // getShortcut is passed for the menu. it returns a promise of the menu's + // shortcut, and it's called now, so the answer is ready by the time the + // port closes. the user can change the shortcut at any time and Chrome + // doesn't say when, so it's asked for each time the menu opens. if the + // page reported a press of that shortcut, when the key went down decides + // it. otherwise it's whether the port closed within MaxPopupLifetime, + // which is all there is to go on when: + // - it's the popup window's port + // - the press came before the menu had the focus. it goes to the + // browser window then, and Chrome closes the menu before it's shown. + // - Chrome didn't return the shortcut, which it sometimes doesn't + // + // neither catches a press that comes after the menu has the focus but + // before it has painted, a stretch of 50-90 ms. Chrome doesn't deliver a + // key that goes down then to the page, and doesn't close the menu either, + // so the menu just stays open. that's true of any key, not only the + // shortcut, and the page can't tell it from a single press held past the + // paint, since all it sees of either is the key coming up. + // + // onDoublePress is passed how it was decided, for logging: { pressTime } + // in ms from the page starting, or { lifetime } in ms. +export default function watchForDoublePress( + port, + onDoublePress, + getShortcut) +{ + // if sw.js is replaying a connect that arrived while the worker was + // still starting, use when it arrived. the time of the replay would + // make a menu that had been open through a slow start look like it had + // only just opened, and closing it would be taken for a double-press. + const connectTime = globalThis.replayedEventTime ?? Date.now(); + const shortcutPromise = getShortcut + ? Promise.resolve().then(getShortcut).catch(() => null) + : null; + const keys = []; + let closedOnPurpose = false; + + port.onMessage.addListener((message) => { + // the page says when it's closing because of something the user + // did in it, either pressing esc or picking an item. without + // that, picking a tab within MaxPopupLifetime of opening the menu + // switched to it and then toggled straight back. the message is + // a string, or an object with the string in its message key. + // once said, it stays said, since the page posts other things on + // this port too, and one of those arriving afterwards mustn't + // turn a pick back into a double-press. + const name = message?.message ?? message; + + if (name == "closedByEsc" || name == "pickedItem") { + closedOnPurpose = true; + } else if (name == "menuKey") { + keys.push(message); + } + }); + + port.onDisconnect.addListener(() => { + if (closedOnPurpose) { + return; + } + + const lifetime = Date.now() - connectTime; + const checkLifetime = () => { + if (lifetime < MaxPopupLifetime) { + onDoublePress({ lifetime }); + } + }; + + if (!shortcutPromise || !keys.length) { + checkLifetime(); + + return; + } + + shortcutPromise.then((shortcut) => { + const press = keys.find((key) => isShortcutKey(key, shortcut)); + + if (!press) { + checkLifetime(); + } else if (press.time < MaxPressGap) { + onDoublePress({ pressTime: press.time }); + } + }); + }); +} diff --git a/src/js/background/sw.js b/src/js/background/sw.js index 91c9ca07..666123d0 100644 --- a/src/js/background/sw.js +++ b/src/js/background/sw.js @@ -82,16 +82,55 @@ const DetachedEventNames = new Set(["commands.onCommand"]); // sent to a dead port until the menu is next opened and closed. const closedPorts = new WeakSet(); -function watchForClose( + // what each cached port has posted so far. a page posts as soon as it has + // connected, and Chrome doesn't hold a message for a listener that's added + // later, so anything posted before background.js got to the port's + // onConnect was lost. that included the key the toolbar menu's page + // reports when its shortcut is pressed a second time: a double-press that + // started the worker could only be judged by how long the port stayed + // open, and one that kept it open 465 ms didn't toggle. the messages are + // handed to the port's real listeners right after its connect is replayed. + // a port never has more than a handful this early, but a page that's stuck + // in a loop shouldn't be able to fill the worker's memory while it starts. +const MaxCachedPortMessages = 50; +const cachedPortMessages = new Map(); + +function watchPort( port) { try { + const messages = []; + const keep = (message) => { + if (messages.length < MaxCachedPortMessages) { + messages.push(message); + } + }; + port.onDisconnect.addListener(() => closedPorts.add(port)); + port.onMessage.addListener(keep); + cachedPortMessages.set(port, { messages, keep }); } catch (error) { // the placeholder listener must never throw } } + // stop keeping a port's messages, and return the ones it posted +function takePortMessages( + port) +{ + const { messages = [], keep } = cachedPortMessages.get(port) || {}; + + cachedPortMessages.delete(port); + + try { + keep && port.onMessage.removeListener(keep); + } catch (error) { + // a port that has closed throws when it's touched + } + + return messages; +} + function cacheEvents( eventNames) { @@ -111,7 +150,7 @@ function cacheEvents( cache.push([eventName, eventArgs, Date.now()]); if (eventName === "runtime.onConnect") { - watchForClose(eventArgs[0]); + watchPort(eventArgs[0]); } if (cache.length > MaxCachedEvents) { @@ -145,6 +184,19 @@ function cacheEvents( // causing the shortcuts, tab events and onStartup to all go dead. cache = null; + // only the ports replayed below still need their messages. the + // rest are closed, were dropped from the cache as too old, or + // have nothing to be replayed to. + const replayedPorts = new Set(!loaded ? [] : events + .filter(([eventName]) => eventName === "runtime.onConnect") + .map(([, [port]]) => port)); + + for (const port of [...cachedPortMessages.keys()]) { + if (!replayedPorts.has(port)) { + takePortMessages(port); + } + } + if (!loaded) { // there are no real handlers to replay to. keeping every // placeholder, including onCommand's, means the next event @@ -163,6 +215,10 @@ function cacheEvents( for (const event of events) { const [eventName, eventArgs, time] = event; + const portMessages = eventName === "runtime.onConnect" + ? takePortMessages(eventArgs[0]) + : []; + if (isExpired(event, cutoff)) { log("sw dropping stale event:", eventName, Date.now() - time, "ms old"); continue; @@ -183,6 +239,13 @@ function cacheEvents( try { getEvent(eventName).dispatch(...eventArgs); + + // the port's onConnect handlers have added their listeners + // now, so give them what the page has posted since it + // connected, in order + for (const message of portMessages) { + eventArgs[0].onMessage.dispatch(message, eventArgs[0]); + } } finally { globalThis.replayedEventTime = undefined; } diff --git a/src/js/shared/commandHandlers.js b/src/js/shared/commandHandlers.js index 9bcd9d44..a4d19abb 100644 --- a/src/js/shared/commandHandlers.js +++ b/src/js/shared/commandHandlers.js @@ -472,9 +472,19 @@ function isAddableTab( } + // the active tab, for a context that isn't told about tab events +function getActiveTab() +{ + return chrome.tabs.query({ active: true, lastFocusedWindow: true }) + .then(([tab]) => tab) + .catch(() => null); +} + + // exported because background.js also calls this when the popup or menu // port disconnects right after connecting, which means the user - // double-pressed the open-popup shortcut to switch tabs + // double-pressed the shortcut that opened it to switch tabs. the worker + // does that whether or not it has control. export function toggleRecentTabs( fromShortcut, receivedTime = Date.now(), @@ -492,6 +502,8 @@ export function toggleRecentTabs( const command = fromShortcut ? ToggleTabsCommand : "toggle from double-press"; // the shortcut's active tab, if we should add it before toggling let tabToAdd = null; + // whether this context is the one that's told about tab events + let hasControl = true; enqueueRecentsCommand(trackCommand(command, (isStale, endPhase) => settingsLoaded // if the user navigated to a tab but hasn't waited for the min @@ -514,11 +526,29 @@ export function toggleRecentTabs( // previous one was still running added the tab it had just left // back on top, then toggled to the tab that was already active, so // no activation came and every later toggle queued up behind it. + // a double-press of the menu's shortcut is handled by the worker + // even when the popup window's page has control, which it takes + // when the worker goes idle and keeps until it closes. the tab + // events go to that page, so this worker has no pending add to + // flush, and the page's can be up to MinTabDwellTime behind. ask + // for the active tab instead, now that the commands ahead of this + // one have finished switching, and let toggle() add it. .then(() => { endPhase("settings"); - tabToAdd = isAddableTab(activeTab) && receivedTime > lastRecentsCommandEnd - ? activeTab - : null; + hasControl = control.isHeld(); + + if (!hasControl) { + return getActiveTab().then((tab) => { + endPhase("activeTab"); + + return tab; + }); + } + + return receivedTime > lastRecentsCommandEnd ? activeTab : null; + }) + .then((currentTab) => { + tabToAdd = isAddableTab(currentTab) ? currentTab : null; if (tabToAdd) { addTab.cancel(); @@ -568,7 +598,9 @@ export function toggleRecentTabs( .then((switched) => { endPhase("toggle"); log("toggle: switched:", switched, - switched ? "waiting for the activation" : ""); + !switched ? "" : hasControl + ? "waiting for the activation" + : "not waiting, the activation goes to the context with control"); return switched; }) @@ -587,7 +619,10 @@ export function toggleRecentTabs( // those are out of date, the target can be the tab that's already // active. so give up on the activation after MaxActivationWait, // and cancel the wait so the next add isn't rushed through. - .then((switched) => switched && waitForActivation()) + // a context without control never sees the activation. the + // worker used to wait the full MaxActivationWait for it after a + // double-press, holding up any toggle queued behind this one. + .then((switched) => switched && hasControl && waitForActivation()) .then(() => { endPhase("activation"); tracker.event("recents", diff --git a/src/public/js/popup/init.js b/src/public/js/popup/init.js index d5f53fef..ef94726d 100644 --- a/src/public/js/popup/init.js +++ b/src/public/js/popup/init.js @@ -36,6 +36,38 @@ if (gIsMenu) { } const gInitTime = performance.now(); +if (gIsMenu) { + // a second press of the menu's shortcut closes the menu, and the + // background toggles to the previous tab if it came soon enough after + // the first. Chrome doesn't tell the extension about either press, + // but this page sees the second one's keydown if it comes after the + // menu has painted. so tell the background about each key that goes + // down with a modifier, which a shortcut always has. + // background/double-press.js checks it against the menu's shortcut. + // it's done here rather than in main.js so that a key pressed before + // the rest of the page has loaded is still reported. + window.addEventListener("keydown", ({ type, key, code, repeat, altKey, ctrlKey, shiftKey, metaKey, timeStamp }) => { + if (!repeat && (altKey || ctrlKey || metaKey)) { + try { + gPort.postMessage({ + message: "menuKey", + type, + key, + code, + repeat, + altKey, + ctrlKey, + shiftKey, + metaKey, + // when the key was pressed, in ms since the page + // started, however late this handler got to run + time: Math.round(timeStamp) + }); + } catch (error) {} + } + }, true); +} + let gKeyCache = []; let gShortcutCache = []; diff --git a/test/support/stdout-ext.js b/test/support/stdout-ext.js new file mode 100644 index 00000000..efeb25d3 --- /dev/null +++ b/test/support/stdout-ext.js @@ -0,0 +1,4 @@ + // stands in for the stdout-ext package under test. that package is a + // file: dependency on a sibling checkout, so it only exists on a machine + // that has it, and error-handler.js imports it unconditionally. +export default function stdout() {} diff --git a/test/unit/double-press.test.js b/test/unit/double-press.test.js new file mode 100644 index 00000000..cf05f00c --- /dev/null +++ b/test/unit/double-press.test.js @@ -0,0 +1,341 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import watchForDoublePress, { isShortcutKey } from "@/background/double-press"; + + + // a menu that closes within MaxPopupLifetime of opening is taken for a + // second press of its shortcut, which toggles to the previous tab. a tab + // picked that quickly closed the menu just as fast, so the pick was + // followed by a switch straight back. the menu now says when it's + // closing because of something the user did in it. +const MaxPopupLifetime = 450; + // how long after the menu's page starts the second press can come, when + // the page saw it +const MaxPressGap = 500; + + // what get-chrome-shortcuts.js returns for alt-E, and what the menu page + // reports for the E going down with alt held +const AltE = { id: "_execute_action", baseKey: "e", modifiers: ["alt"] }; + +function keyDown( + time, + props = {}) +{ + return { + message: "menuKey", + type: "keydown", + key: "e", + code: "KeyE", + repeat: false, + altKey: true, + ctrlKey: false, + shiftKey: false, + metaKey: false, + time, + ...props + }; +} + + // let the promise for the shortcut settle +async function settle() +{ + for (let i = 0; i < 5; i++) { + await Promise.resolve(); + } +} + + +function openPort() +{ + const port = chrome.runtime.connect(); + const onDoublePress = vi.fn(); + + watchForDoublePress(port, onDoublePress); + + return { port, onDoublePress }; +} + + +describe("a port that closes soon after opening", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + globalThis.replayedEventTime = undefined; + }); + + it("is a double-press when it closes without a word", () => { + const { port, onDoublePress } = openPort(); + + vi.advanceTimersByTime(MaxPopupLifetime - 50); + + expect(onDoublePress).not.toHaveBeenCalled(); + + port.onDisconnect.dispatch(port); + + expect(onDoublePress).toHaveBeenCalledOnce(); + }); + + it("isn't one when the page said the user picked an item", () => { + const { port, onDoublePress } = openPort(); + + vi.advanceTimersByTime(MaxPopupLifetime - 50); + port.onMessage.dispatch("pickedItem"); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + it("isn't one when the pick came as an object", () => { + const { port, onDoublePress } = openPort(); + + port.onMessage.dispatch({ message: "pickedItem", tabID: 2 }); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + it("isn't one when the page said it was closed by esc", () => { + const { port, onDoublePress } = openPort(); + + port.onMessage.dispatch("closedByEsc"); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + it("isn't one when esc is followed by the menu's own close", () => { + const { port, onDoublePress } = openPort(); + + // closeWindow() posts both when the menu is closed by esc + port.onMessage.dispatch("closedByEsc"); + port.onMessage.dispatch("pickedItem"); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + it("isn't one when something else is posted after the pick", () => { + const { port, onDoublePress } = openPort(); + + port.onMessage.dispatch("pickedItem"); + port.onMessage.dispatch({ message: "menuKey", type: "keyup", key: "Enter" }); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + it("is still one when the page only posted something else", () => { + const { port, onDoublePress } = openPort(); + + port.onMessage.dispatch({ message: "menuKey", type: "keydown", key: "Alt" }); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).toHaveBeenCalledOnce(); + }); + + it("isn't one once it's been open longer than a double-press takes", () => { + const { port, onDoublePress } = openPort(); + + vi.advanceTimersByTime(MaxPopupLifetime + 50); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + // sw.js caches a connect that arrives while the worker is starting, and + // replays it once the worker has loaded, saying when it really arrived + it("counts from when the menu opened, not from when a slow worker start replayed it", () => { + globalThis.replayedEventTime = Date.now() - 1500; + + const { port, onDoublePress } = openPort(); + + globalThis.replayedEventTime = undefined; + vi.advanceTimersByTime(MaxPopupLifetime - 50); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + it("is still one for a replayed menu that closes soon after it really opened", () => { + globalThis.replayedEventTime = Date.now() - 100; + + const { port, onDoublePress } = openPort(); + + globalThis.replayedEventTime = undefined; + vi.advanceTimersByTime(200); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).toHaveBeenCalledOnce(); + }); +}); + + + // the port doesn't close until the menu's page has gone, which is some + // time after the second press, and longer the busier the page is. so + // when the page saw the press, the time the key went down decides it. +describe("a menu whose page reports a second press of its shortcut", () => { + function openMenu( + getShortcut = () => Promise.resolve(AltE)) + { + const port = chrome.runtime.connect(); + const onDoublePress = vi.fn(); + + watchForDoublePress(port, onDoublePress, getShortcut); + + return { port, onDoublePress }; + } + + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("is a double-press however long the page then takes to go away", async () => { + const { port, onDoublePress } = openMenu(); + + port.onMessage.dispatch(keyDown(MaxPressGap - 50)); + vi.advanceTimersByTime(MaxPopupLifetime + 2000); + port.onDisconnect.dispatch(port); + await settle(); + + expect(onDoublePress).toHaveBeenCalledExactlyOnceWith({ pressTime: MaxPressGap - 50 }); + }); + + it("isn't one when the press came too late, even if the port closed in time", async () => { + const { port, onDoublePress } = openMenu(); + + port.onMessage.dispatch(keyDown(MaxPressGap + 50)); + vi.advanceTimersByTime(MaxPopupLifetime - 50); + port.onDisconnect.dispatch(port); + await settle(); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + it("isn't one when the user then picked an item", async () => { + const { port, onDoublePress } = openMenu(); + + port.onMessage.dispatch(keyDown(100)); + port.onMessage.dispatch("pickedItem"); + port.onDisconnect.dispatch(port); + await settle(); + + expect(onDoublePress).not.toHaveBeenCalled(); + }); + + // the page only has focus for some of the presses, and what it posts + // before a new worker is listening is lost + it("goes by how long the port was open when the page reported nothing", () => { + const { port, onDoublePress } = openMenu(); + + vi.advanceTimersByTime(MaxPopupLifetime - 50); + port.onDisconnect.dispatch(port); + + expect(onDoublePress).toHaveBeenCalledExactlyOnceWith({ lifetime: MaxPopupLifetime - 50 }); + }); + + it("goes by how long the port was open when the keys it reported weren't the shortcut", async () => { + const quick = openMenu(); + + // the first press's modifier is still down, and alt-W moves the + // selection in the menu + quick.port.onMessage.dispatch(keyDown(80, { key: "w", code: "KeyW" })); + quick.port.onMessage.dispatch({ ...keyDown(60), type: "keyup" }); + vi.advanceTimersByTime(MaxPopupLifetime - 50); + quick.port.onDisconnect.dispatch(quick.port); + await settle(); + + expect(quick.onDoublePress).toHaveBeenCalledOnce(); + + const slow = openMenu(); + + slow.port.onMessage.dispatch(keyDown(80, { key: "w", code: "KeyW" })); + vi.advanceTimersByTime(MaxPopupLifetime + 50); + slow.port.onDisconnect.dispatch(slow.port); + await settle(); + + expect(slow.onDoublePress).not.toHaveBeenCalled(); + }); + + it("goes by how long the port was open when Chrome doesn't give the shortcut", async () => { + const failed = openMenu(() => Promise.reject(new Error("no shortcuts for you"))); + + failed.port.onMessage.dispatch(keyDown(100)); + vi.advanceTimersByTime(MaxPopupLifetime - 50); + failed.port.onDisconnect.dispatch(failed.port); + await settle(); + + expect(failed.onDoublePress).toHaveBeenCalledOnce(); + + // Chrome sometimes returns the command without its shortcut + const missing = openMenu(() => Promise.resolve({ id: "_execute_action", baseKey: "", modifiers: [] })); + + missing.port.onMessage.dispatch(keyDown(100)); + vi.advanceTimersByTime(MaxPopupLifetime + 50); + missing.port.onDisconnect.dispatch(missing.port); + await settle(); + + expect(missing.onDoublePress).not.toHaveBeenCalled(); + }); + + it("asks for the shortcut when the menu opens, without waiting for it to close", async () => { + const getShortcut = vi.fn(() => Promise.resolve(AltE)); + + openMenu(getShortcut); + await settle(); + + expect(getShortcut).toHaveBeenCalledOnce(); + }); +}); + + +describe("matching a reported key to the menu's shortcut", () => { + it("needs the same key and exactly the same modifiers", () => { + expect(isShortcutKey(keyDown(0), AltE)).toBe(true); + expect(isShortcutKey(keyDown(0, { key: "w", code: "KeyW" }), AltE)).toBe(false); + expect(isShortcutKey(keyDown(0, { altKey: false }), AltE)).toBe(false); + expect(isShortcutKey(keyDown(0, { shiftKey: true }), AltE)).toBe(false); + expect(isShortcutKey(keyDown(0, { key: "Alt", code: "AltLeft" }), AltE)).toBe(false); + }); + + it("ignores a key coming up, or repeating because it's held down", () => { + expect(isShortcutKey({ ...keyDown(0), type: "keyup" }, AltE)).toBe(false); + expect(isShortcutKey(keyDown(0, { repeat: true }), AltE)).toBe(false); + }); + + it("goes by the key's position when a modifier changes its character", () => { + const ctrlShift1 = { baseKey: "1", modifiers: ["ctrl", "shift"] }; + const optE = { baseKey: "e", modifiers: ["opt"] }; + + expect(isShortcutKey(keyDown(0, { + key: "!", code: "Digit1", altKey: false, ctrlKey: true, shiftKey: true + }), ctrlShift1)).toBe(true); + // opt-E on a Mac starts an accent + expect(isShortcutKey(keyDown(0, { key: "Dead" }), optE)).toBe(true); + expect(isShortcutKey(keyDown(0, { key: "E", shiftKey: true }), + { baseKey: "e", modifiers: ["alt", "shift"] })).toBe(true); + }); + + it("knows the Mac's command key and keys Chrome names differently", () => { + expect(isShortcutKey(keyDown(0, { + key: " ", code: "Space", altKey: false, metaKey: true + }), { baseKey: "space", modifiers: ["cmd"] })).toBe(true); + expect(isShortcutKey(keyDown(0, { + key: ",", code: "Comma" + }), { baseKey: ",", modifiers: ["alt"] })).toBe(true); + expect(isShortcutKey(keyDown(0, { + key: "ArrowLeft", code: "ArrowLeft" + }), { baseKey: "arrowleft", modifiers: ["alt"] })).toBe(true); + }); + + it("matches nothing when there's no shortcut, or a modifier it doesn't know", () => { + expect(isShortcutKey(keyDown(0), undefined)).toBe(false); + expect(isShortcutKey(keyDown(0), { baseKey: "", modifiers: [] })).toBe(false); + expect(isShortcutKey(keyDown(0), { baseKey: "e", modifiers: ["alt", "hyper"] })).toBe(false); + }); +}); diff --git a/test/unit/menu-double-press.test.js b/test/unit/menu-double-press.test.js index d239c8d1..94444f4d 100644 --- a/test/unit/menu-double-press.test.js +++ b/test/unit/menu-double-press.test.js @@ -2,11 +2,11 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { toggleRecentTabs } from "@/shared/commandHandlers"; - // the background treats a menu that closes within MaxPopupLifetime of - // opening as a double-press of its shortcut, and toggles to the previous - // tab. a tab picked that quickly closed the menu just as fast, so the - // background switched to the picked tab and then straight back. the menu - // now says when it's closing because of something the user did in it. + // background.js toggles to the previous tab when the popup window or the + // toolbar menu is closed by a second press of the shortcut that opened + // it. the worker does that whether or not it has control. see + // double-press.test.js for what counts as a double-press, and + // worker-popup-control.test.js for a toggle in a worker without control. // // only the port handling in background.js is under test, so everything // else it starts up is stubbed out. @@ -21,15 +21,49 @@ vi.mock("@/background/toolbar-icon", () => ({ default: {} })); vi.mock("@/background/check-menu-pick", () => ({ default: vi.fn(() => Promise.resolve(null)), })); +vi.mock("@/background/get-chrome-shortcuts", () => ({ + default: vi.fn(() => Promise.resolve([ + { id: "010-open-popup-window", baseKey: "q", modifiers: ["alt"] }, + { id: "_execute_action", baseKey: "e", modifiers: ["alt"] }, + ])), +})); const MaxPopupLifetime = 450; +const MaxPressGap = 500; + + + // what the menu's page posts when a key goes down with alt held +function altKeyDown( + key, + time) +{ + return { + message: "menuKey", + type: "keydown", + key, + code: `Key${key.toUpperCase()}`, + repeat: false, + altKey: true, + ctrlKey: false, + shiftKey: false, + metaKey: false, + time, + }; +} + + // several macrotasks, so the lookup of the menu's shortcut settles +function flush() +{ + return vi.advanceTimersByTimeAsync(0); +} function openPort( - name) + name, + props = {}) { - const port = chrome.runtime.connect(); + const port = Object.assign(chrome.runtime.connect(), props); port.name = name; chrome.runtime.onConnect.dispatch(port); @@ -38,7 +72,9 @@ function openPort( } -describe("a menu that closes soon after opening", () => { + // each test's import of background.js adds another listener to the same + // fake event, so the tests can't count the calls +describe("a port that closes soon after background.js sees it open", () => { beforeEach(async () => { vi.useFakeTimers(); vi.clearAllMocks(); @@ -51,120 +87,131 @@ describe("a menu that closes soon after opening", () => { vi.useRealTimers(); }); - it("toggles tabs when it closes without a word, since that's a double-press", () => { - const port = openPort("menu"); + it("toggles tabs when it's the popup window's, since that's a double-press", () => { + const port = openPort("popup"); vi.advanceTimersByTime(MaxPopupLifetime - 50); port.onDisconnect.dispatch(port); - expect(toggleRecentTabs).toHaveBeenCalledOnce(); + expect(toggleRecentTabs).toHaveBeenCalled(); }); - it("doesn't toggle when it said the user picked an item", () => { - const port = openPort("menu"); + it("doesn't toggle once the popup window has been open longer than a double-press takes", () => { + const port = openPort("popup"); - vi.advanceTimersByTime(MaxPopupLifetime - 50); - port.onMessage.dispatch("pickedItem"); + vi.advanceTimersByTime(MaxPopupLifetime + 50); port.onDisconnect.dispatch(port); expect(toggleRecentTabs).not.toHaveBeenCalled(); }); - it("doesn't toggle when it said which tab the user picked", () => { - const port = openPort("menu"); + // the worker makes this port for itself at startup when the popup + // window is already open. it drops right away if the window was + // closing, which isn't the user pressing anything. + it("doesn't toggle when it's the worker's stand-in for the popup window's port", () => { + const port = openPort("popup", { isStandIn: true }); - port.onMessage.dispatch({ message: "pickedItem", tabID: 2 }); port.onDisconnect.dispatch(port); expect(toggleRecentTabs).not.toHaveBeenCalled(); }); - it("starts watching for the switch as soon as the menu says what it picked", async () => { - const { default: checkMenuPick } = await import("@/background/check-menu-pick"); + it("toggles tabs when it's the menu's and the page never said why it closed", async () => { const port = openPort("menu"); - port.onMessage.dispatch({ message: "pickedItem", tabID: 2 }); + vi.advanceTimersByTime(MaxPopupLifetime - 50); + port.onDisconnect.dispatch(port); + await flush(); - // before the menu has gone, since the switch happens while it's - // closing. each test's import of background.js adds another - // onConnect listener to the same fake, so don't count the calls. - expect(checkMenuPick).toHaveBeenCalledWith( - expect.objectContaining({ tabID: 2 }), expect.anything()); + expect(toggleRecentTabs).toHaveBeenCalled(); + }); - const calls = checkMenuPick.mock.calls.length; + it("doesn't toggle when the menu was open longer than that and reported no press", async () => { + const port = openPort("menu"); - // closeWindow() follows the tab's ID with a plain pickedItem, - // which mustn't start another watch, and nor must the disconnect - port.onMessage.dispatch("pickedItem"); + vi.advanceTimersByTime(MaxPopupLifetime + 50); port.onDisconnect.dispatch(port); + await flush(); - expect(checkMenuPick).toHaveBeenCalledTimes(calls); + expect(toggleRecentTabs).not.toHaveBeenCalled(); }); - it("doesn't check anything when the menu closes without a pick", async () => { - const { default: checkMenuPick } = await import("@/background/check-menu-pick"); + // the page keeps running for a while after the second press, so the + // port can close well after MaxPopupLifetime + it("toggles when the menu reported a second press of its shortcut, however late the port closes", async () => { const port = openPort("menu"); - port.onMessage.dispatch("closedByEsc"); + port.onMessage.dispatch(altKeyDown("e", MaxPressGap - 50)); + vi.advanceTimersByTime(MaxPopupLifetime + 500); port.onDisconnect.dispatch(port); + await flush(); - expect(checkMenuPick).not.toHaveBeenCalled(); + expect(toggleRecentTabs).toHaveBeenCalled(); }); - it("doesn't toggle when it said it was closed by esc", () => { + it("doesn't toggle when the second press came too long after the menu opened", async () => { const port = openPort("menu"); - port.onMessage.dispatch("closedByEsc"); + port.onMessage.dispatch(altKeyDown("e", MaxPressGap + 50)); + vi.advanceTimersByTime(MaxPopupLifetime - 50); port.onDisconnect.dispatch(port); + await flush(); expect(toggleRecentTabs).not.toHaveBeenCalled(); }); - it("doesn't toggle when esc is followed by the menu's own close", () => { + // alt-Q is the popup window's shortcut, not the menu's + it("doesn't take another shortcut's key for a second press of the menu's", async () => { const port = openPort("menu"); - // closeWindow() posts both when the menu is closed by esc - port.onMessage.dispatch("closedByEsc"); - port.onMessage.dispatch("pickedItem"); + port.onMessage.dispatch(altKeyDown("q", MaxPressGap - 50)); + vi.advanceTimersByTime(MaxPopupLifetime + 500); port.onDisconnect.dispatch(port); + await flush(); expect(toggleRecentTabs).not.toHaveBeenCalled(); }); - it("doesn't toggle once it's been open longer than a double-press takes", () => { + it("doesn't toggle when the menu reported a press and then a pick", async () => { const port = openPort("menu"); - vi.advanceTimersByTime(MaxPopupLifetime + 50); + port.onMessage.dispatch(altKeyDown("e", MaxPressGap - 50)); + port.onMessage.dispatch({ message: "pickedItem", tabID: 2 }); port.onDisconnect.dispatch(port); + await flush(); expect(toggleRecentTabs).not.toHaveBeenCalled(); }); - // sw.js caches a connect that arrives while the worker is starting, and - // replays it once the worker has loaded, saying when it really arrived - it("counts from when the menu opened, not from when a slow worker start replayed it", () => { - globalThis.replayedEventTime = Date.now() - 1500; - + it("starts watching for the switch as soon as the menu says what it picked", async () => { + const { default: checkMenuPick } = await import("@/background/check-menu-pick"); const port = openPort("menu"); - globalThis.replayedEventTime = undefined; - vi.advanceTimersByTime(MaxPopupLifetime - 50); + port.onMessage.dispatch({ message: "pickedItem", tabID: 2 }); + + // before the menu has gone, since the switch happens while it's + // closing. each test's import of background.js adds another + // onConnect listener to the same fake, so don't count the calls. + expect(checkMenuPick).toHaveBeenCalledWith( + expect.objectContaining({ tabID: 2 }), expect.anything()); + + const calls = checkMenuPick.mock.calls.length; + + // closeWindow() follows the tab's ID with a plain pickedItem, + // which mustn't start another watch, and nor must the disconnect + port.onMessage.dispatch("pickedItem"); port.onDisconnect.dispatch(port); - expect(toggleRecentTabs).not.toHaveBeenCalled(); + expect(checkMenuPick).toHaveBeenCalledTimes(calls); }); - it("still toggles for a replayed menu that closes soon after it really opened", () => { - globalThis.replayedEventTime = Date.now() - 100; - + it("doesn't check anything when the menu closes without a pick", async () => { + const { default: checkMenuPick } = await import("@/background/check-menu-pick"); const port = openPort("menu"); - globalThis.replayedEventTime = undefined; - vi.advanceTimersByTime(200); + port.onMessage.dispatch("closedByEsc"); port.onDisconnect.dispatch(port); - // each test's import of background.js adds another listener to the - // same fake event, so don't count the calls - expect(toggleRecentTabs).toHaveBeenCalled(); + expect(checkMenuPick).not.toHaveBeenCalled(); }); }); diff --git a/test/unit/sw-closed-port.test.js b/test/unit/sw-closed-port.test.js index 38bb337d..e4cb1365 100644 --- a/test/unit/sw-closed-port.test.js +++ b/test/unit/sw-closed-port.test.js @@ -100,4 +100,55 @@ describe("sw.js replaying port connections", () => { Date.now.mockRestore(); void popupPort; }); + + // the menu's page reports a second press of its shortcut on its port. + // when that double-press is what started the worker, the report comes + // before background.js has a listener on the port. + it("hands a replayed port's listeners what the page posted while the worker was starting", async () => { + const heard = []; + let finishLoading; + + importScripts.mockImplementation(() => { + finishLoading = () => { + chrome.runtime.onConnect.addListener((port) => { + heard.push(["connect", port.name]); + port.onMessage.addListener((message, sender) => + heard.push([port.name, message, sender === port])); + }); + globalThis.backgroundLoaded(); + }; + }); + + vi.resetModules(); + await import("@/background/sw"); + + const menuPort = connect("menu"); + const closedPort = connect("popup"); + + menuPort.onMessage.dispatch({ message: "menuKey", key: "Alt" }, menuPort); + menuPort.onMessage.dispatch({ message: "menuKey", key: "e" }, menuPort); + closedPort.onMessage.dispatch("pickedItem", closedPort); + closedPort.onDisconnect.dispatch(closedPort); + + expect(heard).toEqual([]); + + finishLoading(); + + // in the order they were posted, after the port's own connect, and + // nothing for the port that had closed + expect(heard).toEqual([ + ["connect", "menu"], + ["menu", { message: "menuKey", key: "Alt" }, true], + ["menu", { message: "menuKey", key: "e" }, true], + ]); + + // from here on the page's messages go straight to the listeners, + // once each + menuPort.onMessage.dispatch("pickedItem", menuPort); + + expect(heard.at(-1)).toEqual(["menu", "pickedItem", true]); + expect(heard).toHaveLength(4); + expect(menuPort.onMessage.listenerCount()).toBe(1); + expect(closedPort.onMessage.listenerCount()).toBe(0); + }); }); diff --git a/test/unit/worker-popup-control.test.js b/test/unit/worker-popup-control.test.js index 33c735c2..c69961d9 100644 --- a/test/unit/worker-popup-control.test.js +++ b/test/unit/worker-popup-control.test.js @@ -76,13 +76,31 @@ function loadContext( const initEventController = (await import("@/shared/eventController")).default; const control = (await import("@/shared/control")).default; const state = (await import("@/shared/state")).default; + const recentTabs = (await import("@/background/recent-tabs")).default; + const { toggleRecentTabs } = await import("@/shared/commandHandlers"); const sendPopupMessage = vi.fn(); const sendMessage = initEventController({ sendPopupMessage, ports: {} }); - return { control, state, sendMessage, sendPopupMessage }; + return { control, state, recentTabs, toggleRecentTabs, sendMessage, sendPopupMessage }; }); } + // a minimal stand-in for the port the menu connects when it opens. + // disconnect() fires the onDisconnect listeners, like the real port + // does in every other context when the menu closes. +function makeMenuPort() +{ + const disconnectListeners = new Set(); + + return { + name: "menu", + postMessage: () => {}, + onMessage: { addListener: () => {} }, + onDisconnect: { addListener: (fn) => disconnectListeners.add(fn) }, + disconnect: () => disconnectListeners.forEach((fn) => fn()), + }; +} + beforeEach(() => { // the vi.mock factories above run once for the whole file, so the mock @@ -354,22 +372,6 @@ describe("toolbar menu open", () => { }); } - // a minimal stand-in for the port the menu connects when it opens. - // disconnect() fires the onDisconnect listeners, like the real port - // does in every other context when the menu closes. - function makeMenuPort() - { - const disconnectListeners = new Set(); - - return { - name: "menu", - postMessage: () => {}, - onMessage: { addListener: () => {} }, - onDisconnect: { addListener: (fn) => disconnectListeners.add(fn) }, - disconnect: () => disconnectListeners.forEach((fn) => fn()), - }; - } - it("the worker ignores commands while the menu is open, and handles them again after it closes", async () => { const worker = await loadContext("/background.html"); @@ -496,3 +498,110 @@ describe("toolbar menu open", () => { expect(popupWindow.create).toHaveBeenCalledTimes(1); }); }); + + + // a second press of the menu's shortcut closes the menu right after it + // opened, and background.js takes that for a double-press and toggles to + // the previous tab. only the worker loads background.js, so the worker + // toggles even when the popup window's page has control and is the one + // getting the tab events. menu-double-press.test.js covers background.js + // deciding to toggle. these cover the toggle in a worker without control. +describe("a toggle from a double-press of the menu's shortcut", () => { + // the popup page has control, and the menu connecting has started a + // new worker, which waits behind the page + async function loadWaitingWorker() + { + const oldWorker = await loadContext("/background.html"); + + await flush(); + + const popup = await loadContext("/popup.html"); + + await flush(); + oldWorker.destroy(); + await flush(); + + const worker = await loadContext("/background.html"); + + await flush(); + + expect(popup.modules.control.isHeld()).toBe(true); + expect(worker.modules.control.isHeld()).toBe(false); + + return { worker, popup }; + } + + it("a worker with control goes by the tab events it's had, without asking for the active tab", async () => { + const worker = await loadContext("/background.html"); + + await flush(); + + // say nothing was switched to, so it doesn't wait for an activation + const toggle = vi.spyOn(worker.modules.recentTabs, "toggle").mockResolvedValue(false); + const query = vi.spyOn(chrome.tabs, "query"); + + worker.modules.toggleRecentTabs(); + await flush(); + + expect(toggle).toHaveBeenCalledExactlyOnceWith(false, null); + expect(query).not.toHaveBeenCalled(); + }); + + // the tab events go to the popup page, so the worker has no pending + // add of the current tab to flush, and the page's can be more than a + // second behind + it("a worker without control adds the tab that's active now before it switches", async () => { + const { worker } = await loadWaitingWorker(); + const toggle = vi.spyOn(worker.modules.recentTabs, "toggle").mockResolvedValue(false); + + worker.modules.toggleRecentTabs(); + await flush(); + + expect(toggle).toHaveBeenCalledExactlyOnceWith(false, expect.objectContaining({ id: 1 })); + }); + + // it used to wait a full second for an activation that only the popup + // page saw, holding up the next toggle + it("a worker without control doesn't wait for the activation, so the next toggle isn't held up", async () => { + const { worker } = await loadWaitingWorker(); + const toggle = vi.spyOn(worker.modules.recentTabs, "toggle").mockResolvedValue(true); + + worker.modules.toggleRecentTabs(); + await flush(); + worker.modules.toggleRecentTabs(); + await flush(); + + expect(toggle).toHaveBeenCalledTimes(2); + }); + + it("a worker without control still toggles if it can't get the active tab", async () => { + const { worker } = await loadWaitingWorker(); + const toggle = vi.spyOn(worker.modules.recentTabs, "toggle").mockResolvedValue(false); + + vi.spyOn(chrome.tabs, "query").mockRejectedValue(new Error("no tabs for you")); + + worker.modules.toggleRecentTabs(); + await flush(); + + expect(toggle).toHaveBeenCalledExactlyOnceWith(false, null); + }); + + // commandHandlers.js runs in both contexts and briefly did the + // toggling itself, in whichever one had control. but the popup page + // could hear the menu's port close 100-200 ms after the worker did, + // which put some double-presses over the time limit. + it("the menu's port closing doesn't toggle in the popup page, even when it has control", async () => { + const { worker, popup } = await loadWaitingWorker(); + const workerToggle = vi.spyOn(worker.modules.recentTabs, "toggle").mockResolvedValue(false); + const popupToggle = vi.spyOn(popup.modules.recentTabs, "toggle").mockResolvedValue(false); + const menuPort = makeMenuPort(); + + chrome.runtime.onConnect.dispatch(menuPort); + menuPort.disconnect(); + await flush(); + + expect(popupToggle).not.toHaveBeenCalled(); + // nor here, since these contexts don't load background.js + expect(workerToggle).not.toHaveBeenCalled(); + }); +}); diff --git a/vitest.config.js b/vitest.config.js index b892b2c2..eca3edd0 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -10,6 +10,8 @@ export default defineConfig({ "@": resolve(__dirname, "src/js"), lodash: resolve(__dirname, "src/js/lib/lodont"), cp: resolve(__dirname, "src/js/lib/cp"), + // a file: dependency on a sibling checkout, which CI doesn't have + "stdout-ext": resolve(__dirname, "test/support/stdout-ext.js"), }, }, test: {