UNPKG

@loke/ui

Version:
38 lines (37 loc) • 1.27 kB
// src/lib/focus-guards/focus-guards.tsx import { useEffect } from "react"; var count = 0, guards = null; function FocusGuards(props) { return useFocusGuards(), props.children; } function useFocusGuards() { useEffect(() => { if (!guards) { let existing = document.querySelectorAll("[data-loke-focus-guard]"); guards = { end: existing[1] ?? createFocusGuard(), start: existing[0] ?? createFocusGuard() }; } let { end, start } = guards; if (document.body.firstElementChild !== start) document.body.insertAdjacentElement("afterbegin", start); if (document.body.lastElementChild !== end) document.body.insertAdjacentElement("beforeend", end); return count++, () => { if (count === 1) guards?.start.remove(), guards?.end.remove(), guards = null; count = Math.max(0, count - 1); }; }, []); } function createFocusGuard() { let element = document.createElement("span"); return element.setAttribute("data-loke-focus-guard", ""), element.tabIndex = 0, element.style.outline = "none", element.style.opacity = "0", element.style.position = "fixed", element.style.pointerEvents = "none", element; } var Root = FocusGuards; export { FocusGuards, Root, useFocusGuards };