@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
28 lines • 1.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useEscapeKeydown = useEscapeKeydown;
const react_1 = require("react");
const hooks_1 = require("../../../utils/hooks");
function useEscapeKeydown(callback, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document, enabled = true) {
const onEscapeKeyDown = (0, hooks_1.useEventCallback)(callback);
(0, react_1.useEffect)(() => {
if (!enabled) {
return;
}
const handleKeyDown = (event) => {
if (event.key === "Escape") {
onEscapeKeyDown(event);
}
};
/**
* We use the bubbling phase (not capture) so that elements inside the layer
* can handle Escape themselves and call stopPropagation() if needed.
* Layer ordering is handled programmatically via the DismissableLayerContext.
*/
ownerDocument.addEventListener("keydown", handleKeyDown);
return () => {
ownerDocument.removeEventListener("keydown", handleKeyDown);
};
}, [onEscapeKeyDown, ownerDocument, enabled]);
}
//# sourceMappingURL=useEscapeKeydown.js.map