@kadoui/react
Version:
Kadoui primitive components for React
50 lines (49 loc) • 1.98 kB
JavaScript
"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useRef } from "react";
import { selectAccessibleChildren } from "../../utils";
export function AccessNavigation({ ref, focusOnMount, direction = "y", dir, onKeyDown, ...p }) {
const accessNavigationRef = ref || useRef(null);
useEffect(() => {
if (!accessNavigationRef.current)
return;
const focusableChildren = selectAccessibleChildren(accessNavigationRef.current);
if (focusOnMount) {
focusableChildren[0]?.focus();
}
}, []);
const handleKeyDown = (ev) => {
const focusableChildren = selectAccessibleChildren(ev.currentTarget);
if (!focusableChildren.length) {
return;
}
const currentDir = (dir ||
document.documentElement.getAttribute("dir") ||
"ltr");
const currentIndex = focusableChildren.findIndex((item) => item === document.activeElement);
if (ev.key ===
(direction === "y"
? "ArrowDown"
: currentDir === "ltr"
? "ArrowRight"
: "ArrowLeft")) {
ev.preventDefault();
ev.stopPropagation();
const nextIndex = currentIndex === -1 || currentIndex === focusableChildren.length - 1
? 0
: currentIndex + 1;
focusableChildren[nextIndex]?.focus();
}
if (ev.key ===
(direction === "y" ? "ArrowUp" : currentDir === "ltr" ? "ArrowLeft" : "ArrowRight")) {
ev.preventDefault();
ev.stopPropagation();
const prevIndex = currentIndex <= 0 ? focusableChildren.length - 1 : currentIndex - 1;
focusableChildren[prevIndex]?.focus();
}
};
return (_jsx("div", { dir: dir, ref: accessNavigationRef, onKeyDown: (ev) => {
onKeyDown?.(ev);
handleKeyDown(ev);
}, ...p }));
}