Skip to content

Commit

Permalink
fix(TooltipPrimitive): tooltip now closes on pressing ESC key
Browse files Browse the repository at this point in the history
  • Loading branch information
DSil committed Dec 12, 2024
1 parent 04bfa42 commit d7243e5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import * as React from "react";
import userEvent from "@testing-library/user-event";

import { render, screen } from "../../../test-utils";
import { fireEvent, render, screen } from "../../../test-utils";
import Tooltip from "..";

describe("Tooltip", () => {
const user = userEvent.setup();

it("it should render on hover", async () => {
it("should render on hover", async () => {
const content = "Write some message to the user";
render(
<Tooltip content={content}>
Expand All @@ -17,7 +17,21 @@ describe("Tooltip", () => {

expect(screen.queryByText(content)).not.toBeInTheDocument();
await user.hover(screen.getByText("Some text"));
expect(screen.queryByText(content)).toBeInTheDocument();
expect(screen.queryByText(content)).toBeVisible();
});

it("should close on ESC click", async () => {
const content = "Write some message to the user";
render(
<Tooltip content={content}>
<p>Some text</p>
</Tooltip>,
);

await user.hover(screen.getByText("Some text"));
expect(screen.queryByText(content)).toBeVisible();
fireEvent.keyDown(document, { key: "Escape" });
expect(screen.queryByText(content)).not.toBeVisible();
});

it("should call onClick 1 time", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,30 @@ const TooltipPrimitive = ({

const tooltipId = useRandomId();

const handleEsc = React.useCallback(
(ev: { key: string }) => {
if (ev.key === "Escape") {
setShown(false);
setRenderWithTimeout(false);
document.removeEventListener("keydown", handleEsc);
}
},
[setRenderWithTimeout],
);

const handleOut = React.useCallback(() => {
setShown(false);
setRenderWithTimeout(false);
document.removeEventListener("keydown", handleEsc);
}, [handleEsc, setRenderWithTimeout]);

const handleIn = React.useCallback(() => {
setRender(true);
setShown(true);
if (onShow) onShow();
clearRenderTimeout();
}, [clearRenderTimeout, setRender, onShow]);

const handleOut = React.useCallback(() => {
setShown(false);
setRenderWithTimeout(false);
}, [setRenderWithTimeout]);
document.addEventListener("keydown", handleEsc);
}, [setRender, onShow, clearRenderTimeout, handleEsc]);

const handleClick = React.useCallback(
(ev: React.MouseEvent<HTMLSpanElement | HTMLDivElement>) => {
Expand Down

0 comments on commit d7243e5

Please sign in to comment.