(() => { document.querySelectorAll(".hy-menu").forEach((menu, index) => { if (menu.dataset.ready === "true") return; menu.dataset.ready = "true"; const button = menu.querySelector(".hy-menu__button"); const backdrop = menu.querySelector(".hy-menu__backdrop"); const panel = menu.querySelector(".hy-menu__panel"); const links = panel.querySelectorAll("a[href]"); const panelId = `hy-menu-panel-${index + 1}`; panel.id = panelId; button.setAttribute("aria-controls", panelId); const setOpen = (open, returnFocus = false) => { menu.classList.toggle("is-open", open); backdrop.hidden = !open; panel.hidden = !open; button.setAttribute("aria-expanded", String(open)); button.setAttribute("aria-label", open ? "メニューを閉じる" : "メニューを開く"); if (open) { requestAnimationFrame(() => panel.querySelector("a[href]")?.focus()); } else if (returnFocus) { button.focus(); } }; button.addEventListener("click", () => { setOpen(button.getAttribute("aria-expanded") !== "true"); }); links.forEach((link) => link.addEventListener("click", () => setOpen(false))); backdrop.addEventListener("click", () => setOpen(false, true)); document.addEventListener("pointerdown", (event) => { if (button.getAttribute("aria-expanded") === "true" && !menu.contains(event.target)) { setOpen(false); } }); document.addEventListener("keydown", (event) => { if (event.key === "Escape" && button.getAttribute("aria-expanded") === "true") { setOpen(false, true); } }); }); })();