@kiwicom/orbit-components
Version:
Orbit-components is a React component library which provides developers with the easiest possible way of building Kiwi.com’s products.
56 lines (48 loc) • 1.5 kB
JavaScript
import * as React from "react";
import FOCUSABLE_ELEMENT_SELECTORS from "./consts";
import KEY_CODE_MAP from "../../common/keyMaps";
const manageFocus = (ref, triggered) => {
if (triggered && ref.current) {
const focusableElements = ref.current.querySelectorAll(FOCUSABLE_ELEMENT_SELECTORS);
if (focusableElements.length > 0) {
const firstFocusableEl = focusableElements[0];
const lastFocusableEl = focusableElements[focusableElements.length - 1];
return {
first: firstFocusableEl,
last: lastFocusableEl
};
}
}
return {
first: null,
last: null
};
};
const useFocusTrap = ref => {
const [triggered, setTriggered] = React.useState(false);
React.useEffect(() => {
const handleKeyDown = ev => {
if (ev.keyCode === KEY_CODE_MAP.TAB) {
if (!triggered) {
setTriggered(true);
}
const {
first,
last
} = manageFocus(ref, triggered);
if (ev.shiftKey && last && (document.activeElement === first || document.activeElement === ref.current)) {
ev.preventDefault();
last.focus();
} else if (!ev.shiftKey && first && document.activeElement === last) {
ev.preventDefault();
first.focus();
}
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [triggered, ref]);
};
export default useFocusTrap;