floating: add click & keydown helpers
This commit is contained in:
@@ -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
|
||||
* the computePosition function from floating-ui. It applies the calculated
|
||||
|
||||
Reference in New Issue
Block a user