Svelte✨ Floating UI 🎈

Overview

🎈 Svelte Floating UI

npm version npm downloads license

Floating UI for Svelte with actions. No wrapper components or component bindings required!

npm i -D svelte-floating-ui

Usage

createFloatingActions takes an optional options object for configuring the content placement. The content action also takes an optional options object for updating the options of the content placement.

createFloatingActions also returns an update method as it's third value which can be used to manually update the content position.

Example

<script lang="ts">
  import { offset, flip, shift } from "@floating-ui/dom";
  import { createFloatingActions } from "svelte-floating-ui";

  const [ floatingRef, floatingContent ] = createFloatingActions({
    strategy: "absolute",
    placement: "top",
    middleware: [
      offset(6),
      flip(),
      shift(),
    ]
  });

  let showTooltip: boolean = false;
</script>

<button 
  on:mouseenter={() => showTooltip = true}
  on:mouseleave={() => showTooltip = false}
  use:floatingRef
>Hover me</button>

{#if showTooltip}
  <div style="position:absolute" use:floatingContent>
    Tooltip
  </div>
{/if}

API

Setting Floating UI options

Floating UI options can be set statically when creating the actions, or dynamically on the content action.

If both are set, then the dynamic options will be merged with the initial options.

<script>
  // set once and no longer updated
  const [ floatingRef, floatingContent ] = createFloatingActions(initOptions);
</script>

<!-- will be merged with initOptions -->
<div use:floatingContent={ dynamicOptions }/>

Updating the Floating UI position

The content element's position can be manually updated by using the third value returned by createFloatingActions. This method takes an optional options object which will be merged with the initial options.

<script>
  // Get update method
  const [ floatingRef, floatingContent, update] = createFloatingActions(initOptions);

  update(updateOptions)
</script>

Floating UI autoUpdate

You can use autoUpdate options directly in initOptions for createFloatingActions or floatingContent, but not in update

<script>
  import { offset, flip, shift } from "@floating-ui/dom";
  import { createFloatingActions } from "svelte-floating-ui";

  const [ floatingRef, floatingContent ] = createFloatingActions({
    strategy: "absolute",
    placement: "top",
    middleware: [
      offset(6),
      flip(),
      shift(),
    ],
    autoUpdate: { // or false to disable everything
      ancestorResize: false,
      elementResize: false
    }
  });
</script>

What values can autoUpdate have?

Partial<Options>

/**
* false: Don't initialize autoUpdate;
* true: Standard autoUpdate values from the documentation;
* object: All as in the autoUpdate documentation. Your parameters are added to the default ones;
* @default true
*/
autoUpdate?: boolean | Partial<Options>

Applying custom styles on compute

To apply styles manually, you can pass the onComputed option to createFloatingActions. This is a function that recieves a ComputePositionReturn. This function is called every time the tooltip's position is computed.

See Arrow Middleware for an example on it's usage.

Arrow Middleware

For convenience, a custom Arrow middleware is provided. Rather than accepting an HTMLElement, this takes a Writable<HTMLElement>. Otherwise, this middleware works exactly as the regular Floating UI one, including needing to manually set the arrow styles.

To set the styles, you can pass the onComputed option. The below implementation is copied from the Floating UI Tutorial.

<script>
  import { writable } from "svelte/store";
  import { arrow } from "svelte-floating-ui";

  const arrowRef = writable(null);
  const [ floatingRef, floatingContent, update] = createFloatingActions({
    strategy: "absolute",
    placement: "bottom",
    middleware: [
      arrow({ element: arrowRef })
    ],
    onComputed({ placement, middlewareData }) {
      const { x, y } = middlewareData.arrow;
      const staticSide = {
        top: 'bottom',
        right: 'left',
        bottom: 'top',
        left: 'right',
      }[placement.split('-')[0]];

      Object.assign($arrowRef.style, {
        left: x != null ? `${x}px` : "",
        top: y != null ? `${y}px` : "",
        [staticSide]: "-4px"
      });
    }
  });
</script>

<button 
  on:mouseenter={() => showTooltip = true}
  on:mouseleave={() => showTooltip = false}
  use:floatingRef
>Hover me</button>

{#if showTooltip}
  <div class="tooltip" use:floatingContent>
    Tooltip this is some longer text than the button
    <div class="arrow" bind:this={$arrowRef} />
  </div>
{/if}

Thanks to TehNut/svelte-floating-ui for the foundation for this package

You might also like...

Svelte component to render markdown.

svelte-exmarkdown Svelte component to render markdown. Motivation svelte-markdown is a good component package. However, it is not extensible. You cann

Jan 6, 2023

Simple and Extensible Markdown Parser for Svelte, however its simplicity can be extended to any framework.

svelte-simple-markdown This is a fork of Simple-Markdown, modified to target Svelte, however due to separating the parsing and outputting steps, it ca

May 22, 2022

Simple and lightweight form validation for Svelte with no dependencies.

Svelidate Simple and lightweight form validation for Svelte with no dependencies Installation // npm npm install svelidate // yarn yarn add svelidate

Dec 28, 2022

A basic Svelte tooltip directive.

SVooltip A basic Svelte tooltip directive. Powered by Floating UI. Usage script import { tooltip } from 'svooltip'; import 'svooltip/svooltip.css'

Nov 26, 2022

A ✨light✨ and magical Svelte component for CSS media queries🐹

Svelte CSS media queries 🐥 Demo - Svelte REPL Lightweight, comfortable, like Svelte 🐣 how to install npm i svelte-media-queries What can I do? quer

Dec 26, 2022

👇 Bread n butter utility for component-tied mouse/touch gestures in Svelte.

👇 Bread n butter utility for component-tied mouse/touch gestures in Svelte.

svelte-gesture svelte-gesture is a library that lets you bind richer mouse and touch events to any component or view. With the data you receive, it be

Dec 21, 2022

Trying to learn Svelte. Based off the official tutorial. Readme has notes!

Learning Svelte! A JavaScript library An open-source front end compiler Instead of using a virtual DOM, Svelte will directly update the DOM in an effi

Jul 5, 2022

Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime.

Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime.

Bun Bakery Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime. Quick

Dec 6, 2022

A lightweight abstraction between Svelte stores and Chrome extension storage.

Svelte Chrome Storage A lightweight abstraction between Svelte stores and Chrome extension storage. This library makes data synchronization of backgro

Nov 15, 2022
Comments
  • Does not work properly with svelte-portal

    Does not work properly with svelte-portal

    When attempting to use svelte-floating-ui with svelte-portal the floating element initially renders in the wrong position. Resizing the window or closing and opening the floating UI fixes it (at least, closing and opening controlled by display: none/block;). If I were to make an educated guess I would say that the floating ui calcualtions are being done before the floating element is moved to the portal.

    Here is some example code:

    <script lang="ts">
      import Portal from 'svelte-portal';
      import { offset, flip, shift } from '@floating-ui/dom';
      import { createFloatingActions } from 'svelte-floating-ui';
    
      const [floatingRef, floatingContent] = createFloatingActions({
        strategy: 'absolute',
        placement: 'bottom-end',
        middleware: [offset(6), flip(), shift()],
      });
    
      const ariaMenuButtonId = 'menu-button';
      const ariaMenuId = 'menu';
      let open = false;
    </script>
    
    <button
      id={ariaMenuButtonId}
      type="submit"
      class="h-10 rounded-sm"
      aria-haspopup="true"
      aria-controls={ariaMenuId}
      on:click={() => {
        open = !open;
      }}
      use:floatingRef>Open</button
    >
    
    <Portal>
      <ul
        id={ariaMenuId}
        role="menu"
        aria-labelledby={ariaMenuButtonId}
        class="menu w-20"
        class:menu-open={open}
        use:floatingContent
      >
        <li role="none"><a href="/#" role="menuitem">Menu Item</a></li>
      </ul>
    </Portal>
    
    <style>
      .menu {
        display: none;
      }
    
      .menu-open {
        display: block;
      }
    </style>
    
    opened by knpwrs 2
Owner
Nikita Fedorov
OMG Frontend :octocat:
Nikita Fedorov
Displaying actual age in percentage with 9 signs after dot (floating number)

Actual Age Chrome Extension Displaying actual age in percentage with 9 signs after dot (floating number) Features Popup You can select your Birth date

Igor Makeenko 22 Nov 2, 2022
Input with floating label make with tailwindcss 3.0.18

tailwind-floating-label-input Input with floating label make with tailwindcss 3.0.18 Works with <input> and <textarea> elements. How to use <Input

Pablo David Gago Ballester 1 Feb 10, 2022
useOverlay uses floating-ui and framer-moting under the hood, giving you an API that provides great usability.

Create floating things easily useOverlay uses floating-ui and framer-moting under the hood, giving you an API that provides great usability. Warning D

Nedim Arabacı 8 Oct 24, 2022
Unread-Messages.js is a lightweight library that lets a user add floating number notifications to any object.

Unread-Messages.js About Unread-Messages.js is a lightweight library that lets a user add mobile-like notification counter badge to any object with ju

Mulaza Jacinto 2 Dec 18, 2021
Bootstrap 5 Floating Label

@tkrotoff/bootstrap-floating-label Floating label for Bootstrap 5 Example: https://codesandbox.io/s/github/tkrotoff/bootstrap-floating-label/tree/code

Tanguy Krotoff 31 Dec 10, 2022
Show floating sticky outline (table of contents) for Notion pages, powered by nbundle.

Notion Outline Show floating sticky outline (table of contents) for Notion pages, powered by nbundle. This is an nbundle-powered Notion app bootstrapp

nbundle 11 Nov 10, 2022
Might be mineral fish site in future, idk. Currently just a fish list. Made with Svelte

Might be mineral fish site in future, idk. Currently just a fish list. Made with Svelte. Built version (used at mineralfish.github.io) at the build branch. Build steps and original README below.

Mineral Fish 3 Nov 3, 2022
An Electron app using NAPI-RS and a native Rust module to implement a Svelte store.

Svelte Store Written in Rust This repo shows a demo of an Electron app running a Svelte UI that reads and writes a Svelte store, but with a twist: the

Dave Ceddia 27 Sep 20, 2022
Svelte debugging tool for re-rendering components

resvelte README This is the README for your extension "resvelte". After writing up a brief description, we recommend including the following sections.

OSLabs Beta 44 Oct 4, 2022
Internationalization for svelte framework. Based on i18next ecosystem

svelte-i18next Svelte wrapper for i18next npm i svelte-i18next i18next Implementation This library wraps an i18next instance in a Svelte Store to obs

Nishu Goel 20 Dec 9, 2022