agahnim.dev/static/contextmenu.js
2026-05-16 22:58:29 +02:00

53 lines
1.2 KiB
JavaScript

(function () {
const menu = document.createElement("helo");
menu.innerHTML = `
<helo-content>
<img src="/static/assets/gifs/helo.gif"/>
</helo-content>
`;
menu.style.display = "none";
function ensureMenu() {
if (!document.body.contains(menu)) {
document.body.appendChild(menu);
}
}
const showMenu = (x, y) => {
ensureMenu();
menu.style.display = "block";
menu.style.left = `${x}px`;
menu.style.top = `${y}px`;
const rect = menu.getBoundingClientRect();
if (x + rect.width > window.innerWidth) {
menu.style.left = `${window.innerWidth - rect.width - 10}px`;
}
if (y + rect.height > window.innerHeight) {
menu.style.top = `${window.innerHeight - rect.height - 10}px`;
}
};
const hideMenu = () => {
menu.style.display = "none";
};
document.addEventListener("contextmenu", (e) => {
e.preventDefault();
showMenu(e.clientX, e.clientY);
});
document.addEventListener("click", hideMenu);
document.addEventListener("scroll", hideMenu);
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") hideMenu();
});
document.body.addEventListener("htmx:historyRestore", ensureMenu);
})();