Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

contextMenuSource.ts

38 lines1.6 KB

1import type { ContextMenuSource } from "@t3tools/contracts";
2​
3// Menus opened by openContextMenuFromKeyboard; a script-made event cannot keep button -1.
4const keyboardContextMenus = new WeakSet<Event>();
5​
6// Chromium uses no button for keyboard context menus and zero clicks for keyboard activation.
7export function contextMenuSourceOf(
8 event: Pick<MouseEvent, "type" | "button" | "detail"> & { readonly nativeEvent?: Event },
9): ContextMenuSource {
10 if (event.nativeEvent !== undefined && keyboardContextMenus.has(event.nativeEvent)) {
11 return "keyboard";
12 }
13 return (event.type === "click" ? event.detail === 0 : event.button === -1) ? "keyboard" : "mouse";
15​
16/**
17 * Opens an element's context menu from the keyboard. Chromium on macOS turns neither
18 * Shift+F10 nor the ContextMenu key into a `contextmenu` event, so the key is handled
19 * here and the element's own handler receives a menu event that reads as keyboard-opened.
20 * Preventing the key keeps other platforms from opening the menu a second time.
21 */
22export function openContextMenuFromKeyboard(
23 event: Pick<KeyboardEvent, "key" | "shiftKey" | "preventDefault"> & {
24 readonly currentTarget: Element;
25 },
26): void {
27 if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
28 event.preventDefault();
29 const bounds = event.currentTarget.getBoundingClientRect();
30 const menu = new MouseEvent("contextmenu", {
31 bubbles: true,
32 cancelable: true,
33 clientX: bounds.left,
34 clientY: bounds.bottom,
35 });
36 keyboardContextMenus.add(menu);
37 event.currentTarget.dispatchEvent(menu);