From 18b0b8963ab5b329b5bf3035d28793b1f71a1730 Mon Sep 17 00:00:00 2001 From: Elijah Duffy Date: Sun, 12 Apr 2026 17:03:17 -0700 Subject: [PATCH] floating: add click & keydown helpers --- src/lib/floating.svelte.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/lib/floating.svelte.ts b/src/lib/floating.svelte.ts index a0833b9..ba7dcf4 100644 --- a/src/lib/floating.svelte.ts +++ b/src/lib/floating.svelte.ts @@ -122,6 +122,38 @@ export class Popover { }; } + /** + * Callback function that closes the popover when the Escape key is pressed. + * Can be applied to the window, typically via , + * or to any other element that will receive keyboard events while the popover is open. + * @param event - The keyboard event to handle. + */ + handleEscape(event: KeyboardEvent) { + if (event.key === 'Escape') { + this.setOpen(false); + } + } + + /** + * Callback function that closes the popover when a click occurs outside of the + * reference and floating elements. Should be applied to the window, typically + * via . + * @param event - The click event to handle. + */ + handleClickOutside(event: MouseEvent) { + if (!this.isOpen() || !this.referenceElement || !this.floatingElement) { + return; + } + + if ( + event.target instanceof Node && + !this.referenceElement.contains(event.target) && + !this.floatingElement.contains(event.target) + ) { + this.setOpen(false); + } + } + /** * Updates the position of the floating element based on the reference element using * the computePosition function from floating-ui. It applies the calculated