Skip to content

Commit

Permalink
Merge pull request #356 from nileshbhagwat/fix/355
Browse files Browse the repository at this point in the history
fix: prevent menu toggle on right-click (#355)
  • Loading branch information
NickDJM authored Oct 28, 2024
2 parents 3b4d5fb + 8882158 commit eb9c3a4
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/_baseMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -1407,6 +1407,10 @@ class BaseMenu {
function toggleToggle(menu, toggle, event) {
preventEvent(event);

if (event.button !== 0) {
return;
}

toggle.toggle();

if (toggle.isOpen) {
Expand Down
42 changes: 42 additions & 0 deletions tests/menus/_baseMenu/click.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,5 +312,47 @@ describe("BaseMenu", () => {

expect(menu.focusState).toBe("none");
});

// Test that pointerup does not toggle submenu when event.button is not 0.
it("should not toggle submenu when event.button is not 0", () => {
// Create a new BaseMenu instance for testing.
const menu = new BaseMenu({
menuElement: document.querySelector("ul"),
containerElement: document.querySelector("nav"),
controllerElement: document.querySelector("button"),
});
initializeMenu(menu);

// Spy on toggle.
const spy = vi.spyOn(menu.elements.controller, "toggle");

// Simulate a pointerup event with button property set to 1.
simulatePointerEvent("pointerup", menu.elements.controller.dom.toggle, {
button: 1,
});

expect(spy).not.toHaveBeenCalled();
});

// Test that pointerup toggles submenu when event.button is 0.
it("should toggle submenu when event.button is 0", () => {
// Create a new BaseMenu instance for testing.
const menu = new BaseMenu({
menuElement: document.querySelector("ul"),
containerElement: document.querySelector("nav"),
controllerElement: document.querySelector("button"),
});
initializeMenu(menu);

// Spy on toggle.
const spy = vi.spyOn(menu.elements.controller, "toggle");

// Simulate a pointerup event with button property set to 0.
simulatePointerEvent("pointerup", menu.elements.controller.dom.toggle, {
button: 0,
});

expect(spy).toHaveBeenCalled();
});
});
});
9 changes: 8 additions & 1 deletion tests/menus/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,15 @@ export function simulatePointerEvent(eventType, element, options = {}) {
const event = new PointerEvent(eventType, {
bubbles: true,
cancelable: true,
...options,
});

// Manually assign read-only properties after the event is created
Object.keys(options).forEach((key) => {
if (key in event) {
Object.defineProperty(event, key, { value: options[key] });
}
});

element.dispatchEvent(event);
return event;
} catch (error) {
Expand Down

0 comments on commit eb9c3a4

Please sign in to comment.