Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion client-src/overlay.js
Original file line number Diff line number Diff line change
Expand Up @@ -644,11 +644,34 @@ const createOverlay = (options) => {
}, trustedTypesPolicyName);
}

/** @type {(event: KeyboardEvent) => void} */
let handleEscapeKey;

/**
* @returns {void}
*/

const hideOverlayWithEscCleanup = () => {
window.removeEventListener("keydown", handleEscapeKey);
hide();
};

const overlayService = createOverlayMachine({
showOverlay: ({ level = "error", messages, messageSource }) =>
show(level, messages, options.trustedTypesPolicyName, messageSource),
hideOverlay: hide,
hideOverlay: hideOverlayWithEscCleanup,
});
/**
* ESC key press to dismiss the overlay.
* @param {KeyboardEvent} event Keydown event
*/
handleEscapeKey = (event) => {
if (event.key === "Escape" || event.key === "Esc" || event.keyCode === 27) {
overlayService.send({ type: "DISMISS" });
}
};

window.addEventListener("keydown", handleEscapeKey);

if (options.catchRuntimeError) {
/**
Expand Down
37 changes: 37 additions & 0 deletions test/client/ReactErrorBoundary.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,41 @@ describe("createOverlay", () => {
});
showOverlayMock.mockRestore();
});
// ESC key test cases

it("should dismiss overlay when ESC key is pressed", () => {
const options = { trustedTypesPolicyName: null, catchRuntimeError: true };
const overlay = createOverlay(options);
const showOverlayMock = jest.spyOn(overlay, "send");

const escEvent = new KeyboardEvent("keydown", { key: "Escape" });
globalThis.window.dispatchEvent(escEvent);

expect(showOverlayMock).toHaveBeenCalledWith({ type: "DISMISS" });
showOverlayMock.mockRestore();
});

it("should dismiss overlay when 'Esc' key is pressed (older browsers)", () => {
const options = { trustedTypesPolicyName: null, catchRuntimeError: true };
const overlay = createOverlay(options);
const showOverlayMock = jest.spyOn(overlay, "send");

const escEvent = new KeyboardEvent("keydown", { key: "Esc" });
globalThis.window.dispatchEvent(escEvent);

expect(showOverlayMock).toHaveBeenCalledWith({ type: "DISMISS" });
showOverlayMock.mockRestore();
});

it("should not dismiss overlay for other keys", () => {
const options = { trustedTypesPolicyName: null, catchRuntimeError: true };
const overlay = createOverlay(options);
const showOverlayMock = jest.spyOn(overlay, "send");

const otherKeyEvent = new KeyboardEvent("keydown", { key: "Enter" });
globalThis.window.dispatchEvent(otherKeyEvent);

expect(showOverlayMock).not.toHaveBeenCalled();
showOverlayMock.mockRestore();
});
});