@octopusdeploy/design-system-components
Version:
The design systems component library.
135 lines (134 loc) • 6.65 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.useFocusTrap = useFocusTrap;
exports.useFocusFirstFocusableElement = useFocusFirstFocusableElement;
const react_1 = __importStar(require("react"));
const isHTMLElement_1 = require("../utils/isHTMLElement");
/**
* Traps focus within a DOM node. Shifting focus with `Tab` and `Shift-Tab` will loop through all focusable elements of the node.
* Nesting is handled naturally by the browser's event model — keydown events only bubble through DOM ancestors,
* so a trap only fires when focus is actually inside its container.
*/
function useFocusTrap(focusContainer, enabled = true) {
(0, react_1.useEffect)(() => {
if (!focusContainer || !enabled)
return;
const onKeyDown = (event) => {
if (event.key !== "Tab")
return;
const tabbableElements = Array.from(focusContainer.querySelectorAll(focusableSelector)).filter(isTabbableElement);
if (tabbableElements.length === 0)
return;
const firstFocusableElement = tabbableElements[0];
const lastFocusableElement = tabbableElements[tabbableElements.length - 1];
// If focus is on a non-tabbable element, e.g. initial focus on a dialog container with tabIndex -1, move to first or last element depending on direction.
if (document.activeElement && !isTabbableElement(document.activeElement)) {
if (event.shiftKey) {
lastFocusableElement?.focus();
}
else {
firstFocusableElement?.focus();
}
event.preventDefault();
return;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const currentIndex = tabbableElements.indexOf(document.activeElement);
// Always handle Tab ourselves so focus order follows DOM order. This prevents browsers from
// skipping elements outside scrollable containers (e.g. dialog footer buttons).
event.preventDefault();
if (event.shiftKey) {
const prevIndex = currentIndex === 0 ? tabbableElements.length - 1 : currentIndex - 1;
tabbableElements[prevIndex].focus();
}
else {
const nextIndex = currentIndex === tabbableElements.length - 1 ? 0 : currentIndex + 1;
tabbableElements[nextIndex].focus();
}
};
focusContainer.addEventListener("keydown", onKeyDown);
return () => {
focusContainer.removeEventListener("keydown", onKeyDown);
};
}, [focusContainer, enabled]);
}
function useFocusFirstFocusableElement() {
return react_1.default.useCallback((container) => {
const [firstFocusableElement] = Array.from(container.querySelectorAll(focusableSelector)).filter(isTabbableElement);
if (firstFocusableElement) {
firstFocusableElement.focus();
}
else if (container.tabIndex >= 0) {
container.focus();
}
}, []);
}
// From https://github.com/testing-library/user-event/blob/main/src/utils/focus/selector.ts
const focusableSelector = ["input:not([type=hidden]):not([disabled])", "button:not([disabled])", "select:not([disabled])", "textarea:not([disabled])", '[contenteditable=""]', '[contenteditable="true"]', "a[href]", "[tabindex]:not([disabled])"].join(", ");
function isTabbableElement(element) {
if (!(0, isHTMLElement_1.isHTMLElement)(element))
return false;
if (element.tabIndex < 0)
return false;
// Exclude elements inside an inert subtree — inert removes them from tab order but tabIndex doesn't reflect it.
if (element.closest("[inert]"))
return false;
if (!isVisible(element))
return false;
return true;
}
function isVisible(element) {
if (element.hidden)
return false;
// Fast path: non-null offsetParent means the element is definitely rendered in a real browser.
// In jsdom offsetParent is always null, so this never short-circuits there.
if (element.offsetParent !== null)
return true;
// offsetParent is null in three cases: display:none (self or ancestor), position:fixed, or jsdom.
// Check the element's own computed styles first to catch explicit display:none / visibility:hidden.
const style = getComputedStyle(element);
if (style.display === "none" || style.visibility === "hidden")
return false;
// Use getClientRects() to catch ancestor display:none (e.g. a side panel hidden via a media
// query) since getComputedStyle only reflects the element's own styles. position:fixed elements
// still produce rects so they pass correctly. In jsdom getClientRects() always returns [] so
// guard with a body probe — body always has rects in a real browser but not in jsdom.
// TODO: Remove the body probe and inline condition once tests run under Vitest browser mode,
// leaving just: if (element.getClientRects().length === 0) return false;
if (element.getClientRects().length === 0 && document.body.getClientRects().length > 0)
return false;
return true;
}