Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions apps/web/src/contextMenuFallback.keyboard.browser.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, it } from "vite-plus/test";
import { userEvent } from "vite-plus/test/browser";
import {
dismissContextMenu,
isContextMenuOpen,
Expand Down Expand Up @@ -104,3 +105,20 @@ it("closes without taking focus back when focus moves elsewhere", async () => {
await expect(result).resolves.toBeNull();
expect(document.activeElement).toBe(destination);
});

it("closes on a press at its opener without the press reopening it", async () => {
using fixture = setup();
let opens = 0;
fixture.origin.addEventListener("click", () => {
opens += 1;
void showContextMenuFallback(items, { x: 300, y: 300 });
});
await userEvent.click(fixture.origin);
expect(isContextMenuOpen()).toBe(true);
await userEvent.click(fixture.origin);
expect(isContextMenuOpen()).toBe(false);
expect(opens).toBe(1);
await userEvent.click(fixture.origin);
expect(isContextMenuOpen()).toBe(true);
expect(opens).toBe(2);
});
18 changes: 18 additions & 0 deletions apps/web/src/contextMenuFallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,23 @@ function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly H
return false;
}

const PRESS_ACTIVATION_EVENTS = ["click", "auxclick", "dblclick"] as const;

function swallowPressActivation() {
const swallow = (event: Event) => {
event.preventDefault();
event.stopPropagation();
};
const release = () => {
for (const type of PRESS_ACTIVATION_EVENTS) document.removeEventListener(type, swallow, true);
document.removeEventListener("pointerdown", release, true);
document.removeEventListener("keydown", release, true);
};
for (const type of PRESS_ACTIVATION_EVENTS) document.addEventListener(type, swallow, true);
document.addEventListener("pointerdown", release, true);
document.addEventListener("keydown", release, true);
}

let activeContextMenuDismiss: ((restoreFocus?: boolean) => void) | null = null;

export function isContextMenuOpen(): boolean {
Expand Down Expand Up @@ -358,6 +375,7 @@ export function showContextMenuFallback<T extends string>(
if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
return;
}
swallowPressActivation();
cleanup(null);
};

Expand Down
Loading