const anchor = element.querySelector(".help-anchor"); const tooltip = element.querySelector(".help-tooltip"); if (anchor && tooltip && typeof tooltip.showPopover === "function") { // The browser top layer avoids clipping, while the component's shadow root // preserves its scoped styles. A native title is the fallback in older browsers. anchor.removeAttribute("title"); let viewportEvents = null; const hide = () => { if (tooltip.matches(":popover-open")) tooltip.hidePopover(); viewportEvents?.abort(); viewportEvents = null; }; const show = () => { if (!tooltip.isConnected || !anchor.isConnected) return; if (!tooltip.matches(":popover-open")) tooltip.showPopover(); const rect = anchor.getBoundingClientRect(); const bounds = tooltip.getBoundingClientRect(); const margin = 16; let top = rect.top - bounds.height - 10; if (top < margin) top = rect.bottom + 10; tooltip.style.left = `${Math.max(margin, Math.min(rect.left - 24, innerWidth - bounds.width - margin))}px`; tooltip.style.top = `${Math.max(margin, Math.min(top, innerHeight - bounds.height - margin))}px`; if (!viewportEvents) { viewportEvents = new AbortController(); const options = {capture: true, signal: viewportEvents.signal}; window.addEventListener("scroll", hide, options); window.addEventListener("resize", hide, options); } }; anchor.addEventListener("mouseenter", show); anchor.addEventListener("mouseleave", () => { if (!anchor.matches(":focus-visible")) hide(); }); anchor.addEventListener("focus", show); anchor.addEventListener("blur", hide); anchor.addEventListener("keydown", (event) => { if (event.key === "Escape") hide(); }); }