@kubit-ui-web/react-components
Version:
Kubit React Components is a customizable, accessible library of React web components, designed to enhance your application's user experience
60 lines • 2.71 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useScrollDetectionWithAutoFocus = void 0;
const react_1 = __importDefault(require("react"));
const resizeObserver_1 = require("../../utils/resizeObserver/resizeObserver");
const hasScroll_1 = require("../../utils/scroll/hasScroll");
/**
* Custom hook that determines if an element has scroll. Besides it will focus on the element if it has scroll and the active element is not inside the parent element.
*
* @returns An object containing the `hasScroll` boolean and the `handleScrollDetection` callback function to initialize the hook.
*/
const useScrollDetectionWithAutoFocus = ({ parentElementRef, }) => {
const [hasScroll, setHasScroll] = react_1.default.useState(false);
const resizeObserverRef = react_1.default.useRef();
const handleScrollDetection = react_1.default.useCallback((element) => {
if (element) {
const handleInnerContentResize = (element) => {
const _hasScroll = (0, hasScroll_1.hasScroll)(element);
setHasScroll(_hasScroll);
};
const handleAutoFocus = element => {
const _hasScroll = (0, hasScroll_1.hasScroll)(element);
if (!_hasScroll) {
return;
}
const autoFocus = () => {
element.setAttribute('tabindex', '0');
element.focus();
};
if (!document.activeElement) {
autoFocus();
return;
}
if (!parentElementRef?.current?.contains(document.activeElement)) {
autoFocus();
return;
}
if (element.compareDocumentPosition(document.activeElement) & Node.DOCUMENT_POSITION_FOLLOWING) {
autoFocus();
}
};
handleInnerContentResize(element);
// Autofocus is only executed on mount
handleAutoFocus(element);
resizeObserverRef.current = new resizeObserver_1.ResizeObserver(() => {
handleInnerContentResize(element);
});
resizeObserverRef.current.observe(element);
}
else {
resizeObserverRef.current?.disconnect();
}
}, []);
return { hasScroll, handleScrollDetection };
};
exports.useScrollDetectionWithAutoFocus = useScrollDetectionWithAutoFocus;
//# sourceMappingURL=useScrollDetectionWithAutoFocus.js.map