Skip to content

useFloatingUI

A thin wrapper around Floating UI for positioning floating elements (such as tooltips, dropdowns, or popovers) relative to a reference element.

Usage

ts
import { ImpulseElement, registerElement, target } from '@ambiki/impulse';
import useFloatingUI from '@ambiki/impulse-view-components/dist/hooks/use_floating_ui';

@registerElement('pop-over')
export default class PopoverElement extends ImpulseElement {
  // The anchor element.
  @target() button: HTMLButtonElement;

  // The element to be positioned relative to the anchor.
  @target() panel: HTMLElement;

  private floatingUI: ReturnType<typeof useFloatingUI>;

  connected() {
    this.floatingUI = useFloatingUI(this, {
      referenceElement: this.button,
      popupElement: this.panel,
      placement: 'bottom',
    });
  }

  show() {
    // Show the popover.
    this.panel.hidden = false;
    // Start positioning logic.
    this.floatingUI.start();
  }

  async hide() {
    // Hide the popover.
    this.panel.hidden = true;
    // Stop positioning logic.
    await this.floatingUI.stop();
  }

  // Required for Floating UI to calculate positioning.
  get open() {
    return !this.panel.hasAttribute('hidden');
  }
}

Arguments

ts
useFloatingUI(element, options);

element

NameDefaultDescription
elementN/AThe impulse element (usually this).

options

NameDefaultDescription
referenceElementN/AThe anchor element.
popupElementN/AThe element that you want to position with respect to the referenceElement.
arrowElementundefinedOptional arrow element pointing to the referenceElement.
middleware[]Array of custom middleware functions for fine-grained positioning control. Read the docs.
offsetOptions0Adds distance between the referenceElement and the popupElement. Read the docs.
placementbottom-startThe preferred placement of the popupElement. May change automatically to stay within the viewport. One of top, top-start, top-end, right, right-start, right-end, bottom, bottom-start, bottom-end, left, left-start, or left-end. Read the docs.
flipOptionsundefinedAutomatically flips the popupElement to the opposite side if there's not enough space. Read the docs.
shiftOptionsundefinedPrevents overflow by shifting the popupElement along its alignment axis. Read the docs.
strategyfixedCSS positioning strategy: either absolute or fixed. One of absolute, or fixed.
syncundefinedSyncs the dimensions of the popupElement with the referenceElement. One of height, width, or both.
autoSizeundefinedAdjusts the dimensions of the popupElement to dynamically fit the viewport. One of height, width, or both.
autoSizePadding0Extra space (in pixels) to add beyond the popupElement's dimensions. Applies only when autoSize is set.

Released under the MIT License.