Skip to content

Commit

Permalink
use elements bounding client rect to detect inside clicks
Browse files Browse the repository at this point in the history
  • Loading branch information
sviripa committed Jul 21, 2024
1 parent 858d0ea commit b37659a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,20 @@ export function useClickOutside<T extends Element>(
const el = $derived(extract(container));

function handleClick(event: MouseEvent) {
if (!event.target || el?.contains(event.target as Node)) return;
if (!event.target || !el) {
return;
}

callback();
const rect = el.getBoundingClientRect();
const clickedInside =
rect.top <= event.clientY &&
event.clientY <= rect.top + rect.height &&
rect.left <= event.clientX &&
event.clientX <= rect.left + rect.width;

if (!clickedInside) {
callback();
}
}

useEventListener(() => document, "click", handleClick);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,30 @@ describe("useClickOutside", () => {
document.body.appendChild(button);
container.appendChild(innerButton);

container.getBoundingClientRect = vi.fn(() => ({
height: 100,
width: 100,
top: 50,
left: 50,
bottom: 0,
right: 0,
x: 50,
y: 50,
toJSON: vi.fn()
}))

const callbackFn = vi.fn();

useClickOutside(() => container, callbackFn);
await tick();

button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
button.dispatchEvent(new MouseEvent("click", { bubbles: true, clientX: 10, clientY: 10 }));
expect(callbackFn).toHaveBeenCalledOnce();

innerButton.dispatchEvent(new MouseEvent("click", { bubbles: true }));
innerButton.dispatchEvent(new MouseEvent("click", { bubbles: true, clientX: 100, clientY: 100 }));
expect(callbackFn).toHaveBeenCalledOnce();

container.dispatchEvent(new MouseEvent("click", { bubbles: true }));
container.dispatchEvent(new MouseEvent("click", { bubbles: true, clientX: 50, clientY: 50 }));
expect(callbackFn).toHaveBeenCalledOnce();
});
});

0 comments on commit b37659a

Please sign in to comment.