BlueGit

timfa questward

Files

questward / client / src / play / contextMenu.js

contextMenu.js

contextMenu.js 1.6 KiB Download Raw
1export function initContextMenu ({ root = document.body, onSuppressWorldClick } = {})
2{
3 const menu = document.createElement("div");
4 menu.id = "context-menu";
5 menu.hidden = true;
6 root.append(menu);
7
8 function suppressWorldClick ()
9 {
10 onSuppressWorldClick?.();
11 }
12
13 function hide ()
14 {
15 menu.hidden = true;
16 menu.replaceChildren();
17 }
18
19 document.addEventListener("mousedown", (event) =>
20 {
21 if (!menu.hidden && !menu.contains(event.target))
22 { hide(); }
23 });
24
25 window.addEventListener("blur", hide);
26 window.addEventListener("resize", hide);
27
28 return {
29 hide,
30 isOpen: () => !menu.hidden,
31 show (clientX, clientY, items)
32 {
33 menu.replaceChildren();
34 for (const item of items)
35 {
36 const button = document.createElement("button");
37 button.type = "button";
38 button.textContent = item.label;
39 button.addEventListener("mousedown", (event) =>
40 {
41 // Consume before the menu closes so the held button does not become a world LMB.
42 event.preventDefault();
43 event.stopPropagation();
44 suppressWorldClick();
45 });
46 button.addEventListener("click", (event) =>
47 {
48 event.preventDefault();
49 event.stopPropagation();
50 suppressWorldClick();
51 hide();
52 item.onSelect?.();
53 });
54 menu.append(button);
55 }
56 menu.hidden = false;
57 const pad = 8;
58 const width = menu.offsetWidth || 160;
59 const height = menu.offsetHeight || 80;
60 const left = Math.min(window.innerWidth - width - pad, Math.max(pad, clientX));
61 const top = Math.min(window.innerHeight - height - pad, Math.max(pad, clientY));
62 menu.style.left = `${left}px`;
63 menu.style.top = `${top}px`;
64 }
65 };
66}