floating: add position reference element override

This commit is contained in:
Elijah Duffy
2026-04-12 17:52:08 -07:00
parent ab352b217a
commit e6fc8e8b37

View File

@@ -41,6 +41,7 @@ export class Popover {
};
private referenceElement: HTMLElement | undefined = $state();
private floatingElement: HTMLElement | undefined = $state();
private positionElement: HTMLElement | undefined = $state();
private open = $state(false);
/**
@@ -95,6 +96,23 @@ export class Popover {
return attrs;
}
/**
* Optionally sets the positioning element for the popover, which is used
* for calculating the position of the floating element. If not set, the
* reference element is used by default.
* @returns An object containing an attachment key for the positioning element.
*/
positionReference() {
return {
[createAttachmentKey()]: (node: HTMLElement) => {
this.positionElement = node;
return () => {
this.positionElement = undefined;
};
}
};
}
/** Returns whether the popover is open */
isOpen() {
return this.open;
@@ -171,7 +189,8 @@ export class Popover {
if (!this.referenceElement || !this.floatingElement) {
return;
}
const position = await computePosition(this.referenceElement, this.floatingElement, {
const reference = this.positionElement || this.referenceElement;
const position = await computePosition(reference, this.floatingElement, {
placement: this.options.placement,
middleware: [
flip(),