@carbon/ibm-products
Version:
Carbon for IBM Products
65 lines (63 loc) • 2.3 kB
JavaScript
/**
* Copyright IBM Corp. 2020, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
require("../../../_virtual/_rolldown/runtime.js");
const require_wait = require("../utils/wait.js");
let react = require("react");
//#region src/global/js/hooks/useCreateComponentFocus.js
/**
* Copyright IBM Corp. 2021, 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const useCreateComponentFocus = ({ previousState, currentStep, blockClass, onMount, firstFocusElement }) => {
(0, react.useEffect)(() => {
if (typeof onMount === "function") onMount();
}, [onMount]);
(0, react.useEffect)(() => {
const awaitFocus = async (elm) => {
await require_wait.default(10);
elm.focus();
};
const isNotContainedInInert = (elm) => {
if (!elm) return false;
const inertParent = elm.closest("[inert]");
return !inertParent || !inertParent.hasAttribute("inert") && !elm.disabled;
};
const getActiveStep = () => {
return Array.from(document.querySelectorAll(blockClass)).find((el) => {
let currentStep = el;
while (currentStep) {
if (currentStep.hasAttribute("inert")) return false;
currentStep = currentStep.parentElement;
}
return true;
});
};
const getFocusableElement = (containingElement) => {
const focusElementQuery = `button, input[type="button"], input, select, textarea, a[href]`;
const firstFocusEl = containingElement.querySelector(firstFocusElement);
if (firstFocusEl && isNotContainedInInert(firstFocusEl) && !firstFocusEl.disabled) return firstFocusEl;
return Array.from(containingElement.querySelectorAll(focusElementQuery)).find((el) => isNotContainedInInert(el) && !el.disabled);
};
if (previousState?.currentStep !== currentStep && currentStep > 0) {
const activeStepElement = getActiveStep();
if (activeStepElement && isNotContainedInInert(activeStepElement)) {
const focusEl = getFocusableElement(activeStepElement);
if (focusEl) awaitFocus(focusEl);
}
}
}, [
currentStep,
previousState,
blockClass,
onMount,
firstFocusElement
]);
};
//#endregion
exports.useCreateComponentFocus = useCreateComponentFocus;