floating: add click & keydown helpers

This commit is contained in:
Elijah Duffy
2026-04-12 17:03:17 -07:00
parent 337c2a50b3
commit 18b0b8963a

View File

@@ -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 <svelte:window onkeydown={popover.handleEscape} />,
* 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 <svelte:window onclick={popover.handleClickOutside} />.
* @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 * Updates the position of the floating element based on the reference element using
* the computePosition function from floating-ui. It applies the calculated * the computePosition function from floating-ui. It applies the calculated