UNPKG

@wordpress/components

Version:
79 lines (78 loc) • 2.85 kB
import { forwardRef, useEffect, useRef } from "@wordpress/element"; import { useMergeRefs } from "@wordpress/compose"; import { focus } from "@wordpress/dom"; import { jsx } from "react/jsx-runtime"; // packages/components/src/navigable-container/container.tsx const noop = () => {}; const MENU_ITEM_ROLES = [ "menuitem", "menuitemradio", "menuitemcheckbox" ]; function cycleValue(value, total, offset) { const nextValue = value + offset; if (nextValue < 0) return total + nextValue; else if (nextValue >= total) return nextValue - total; return nextValue; } function getFocusableContext(container, target, tabbableOnly) { const focusables = (tabbableOnly ? focus.tabbable : focus.focusable).find(container); const index = focusables.indexOf(target); if (index > -1 || !tabbableOnly && target === container) return { index, target, focusables }; return null; } function UnforwardedNavigableContainer({ children, stopNavigationEvents, eventToOffset, onNavigate = noop, onKeyDown, cycle = true, onlyBrowserTabstops, ...restProps }, ref) { const containerRef = useRef(null); useEffect(() => { const container = containerRef.current; if (!container) return; function handleKeyDown(event) { if (onKeyDown) onKeyDown(event); const offset = eventToOffset(event); if (offset !== void 0 && stopNavigationEvents) { event.stopImmediatePropagation(); const targetRole = event.target?.getAttribute("role"); if (!!targetRole && MENU_ITEM_ROLES.includes(targetRole) || !onlyBrowserTabstops && event.target === container) event.preventDefault(); } if (!offset) return; const activeElement = event.target?.ownerDocument?.activeElement; if (!activeElement) return; const context = getFocusableContext(container, activeElement, !!onlyBrowserTabstops); if (!context) return; const { index, focusables } = context; let nextIndex = index + offset; if (index === -1) nextIndex = offset > 0 ? 0 : focusables.length - 1; else if (cycle) nextIndex = cycleValue(index, focusables.length, offset); if (nextIndex >= 0 && nextIndex < focusables.length) { focusables[nextIndex].focus(); onNavigate(nextIndex, focusables[nextIndex]); if (event.code === "Tab") event.preventDefault(); } } container.addEventListener("keydown", handleKeyDown); return () => { container.removeEventListener("keydown", handleKeyDown); }; }, [ onKeyDown, eventToOffset, stopNavigationEvents, cycle, onNavigate, onlyBrowserTabstops ]); const mergedRef = useMergeRefs([containerRef, ref]); return /* @__PURE__ */ jsx("div", { ref: mergedRef, ...restProps, children }); } const NavigableContainer = forwardRef(UnforwardedNavigableContainer); NavigableContainer.displayName = "NavigableContainer"; export { NavigableContainer as default }; //# sourceMappingURL=container.mjs.map