@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
25 lines • 1.08 kB
JavaScript
import { useEffect } from "react";
import { useEventCallback } from "../../../utils/hooks/index.js";
export function useEscapeKeydown(callback, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document, enabled = true) {
const onEscapeKeyDown = useEventCallback(callback);
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