Utilities

Need a little helper?

The utilities described here match the behavior of framer-motion. The syntax is similar, but often stores are used.

Animate

Motion values can be animated via javascript code with the animate function. It takes three arguments: the first is the motion value, which you want to animate, the second is the target value, or an array of keyframes. The third is an object of tween or spring options. animate returns an object, which for now only has one method stop. Call this function to stop the animation.

Also, you can add lifecycle callbacks to the options object in the third argument. Currently supported are

Lifecycles are demonstrated in the REPL of this example:

/ REPL

Transform

transform function calculates interpolated values, just like the useTransform motion value. You can either calculate single values, eg.:

import { transform } from 'svelte-motion'
const x = transform(91,[0,100],[-1,4]) // 3.55 

or you can obtain a function. This also works with colors, like in the following example.

rgba(255, 0, 0, 1)

rgba(240, 0, 85, 1)

rgba(225, 0, 120, 1)

rgba(208, 0, 147, 1)

rgba(190, 0, 170, 1)

rgba(170, 0, 190, 1)

rgba(147, 0, 208, 1)

rgba(120, 0, 225, 1)

rgba(85, 0, 240, 1)

rgba(0, 0, 255, 1)

As the color picker, ReinventedColorWheel is used.

useIsPresent

This utilities tells you, if a component wrapped with AnimatePresence is mounted, or if it currently exits. It returns a readable store, so it notifys you on changes:

import { useIsPresent }
const isPresent = useIsPresent();
$: (status = $isPresent ? "Hello World" : "Goodbye" )

Hello World

usePresence

usePresence returns a store, which has two values: a boolean, telling you, if the component is mounted or want to exit, just like useIsPresent. Additionally, it provides a callback, and the unmounting is postponed until you call this callback.

<script>
    import { usePresence }
    const presence = usePresence();
    $: (status = $presence[0] ? "Hello World" : "Do you really want to exit?")
</script>

{status}
{#if !$presence[0]}
    <button on:click={$presence[1]}>Exit</button>
{/if}
Hello World

useCycle

Returns a Svelte store with an next method. This lets you cycle through the elements of the list of elements you provide to useCycle.

useReducedMotion

Returns a store which holds a boolean, indicating if the user prefers to see less motion.

import { useReducedMotion } from 'svelte-motion'

const shouldReduceMotion = useReducedMotion()
$: (slideOutX = $shouldReduceMotion ? 0 : "-100%")

useDragControls

In the example below you can drag the upper box by starting to drag on the lower box.