### Install Svelte Motion dependency
Source: https://svelte-motion.gradientdescent.de/
Install the Svelte Motion package as a development dependency using npm.
```bash
npm install --save-dev svelte-motion
```
--------------------------------
### Implement Hover and Tap Animations
Source: https://svelte-motion.gradientdescent.de/gestures
Use the whileHover and whileTap props to animate elements during user interaction. This example scales the button on hover and rotates it on tap.
```svelte
```
--------------------------------
### Define Pan Gesture Handlers
Source: https://svelte-motion.gradientdescent.de/API/gestures
Defines the interface for pan gesture callbacks including start, session start, move, and end events. Requires touch-action CSS rules for proper touch input handling.
```typescript
interface PanHandlers {
onPan?: (event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => void;
onPanStart?: (event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => void;
onPanSessionStart?: (event: MouseEvent | TouchEvent | PointerEvent, info: EventInfo) => void;
onPanEnd?: (event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => void;
}
```
--------------------------------
### VisualElementConfig Interface
Source: https://svelte-motion.gradientdescent.de/API/visualelement
Defines the configuration object for a VisualElement, specifying its behavior and methods for rendering, layout, and animation. It includes methods for getting base targets, building the element, sorting nodes, making targets animatable, measuring, reading values, resetting and restoring transforms, rendering, removing values, scraping motion values, and more.
```typescript
interface VisualElementConfig {
treeType?: string;
getBaseTarget?(props: MotionProps, key: string): string | number | undefined | MotionValue;
build(visualElement: VisualElement, renderState: RenderState, latestValues: ResolvedValues, projection: TargetProjection, layoutState: LayoutState, options: Options, props: MotionProps): void;
sortNodePosition?(a: Instance, b: Instance): number;
makeTargetAnimatable(element: VisualElement, target: TargetAndTransition, props: MotionProps, isLive: boolean): TargetAndTransition;
measureViewportBox(instance: Instance, options: Options): AxisBox2D;
readValueFromInstance(instance: Instance, key: string, options: Options): string | number | null | undefined;
resetTransform(element: VisualElement, instance: Instance, props: MotionProps): void;
restoreTransform(instance: Instance, renderState: RenderState): void;
render(instance: Instance, renderState: RenderState): void;
removeValueFromRenderState(key: string, renderState: RenderState): void;
scrapeMotionValuesFromProps: ScrapeMotionValuesFromProps;
}
```
--------------------------------
### Animation Controls with useAnimation in Svelte
Source: https://svelte-motion.gradientdescent.de/animation
Demonstrates how to use the `useAnimation` hook in Svelte Motion to create imperative animation controls. These controls can be passed to the `animate` prop of `Motion` components for starting and stopping animations programmatically.
```javascript
import { useAnimation } from 'svelte-motion'
const controls = useAnimation();
```
--------------------------------
### Create animation controls with useAnimation
Source: https://svelte-motion.gradientdescent.de/API/animation
The useAnimation hook creates an AnimationControls instance used to manually sequence animations across multiple components. The returned object is passed to the animate property of components, enabling programmatic control via the start method.
```TypeScript
const controls = useAnimation();
// Pass to component:
//
// Start animation:
// controls.start({ opacity: 1 });
```
--------------------------------
### None Transition
Source: https://svelte-motion.gradientdescent.de/API/transition
Provides an instant transition, meaning no animation occurs.
```APIDOC
## None Transition
### Description
Instant transition. For internal use only.
### Method
N/A (Configuration Object)
### Endpoint
N/A (Configuration Object)
### Parameters
#### Options
- **type** (boolean) - Required - Set to `false` for an instant transition.
### Request Example
```json
{
"type": false
}
```
### Response
#### Success Response (N/A - Configuration Object)
This is a configuration object for an animation, not a typical API response.
#### Response Example
N/A
```
--------------------------------
### Utility: createBatcher
Source: https://svelte-motion.gradientdescent.de/API/sharedlayout
Creates a batcher to process VisualElements for synchronized layout updates.
```APIDOC
## FUNCTION createBatcher
### Description
Creates a SyncLayoutBatcher instance to process multiple VisualElements, ensuring layout changes are calculated and applied efficiently.
### Returns
- **SyncLayoutBatcher** (Object) - The batcher instance used for managing layout synchronization.
```
--------------------------------
### Initialize Motion component
Source: https://svelte-motion.gradientdescent.de/
Import the M component from svelte-motion to create animated elements similar to Framer Motion's motion.div.
```svelte
import { M } from 'svelte-motion'
```
--------------------------------
### Manage Component Presence with Delayed Unmounting using usePresence
Source: https://svelte-motion.gradientdescent.de/utilities
The `usePresence` hook provides a store with two values: a boolean indicating if the component is mounted or wants to exit, and a callback to postpone unmounting. This allows for custom exit animations or cleanup before the component is removed from the DOM.
```javascript
import { usePresence } from 'svelte-motion';
const presence = usePresence();
$: status = $presence[0] ? "Hello World" : "Do you really want to exit?";
// In the template, conditionally render a button to trigger the exit:
// {#if !$presence[0]}
//
// {/if}
```
--------------------------------
### Get Scroll Motion Value for Element (Bind:this)
Source: https://svelte-motion.gradientdescent.de/motionvalue
Obtains scroll motion values for a specific HTML element using `useElementScroll`. This method directly binds the element to the `ref` attribute provided by the hook.
```javascript
import { useElementScroll } from 'svelte-motion'
const scrollMotionValue = useElementScroll();
// In template:
//
...
```
--------------------------------
### Get Scroll Motion Value for Element (Ref Object)
Source: https://svelte-motion.gradientdescent.de/motionvalue
Obtains scroll motion values for a specific HTML element using `useElementScroll`. This method utilizes a React-like ref object where the `current` property is bound to the element.
```javascript
import { useElementScroll } from 'svelte-motion'
const ref = {}
const scrollMotionValue = useElementScroll(ref)
// In template:
//
...
```
--------------------------------
### Motion Advanced Props
Source: https://svelte-motion.gradientdescent.de/API/motion
Advanced configuration interfaces for dynamic variants and inheritance control.
```APIDOC
## [INTERFACE] MotionAdvancedProps
### Description
Provides advanced control over how motion components resolve variants and inherit properties.
### Parameters
- **custom** (any) - Optional - Data used to resolve dynamic variants.
- **inherit** (boolean) - Optional - Set to false to prevent inheriting variant changes from parent components.
### Usage Example
```
--------------------------------
### Gesture Event Handlers
Source: https://svelte-motion.gradientdescent.de/API/gestures
Interfaces for handling drag, hover, and focus interaction events.
```APIDOC
## Gesture Handlers
### Description
Interfaces for tracking component interactions like dragging, hovering, and focusing.
### DragHandlers
- **onDragStart** (Function) - Callback when dragging starts.
- **onDragEnd** (Function) - Callback when dragging ends.
- **onDrag** (Function) - Callback during drag movement.
### HoverHandlers
- **whileHover** (VariantLabels | TargetAndTransition) - Animation applied during hover.
- **onHoverStart** (Function) - Callback on hover start.
- **onHoverEnd** (Function) - Callback on hover end.
### FocusHandlers
- **whileFocus** (VariantLabels | TargetAndTransition) - Animation applied during focus.
```
--------------------------------
### VisualElementDragControls Class
Source: https://svelte-motion.gradientdescent.de/API/visualelement
Manages drag gesture interactions for a VisualElement. It provides methods to start, resolve, cancel, and stop drag operations, including snapping to cursor, updating axis values, setting properties, and managing motion. It also handles constraint resolution for both layout and refs.
```typescript
class VisualElementDragControls {
start: (originEvent: MouseEvent | TouchEvent | PointerEvent, { snapToCursor, cursorProgress }?: DragControlOptions) => void;
resolveDragConstraints: () => void;
resolveRefConstraints: (layoutBox: AxisBox2D, constraints: Node) => { x: { min: number, max: number }, y: { min: number, max: number } };
cancelDrag: () => void;
stop: (event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => void;
snapToCursor: (point: Point2D) => boolean;
updateAxis: (axis: DragDirection, point: Point2D, offset?: Point2D) => void;
updateAxisMotionValue: (axis: DragDirection, offset: Point2D) => void;
updateVisualElementAxis: (axis: DragDirection, point: Point2D) => void;
setProps: (props: DragControlsProps & MotionProps) => void;
stopMotion: () => void;
scalePoint: () => void;
updateConstraints: (onReady?: () => void) => void;
mount: (visualElement: VisualElement) => () => void;
}
```
--------------------------------
### Utility: createCrossfader
Source: https://svelte-motion.gradientdescent.de/API/sharedlayout
Creates a crossfader instance to manage transitions between visual elements.
```APIDOC
## FUNCTION createCrossfader
### Description
Initializes a Crossfader instance to handle complex animation states between visual elements.
### Returns
- **Crossfader** (Object) - An object containing methods: isActive(), getCrossfadeState(), toLead(), fromLead(), setOptions(), reset(), stop(), and getLatestValues().
### Options (CrossfadeAnimationOptions)
- **lead** (VisualElement) - Optional - The leading element.
- **follow** (VisualElement) - Optional - The following element.
- **crossfadeOpacity** (boolean) - Optional - Whether to animate opacity during crossfade.
```
--------------------------------
### Layout Props Configuration
Source: https://svelte-motion.gradientdescent.de/API/measure
Interface defining properties for components to support automatic layout animations. Includes configuration for shared layout transitions and completion callbacks.
```typescript
interface LayoutProps {
layout?: boolean | "position";
layoutId?: string;
onLayoutAnimationComplete?: () => void;
}
```
--------------------------------
### Tween Animation Configuration
Source: https://svelte-motion.gradientdescent.de/API/transition
Configuration object for defining duration-based tween animations in Svelte Motion.
```APIDOC
## Tween Configuration
### Description
An animation interface that animates between two or more values over a specific duration of time. This is the default animation for non-physical values.
### Parameters
#### Configuration Properties
- **type** (string) - Optional - Set to "tween" to explicitly define a duration-based animation.
- **duration** (number) - Optional - The duration of the animation in seconds. Defaults to 0.3 or 0.8 for keyframes.
- **ease** (Easing | Easing[]) - Optional - The easing function(s) to apply to the animation.
- **times** (number[]) - Optional - Array of values between 0 and 1 determining when each keyframe is reached.
- **easings** (Easing[]) - Optional - Array of easing functions to apply between each keyframe.
- **from** (number | string) - Optional - The starting value for the animation. Defaults to the current state.
### Request Example
{
"type": "tween",
"duration": 0.5,
"ease": "easeInOut",
"from": 0
}
### Response
#### Success Response (N/A)
- This configuration is applied internally by the Svelte Motion engine to update component styles over time.
```
--------------------------------
### Implement Motion Elements with M Shorthand
Source: https://svelte-motion.gradientdescent.de/motion
The M shorthand provides a quick way to add motion to standard HTML elements. While convenient, it limits direct access to native DOM directives like on:click.
```svelte
A big motion headerA big motion headerA motion button
```
--------------------------------
### Keyframes Transition
Source: https://svelte-motion.gradientdescent.de/API/transition
Animates between multiple values using keyframes. The sequence can be arranged using duration, easing functions, and specific time points.
```APIDOC
## Keyframes Transition
### Description
Keyframes tweens between multiple `values`. These tweens can be arranged using the `duration`, `easings`, and `times` properties.
### Method
N/A (Configuration Object)
### Endpoint
N/A (Configuration Object)
### Parameters
#### Options
- **type** (string) - Optional - Set to `"keyframes"` to use keyframes animation. Defaults to `"tween"`.
- **times** (number[]) - Optional - An array of numbers between 0 and 1, where `1` represents the `total` duration. Each value represents at which point during the animation each item in the animation target should be hit. Defaults to an array of evenly-spread durations.
- **ease** (Easing | Easing[]) - Optional - An array of easing functions for each generated tween, or a single easing function applied to all tweens. This array should be one item less than `values`.
- **duration** (number) - Optional - The total duration of the animation. Defaults to `0.3`.
- **repeatDelay** (number) - Optional - Delay before repeating the animation.
- **values** (any[]) - Required - An array of values to tween between.
### Request Example
```json
{
"type": "keyframes",
"duration": 1,
"values": [0, 100, 50, 200],
"times": [0, 0.3, 0.7, 1],
"ease": "easeInOut"
}
```
### Response
#### Success Response (N/A - Configuration Object)
This is a configuration object for an animation, not a typical API response.
#### Response Example
N/A
```
--------------------------------
### Update build dependencies
Source: https://svelte-motion.gradientdescent.de/
Resolve Terser unexpected token errors by updating the rollup-plugin-terser package to the latest version.
```bash
npm install --save-dev rollup-plugin-terser@latest
```
--------------------------------
### Configure Global Transitions with MotionConfig
Source: https://svelte-motion.gradientdescent.de/motionconfig
The MotionConfig component allows developers to wrap multiple Motion components to share a unified transition configuration. This simplifies animation management by applying properties like duration globally to all children.
```svelte
...
```
--------------------------------
### Accessing Svelte Motion Contexts
Source: https://svelte-motion.gradientdescent.de/API/context
Demonstrates how to retrieve Svelte Motion contexts using Svelte's getContext function, providing a fallback to the default context factory if the context is not present in the component tree.
```javascript
import { LayoutGroupContext } from 'svelte-motion';
import { getContext } from 'svelte';
const layoutGroupContext = getContext(LayoutGroupContext) || LayoutGroupContext();
```
```javascript
import { MotionConfigContext } from 'svelte-motion';
import { getContext } from 'svelte';
const motionConfigContext = getContext(MotionConfigContext) || MotionConfigContext();
```
```javascript
import { PresenceContext } from 'svelte-motion';
import { getContext } from 'svelte';
const presenceContext = getContext(PresenceContext) || PresenceContext();
```
```javascript
import { SharedLayoutContext } from 'svelte-motion';
import { getContext } from 'svelte';
const sharedLayoutContext = getContext(SharedLayoutContext) || SharedLayoutContext();
```
--------------------------------
### Cycle Through Elements with useCycle
Source: https://svelte-motion.gradientdescent.de/utilities
The `useCycle` hook returns a Svelte store that allows you to cycle through a provided list of elements. It includes a `next` method to advance to the next element in the cycle.
```javascript
import { useCycle } from 'svelte-motion';
const cycleItems = ['item1', 'item2', 'item3'];
const currentItem = useCycle(cycleItems);
// To cycle to the next item:
// currentItem.next();
// The current item can be accessed via $currentItem
```
--------------------------------
### Orchestrate Animation Timing with Svelte Motion
Source: https://svelte-motion.gradientdescent.de/API/transition
Configure the timing and sequencing of animations, including delays and stagger effects for child components. Options like `delay`, `when`, `delayChildren`, `staggerChildren`, and `staggerDirection` provide fine-grained control over animation playback.
```typescript
interface Orchestration {
delay?: number;
when?: false | "beforeChildren" | "afterChildren" | string;
delayChildren?: number;
staggerChildren?: number;
staggerDirection?: number;
}
```
--------------------------------
### Motion Component API
Source: https://svelte-motion.gradientdescent.de/API/motion
Defines the core Motion component properties and configuration for animating Svelte elements.
```APIDOC
## [COMPONENT]
### Description
The Motion component is the primary interface for applying animations to Svelte elements. It supports standard DOM elements and SVG elements via the `isSVG` prop.
### Parameters
#### Props
- **isSVG** (boolean) - Optional - Set to true if the component is an SVG element like circle or path.
- **forwardMotionProps** (boolean) - Optional - Whether to forward motion props to the underlying element.
- **initial** (boolean | Target | VariantLabels) - Optional - Initial values or variant labels to start in.
- **style** (MotionStyle) - Optional - Enhanced CSS style object supporting MotionValues.
- **transformTemplate** (function) - Optional - Custom function to generate transform strings.
### Request Example
### Response
#### Slots
- **motion** (action) - The action to pass to the child element for animation.
- **props** (object) - Unused props to be passed down to the child component.
```
--------------------------------
### Hooks: usePresence & useIsPresent
Source: https://svelte-motion.gradientdescent.de/API/presence
Hooks to track the presence state of a component within an AnimatePresence container.
```APIDOC
## usePresence
### Description
Returns a Readable store containing the presence state. If the component is exiting, it provides a `safeToRemove` function that must be called to finalize removal.
### Return Value
- **Readable<[boolean, (() => void)?]>** - Returns [true, null] (AlwaysPresent), [true] (Present), or [false, safeToRemove] (NotPresent).
## useIsPresent
### Description
Returns a simple boolean Readable store indicating whether the component is currently present in the tree.
### Return Value
- **Readable** - True if present, false if exiting.
```
--------------------------------
### Basic Motion Component Syntax in Svelte
Source: https://svelte-motion.gradientdescent.de/animation
Demonstrates the fundamental syntax for using the `Motion` component in Svelte, which is analogous to `motion.div` in framer-motion. It utilizes a slot prop to pass an action to an inner DOM element.
```svelte
```
--------------------------------
### Check Component Presence with useIsPresent
Source: https://svelte-motion.gradientdescent.de/utilities
The `useIsPresent` hook returns a readable store that indicates whether a component wrapped with `AnimatePresence` is currently mounted or exiting. This allows for conditional rendering or animations based on the component's presence.
```javascript
import { useIsPresent } from 'svelte-motion';
const isPresent = useIsPresent();
// Use the store's value in your template or script:
$: status = $isPresent ? "Hello World" : "Goodbye";
```
--------------------------------
### Define Generic Transition Properties in Svelte Motion
Source: https://svelte-motion.gradientdescent.de/API/transition
A flexible definition for transitions that can accept various animation types or a map of transition definitions. This interface allows for custom transition configurations.
```typescript
type PermissiveTransitionDefinition = { [key: string]: any };
```
--------------------------------
### Combine Transition Definitions in Svelte Motion
Source: https://svelte-motion.gradientdescent.de/API/transition
Define a transition using a map where keys represent animation states and values are specific transition definitions. This allows for complex, state-dependent animations.
```typescript
type TransitionMap = Orchestration & { [key: string]: TransitionDefinition };
```
--------------------------------
### Implement Crossfade Animation with AnimateSharedLayout
Source: https://svelte-motion.gradientdescent.de/layout
Demonstrates how to enable crossfade transitions between different layout targets by setting the type property on the AnimateSharedLayout component. This is useful for smooth visual transitions when elements appear or disappear.
```svelte
```
--------------------------------
### Animation Lifecycle Callbacks in Svelte Motion
Source: https://svelte-motion.gradientdescent.de/animation
Explains how to use lifecycle props like `onUpdate`, `onAnimationStart`, and `onAnimationComplete` with the `Motion` component in Svelte. These callbacks allow you to hook into the animation's progress and completion.
```javascript
const onUpdate = ({opacity,x}) => {//do something}
```
```svelte
{/*definition is \"myVariant\" */}}>
{/*definition is {x:100,opacity:0}*/}}/>
```
--------------------------------
### Configure MotionConfig Component
Source: https://svelte-motion.gradientdescent.de/API/mconf
The MotionConfig component acts as a provider to set default transitions and static behavior for all descendant motion components. It accepts props such as transition, isStatic, and transformPagePoint.
```svelte
```
--------------------------------
### Implement Spring Physics Animations in Svelte Motion
Source: https://svelte-motion.gradientdescent.de/API/transition
Animate elements using spring physics for realistic motion. Configure `stiffness`, `damping`, `mass`, `duration`, `bounce`, `restSpeed`, and `restDelta` to control the spring's behavior. This is the default animation type for physical values.
```typescript
interface Spring extends Repeat {
type: "spring";
stiffness?: number;
damping?: number;
mass?: number;
duration?: number;
bounce?: number;
restSpeed?: number;
restDelta?: number;
from?: number | string;
velocity?: number;
}
```
--------------------------------
### Define All Possible Transition Types in Svelte Motion
Source: https://svelte-motion.gradientdescent.de/API/transition
A union type representing all available transition definitions, including spring, tween, keyframes, inertia, just, none, and permissive definitions. This provides a comprehensive way to specify animation behavior.
```typescript
type TransitionDefinition = Tween | Spring | Keyframes | Inertia | Just | None | PermissiveTransitionDefinition;
```
--------------------------------
### Draggable Component Configuration
Source: https://svelte-motion.gradientdescent.de/API/gestures
Defines the properties and event handlers available for enabling and configuring drag gestures on Svelte Motion components.
```APIDOC
## DraggableProps
### Description
Configuration interface for enabling drag gestures on a component. Extends DragHandlers for event callbacks.
### Parameters
#### Request Body
- **drag** (boolean | "x" | "y") - Optional - Enable dragging. Defaults to false.
- **whileDrag** (VariantLabels | TargetAndTransition) - Optional - Animation properties while dragging.
- **dragConstraints** (false | BoundingBox2D | Node) - Optional - Defines the permitted draggable area.
- **dragElastic** (boolean | number | Partial) - Optional - Degree of movement outside constraints. Defaults to 0.5.
- **dragMomentum** (boolean) - Optional - Apply momentum after release. Defaults to true.
- **dragControls** (DragControls) - Optional - External controls to initiate dragging.
- **dragListener** (boolean) - Optional - Whether to attach automatic drag listeners. Defaults to true.
### Request Example
{
"drag": "x",
"dragElastic": 0.2,
"dragMomentum": true
}
```
--------------------------------
### Initialize MotionValue with useMotionValue
Source: https://svelte-motion.gradientdescent.de/API/motionvalue
Creates a MotionValue instance to track state and velocity. This is typically used for manual control or passing values into animated components.
```typescript
import { useMotionValue } from "svelte-motion";
const x = useMotionValue(0);
x.set(100);
```
--------------------------------
### Create Custom Motion Components
Source: https://svelte-motion.gradientdescent.de/motion
Developers can create reusable motion components by wrapping the Motion component and using slot props to forward events and attributes to the underlying DOM element.
```svelte
```
--------------------------------
### Basic Animation with Svelte Motion
Source: https://svelte-motion.gradientdescent.de/animation
Illustrates a simple Svelte component that uses the `Motion` component to animate a div's rotation. It employs the `animate`, `transition`, and `let:motion` props for declarative animation control.
```svelte
```
--------------------------------
### Using MotionDiv Component in Svelte
Source: https://svelte-motion.gradientdescent.de/animation
Shows how to import and use the `MotionDiv` component from 'svelte-motion', which serves as a direct equivalent to `motion.div` from framer-motion for animating div elements.
```javascript
import {MotionDiv} from 'svelte-motion'
```
--------------------------------
### Import Motion for SSR
Source: https://svelte-motion.gradientdescent.de/
Directly import the MotionSSR component to ensure compatibility with SvelteKit server-side rendering environments.
```javascript
import Motion from 'svelte-motion/src/motion/MotionSSR.svelte'
```
--------------------------------
### Configure Animation Repetition in Svelte Motion
Source: https://svelte-motion.gradientdescent.de/API/transition
Define how animations repeat, including the number of repetitions and the type of repetition. Options like `repeat`, `repeatType`, and `repeatDelay` allow for looping, reversing, or mirroring animations.
```typescript
interface Repeat {
repeat?: number;
repeatType?: "loop" | "reverse" | "mirror";
repeatDelay?: number;
}
```
--------------------------------
### Layout State Management
Source: https://svelte-motion.gradientdescent.de/API/measure
Interface representing the internal state of an element's layout, including measurements, tree scale, and projection deltas used for visual transformations.
```typescript
interface LayoutState {
isHydrated: boolean;
layout: AxisBox2D;
layoutCorrected: AxisBox2D;
treeScale: { x: number; y: number };
delta: { x: AxisDelta; y: AxisDelta };
deltaFinal: { x: AxisDelta; y: AxisDelta };
deltaTransform: string;
}
```
--------------------------------
### snapshotViewportBox Function
Source: https://svelte-motion.gradientdescent.de/API/visualelement
Records the viewport box dimensions of a given visual element. This is often used to capture the element's state before a potential mutation or re-render, allowing for accurate animations or layout calculations.
```typescript
declare function snapshotViewportBox(visualElement: VisualElement): void;
```
--------------------------------
### Create Spring Animations with useSpring
Source: https://svelte-motion.gradientdescent.de/API/motionvalue
Initializes a MotionValue that animates to new states using spring physics. It can be used as a standalone value or as a subscriber to another MotionValue.
```typescript
import { useSpring } from "svelte-motion";
const spring = useSpring(0, { stiffness: 100, damping: 10 });
spring.set(50);
```
--------------------------------
### LifecycleManager Interface
Source: https://svelte-motion.gradientdescent.de/API/animation
Provides a set of hooks to listen to animation and layout lifecycle events within a motion component.
```APIDOC
## [INTERFACE] LifecycleManager
### Description
Manages event listeners for various stages of the motion component lifecycle, including layout measurements and animation progress.
### Methods
- **onAnimationStart** (callback: AnimationStartListener) - Registers a callback when the animation begins.
- **onAnimationComplete** (callback: AnimationCompleteListener) - Registers a callback when the animation completes.
- **onUpdate** (callback: UpdateListener) - Registers a callback fired with latest motion values (max once per frame).
- **onLayoutMeasure** (callback: LayoutMeasureListener) - Registers a callback for layout measurement updates.
### Response Example
{
"onAnimationComplete": "(definition) => { console.log('Animation finished:', definition); }"
}
```
--------------------------------
### Svelte Motion Animation Options Interface
Source: https://svelte-motion.gradientdescent.de/API/animation
Defines the optional parameters that can be passed to control animations. This includes setting delays, overriding transitions, providing custom data, and specifying animation types.
```typescript
interface AnimationOptions {
delay?: number;
transitionOverride?: Transition;
custom?: any;
type?: AnimationType;
}
```
--------------------------------
### Configure DOM Event Listeners
Source: https://svelte-motion.gradientdescent.de/API/gestures
Defines the properties required to attach a direct event listener to a DOM element, bypassing standard Svelte event systems.
```typescript
interface UseDomEventProps {
ref: { current: Node } | VisualElement;
eventName: string;
handler?: EventListener;
options?: AddEventListenerOptions;
}
```
--------------------------------
### Implement Motion with Motion Action Component
Source: https://svelte-motion.gradientdescent.de/motion
The Motion component provides a flexible approach by exposing a 'motion' action via slot props. This allows developers to retain full access to native DOM events, actions, and directives.
```svelte
A big motion header
A big motion header
```
--------------------------------
### batchLayout Function
Source: https://svelte-motion.gradientdescent.de/API/visualelement
Batches layout-related read and write operations. It accepts a callback function that performs these operations and returns a cleanup function that indicates whether the layout was flushed.
```typescript
declare function batchLayout(callback: ReadWrites): () => boolean;
```
--------------------------------
### VisualElement Interface Definition
Source: https://svelte-motion.gradientdescent.de/API/visualelement
Defines the structure and capabilities of a VisualElement, including properties for tree structure, animation state, layout management, and value handling. It serves as the blueprint for all visual components in the Svelte Motion library.
```typescript
interface VisualElement {
treeType: string;
depth: number;
parent?: VisualElement;
children: Set;
variantChildren?: Set;
current: Instance | null;
layoutTree: FlatTree;
manuallyAnimateOnMount: boolean;
blockInitialAnimation?: boolean;
presenceId: number | undefined;
projection: TargetProjection;
isProjectionReady: () => boolean;
isMounted(): boolean;
mount(instance: Instance): void;
unmount(): void;
isStatic?: boolean;
getInstance(): Instance | null;
path: VisualElement[];
sortNodePosition(element: VisualElement): number;
addVariantChild(child: VisualElement): undefined | (() => void);
getClosestVariantNode(): VisualElement | undefined;
setCrossfader(crossfader: Crossfader): void;
layoutSafeToRemove?: () => void;
animateMotionValue?: typeof startAnimation;
/**
* Visibility
*/
isVisible?: boolean;
setVisibility(visibility: boolean): void;
hasValue(key: string): boolean;
addValue(key: string, value: MotionValue): void;
removeValue(key: string): void;
getValue(key: string): undefined | MotionValue;
getValue(key: string, defaultValue: string | number): MotionValue;
getValue(key: string, defaultValue?: string | number): undefined | MotionValue;
forEachValue(callback: (value: MotionValue, key: string) => void): void;
readValue(key: string): string | number | undefined | null;
setBaseTarget(key: string, value: string | number | null): void;
getBaseTarget(key: string): number | string | undefined | null;
getStaticValue(key: string): number | string | undefined;
setStaticValue(key: string, value: number | string): void;
getLatestValues(): ResolvedValues;
scheduleRender(): void;
setProps(props: MotionProps): void;
getProps(): MotionProps;
getVariant(name: string): Variant | undefined;
getDefaultTransition(): Transition | undefined;
getVariantContext(startAtParent?: boolean): undefined | {
initial?: string | string[];
animate?: string | string[];
exit?: string | string[];
whileHover?: string | string[];
whileDrag?: string | string[];
whileFocus?: string | string[];
whileTap?: string | string[];
};
build(): RenderState;
syncRender(): void;
enableLayoutProjection(): void;
lockProjectionTarget(): void;
unlockProjectionTarget(): void;
rebaseProjectionTarget(force?: boolean, sourceBox?: AxisBox2D): void;
measureViewportBox(withTransform?: boolean): AxisBox2D;
getLayoutState: () => LayoutState;
getProjectionParent: () => VisualElement | false;
getProjectionAnimationProgress(): MotionPoint;
setProjectionTargetAxis(axis: "x" | "y", min: number, max: number, isRelative?: boolean): void;
startLayoutAnimation(axis: "x" | "y", transition: Transition, isRelative: boolean): Promise;
stopLayoutAnimation(): void;
updateLayoutProjection(): void;
updateTreeLayoutProjection(): void;
resolveRelativeTargetBox(): void;
makeTargetAnimatable(target: TargetAndTransition, isLive?: boolean): TargetAndTransition;
scheduleUpdateLayoutProjection(): void;
notifyLayoutReady(config?: SharedLayoutAnimationConfig): void;
pointTo(element: VisualElement): void;
resetTransform(): void;
restoreTransform(): void;
shouldResetTransform(): boolean;
isPresent: boolean;
presence: Presence;
isPresenceRoot?: boolean;
prevDragCursor?: Point2D;
prevViewportBox?: AxisBox2D;
getLayoutId(): string | undefined;
animationState?: AnimationState;
}
```
--------------------------------
### visualElement Factory Function
Source: https://svelte-motion.gradientdescent.de/API/visualelement
A factory function that creates a VisualElement instance. It takes a VisualElementConfig and returns a function that, when called with VisualElementOptions, produces a VisualElement. This allows for flexible configuration and instantiation of visual elements.
```typescript
declare function visualElement (config: VisualElementConfig) => (visualElementOptions: VisualElementOptions, options?: Options) => VisualElement;
```
--------------------------------
### VisualState Interface
Source: https://svelte-motion.gradientdescent.de/API/visualelement
Represents the state of a VisualElement, including its render state, latest animated values, and an optional mount function. This interface is generic and can be adapted to different rendering contexts.
```typescript
interface VisualState {
renderState: RenderState;
latestValues: ResolvedValues;
mount?: (instance: Instance) => void;
}
```
--------------------------------
### AnimationProps Interface
Source: https://svelte-motion.gradientdescent.de/API/animation
Defines the core properties used to control animations, variants, and transitions on motion components.
```APIDOC
## [INTERFACE] AnimationProps
### Description
Defines the configuration properties for motion components to manage animations, exit states, and variant-based orchestration.
### Parameters
#### Request Body
- **animate** (AnimationControls | TargetAndTransition | VariantLabels | boolean) - Optional - Values to animate to, variant label(s), or AnimationControls.
- **exit** (TargetAndTransition | VariantLabels) - Optional - Target to animate to when the component is removed from the tree. Requires AnimatePresence.
- **variants** (Variants) - Optional - Defines animation states organized by name for orchestration.
- **transition** (Transition) - Optional - Default transition configuration used if none is defined in animate.
### Request Example
{
"animate": { "opacity": 1 },
"variants": { "visible": { "opacity": 1 }, "hidden": { "opacity": 0 } },
"transition": { "duration": 0.3 }
}
```
--------------------------------
### Svelte Motion Visual Element Lifecycles Interface
Source: https://svelte-motion.gradientdescent.de/API/animation
Defines callback functions for key lifecycle events related to visual elements in Svelte Motion. This includes updates to viewport bounding boxes, layout measurements, and animation start/completion.
```typescript
interface VisualElementLifecycles {
onViewportBoxUpdate: (box: AxisBox2D, delta: BoxDelta) => void;
onBeforeLayoutMeasure: (box: AxisBox2D) => void;
onLayoutMeasure: (box: AxisBox2D, prevBox: AxisBox2D) => void;
onUpdate: (latest: ResolvedValues) => void;
onAnimationStart: () => void;
onAnimationComplete: (definition: AnimationDefinition) => void;
}
```
--------------------------------
### useVelocity
Source: https://svelte-motion.gradientdescent.de/API/motionvalue
Creates a MotionValue that tracks and updates based on the velocity of a provided MotionValue.
```APIDOC
## useVelocity
### Description
Creates a MotionValue that updates when the velocity of the provided MotionValue changes.
### Parameters
- **value** (MotionValue) - Required - The source MotionValue to track.
### Methods
- **reset** (value: MotionValue) - Updates the props of the velocity motion value.
### Response
- **MotionValue** - A MotionValue representing the current velocity.
```
--------------------------------
### VisualElementOptions Interface
Source: https://svelte-motion.gradientdescent.de/API/visualelement
Defines the options object passed to a VisualElement during its creation or update. It includes the visual state, parent and variant parent elements, snapshot values, presence ID, motion props, and a flag to block initial animations.
```typescript
interface VisualElementOptions {
visualState: VisualState;
parent?: VisualElement;
variantParent?: VisualElement;
snapshot?: ResolvedValues;
presenceId?: number | undefined;
props: MotionProps;
blockInitialAnimation?: boolean;
}
```
--------------------------------
### Detect User Preference for Reduced Motion with useReducedMotion
Source: https://svelte-motion.gradientdescent.de/utilities
The `useReducedMotion` hook returns a store containing a boolean value. This value indicates whether the user has system-level preferences set to reduce motion, allowing for adaptive animations.
```javascript
import { useReducedMotion } from 'svelte-motion';
const shouldReduceMotion = useReducedMotion();
// Use the store's value to conditionally apply animations:
$: slideOutX = $shouldReduceMotion ? '0' : '-100%';
```
--------------------------------
### WithDepth Interface
Source: https://svelte-motion.gradientdescent.de/API/visualelement
A simple interface representing an object with a depth property, likely used for hierarchical ordering or processing.
```typescript
interface WithDepth {
depth: number;
}
```
--------------------------------
### Define Tap Gesture Handlers
Source: https://svelte-motion.gradientdescent.de/API/gestures
Defines the interface for tap gesture callbacks and the whileTap animation state. Used to manage interactive press states on components.
```typescript
interface TapHandlers {
onTap?: (event: MouseEvent | TouchEvent | PointerEvent, info: TapInfo) => void;
onTapStart?: (event: MouseEvent | TouchEvent | PointerEvent, info: TapInfo) => void;
onTapCancel?: (event: MouseEvent | TouchEvent | PointerEvent, info: TapInfo) => void;
whileTap?: VariantLabels | TargetAndTransition;
}
```
--------------------------------
### Manage Hierarchical Elements with FlatTree
Source: https://svelte-motion.gradientdescent.de/API/visualelement
The FlatTree class provides a mechanism to manage nested visual elements. It includes methods to add or remove children and iterate through the tree structure using a callback function.
```typescript
class FlatTree {
add: (child: WithDepth) => void;
remove: (child: WithDepth) => void;
forEach: (callback: (child: WithDepth) => void) => void;
}
```
--------------------------------
### Animate on Focus
Source: https://svelte-motion.gradientdescent.de/gestures
The whileFocus prop allows for animations when an input or focusable element receives focus. This is useful for highlighting active form fields.
```svelte
```
--------------------------------
### Svelte Motion Animation Props Interface
Source: https://svelte-motion.gradientdescent.de/API/animation
Defines the core properties used to control animations on Svelte Motion components. These include 'animate' for target values, 'exit' for animations when components are removed, 'variants' for named animation states, and 'transition' for default animation settings.
```typescript
interface AnimationProps {
animate: AnimationControls | TargetAndTransition | VariantLabels | boolean;
exit: TargetAndTransition | VariantLabels;
variants: Variants;
transition: Transition;
}
```
--------------------------------
### Svelte Motion Animation Playback Controls
Source: https://svelte-motion.gradientdescent.de/API/animation
Provides a simple interface for controlling the playback of animations. The primary method available is 'stop', which immediately halts any ongoing animation.
```typescript
interface AnimationPlaybackControls {
stop: () => void;
}
```
--------------------------------
### Svelte Motion Animation State Management
Source: https://svelte-motion.gradientdescent.de/API/animation
An interface for managing the state of animations, including animating changes, setting active states, and retrieving animation details. It allows for fine-grained control over the animation lifecycle.
```typescript
interface AnimationState {
animateChanges: (options?: AnimationOptions, type?: AnimationType) => Promise;
setActive: (type: AnimationType, isActive: boolean, options?: AnimationOptions) => Promise;
setAnimateFunction: (fn: any) => void;
isAnimated(key: string): boolean;
getState: () => {
[key: string]: AnimationTypeState;
};
}
```
--------------------------------
### Motion Transform Properties
Source: https://svelte-motion.gradientdescent.de/API/motion
Definition of transform-related properties available for motion animations.
```APIDOC
## [INTERFACE] MotionTransform
### Description
Defines the set of transform properties that can be animated, including position, rotation, scale, and skew.
### Properties
- **x, y, z** (string | number | MotionValue) - Position coordinates.
- **rotate, rotateX, rotateY, rotateZ** (string | number | MotionValue) - Rotation values.
- **scale, scaleX, scaleY, scaleZ** (string | number | MotionValue) - Scaling factors.
- **skew, skewX, skewY, skewZ** (string | number | MotionValue) - Skew values.
- **perspective** (string | number | MotionValue) - Perspective depth.
```
--------------------------------
### Define Axis and Bounding Box Structures
Source: https://svelte-motion.gradientdescent.de/API/measure
Core interfaces for representing spatial data in Svelte Motion. These structures allow for generic axis-based calculations and 2D bounding box transformations.
```typescript
type Axis = { min: number; max: number };
type AxisBox2D = { x: Axis; y: Axis };
interface AxisDelta {
translate: number;
scale: number;
origin: number;
originPoint: number;
}
interface BoundingBox2D {
top: number;
left: number;
bottom: number;
right: number;
}
```
--------------------------------
### Inertia Transition
Source: https://svelte-motion.gradientdescent.de/API/transition
An animation that decelerates a value based on its initial velocity, often used for inertial scrolling. It supports min/max boundaries with spring-like behavior and target modification.
```APIDOC
## Inertia Transition
### Description
An animation that decelerates a value based on its initial velocity, usually used to implement inertial scrolling. Optionally, `min` and `max` boundaries can be defined, and inertia will snap to these with a spring animation.
### Method
N/A (Configuration Object)
### Endpoint
N/A (Configuration Object)
### Parameters
#### Options
- **type** (string) - Optional - Set to `"inertia"` to use inertia animation. Defaults to `"tween"`.
- **modifyTarget** ((v: number) => number) - Optional - A function that receives the automatically-calculated target and returns a new one. Useful for snapping the target to a grid.
- **bounceStiffness** (number) - Optional - If `min` or `max` is set, this affects the stiffness of the bounce spring. Defaults to `500`.
- **bounceDamping** (number) - Optional - If `min` or `max` is set, this affects the damping of the bounce spring. Defaults to `10`.
- **power** (number) - Optional - A higher power value equals a further target. Defaults to `0.8`.
- **timeConstant** (number) - Optional - Adjusting the time constant will change the duration of the deceleration. Defaults to `700`.
- **restDelta** (number) - Optional - End the animation if the distance to the animation target is below this value, and the absolute speed is below `restSpeed`. Defaults to `0.01`.
- **min** (number) - Optional - Minimum constraint. If set, the value will "bump" against this value.
- **max** (number) - Optional - Maximum constraint. If set, the value will "bump" against this value.
- **from** (number | string) - Optional - The value to animate from. Defaults to the current state of the animating value.
- **velocity** (number) - Optional - The initial velocity of the animation. Defaults to the current velocity of the component.
### Request Example
```json
{
"type": "inertia",
"modifyTarget": "(v) => Math.round(v / 10) * 10",
"min": 0,
"max": 500
}
```
### Response
#### Success Response (N/A - Configuration Object)
This is a configuration object for an animation, not a typical API response.
#### Response Example
N/A
```
--------------------------------
### useViewportScroll
Source: https://svelte-motion.gradientdescent.de/API/motionvalue
Returns MotionValues that update in response to viewport scroll events.
```APIDOC
## useViewportScroll
### Description
Returns MotionValues that update when the viewport scrolls. Note: Avoid setting body or html to height: 100% as it interferes with progress measurement.
### Parameters
- **ref** ({current?: Node}) - Optional - A reference to the scrollable element.
### Response
- **ScrollMotionValues** - An object containing MotionValues for scroll progress and position.
```
--------------------------------
### Subscribe to MotionValue changes
Source: https://svelte-motion.gradientdescent.de/API/motionvalue
Demonstrates how to subscribe to a MotionValue to react to state updates. The subscribe method returns an unsubscriber function to prevent memory leaks.
```typescript
const unsubscribe = motionValue.onChange((v) => {
console.log("Value changed to:", v);
});
// Call when component is destroyed
unsubscribe();
```
--------------------------------
### Cycle through values with useCycle
Source: https://svelte-motion.gradientdescent.de/API/utils
The useCycle hook creates a custom Svelte store that cycles through a provided array of items. It provides a next method to advance the state, useful for toggling animations or states.
```typescript
const [x, cycleX] = useCycle(0, 100, 200);
// Cycle to next value
cycleX();
// Cycle to specific index
cycleX(0);
```
--------------------------------
### Combine Motion Values with useMotionTemplate
Source: https://svelte-motion.gradientdescent.de/motionvalue
Combines multiple motion values into a single string template using `useMotionTemplate`. This is useful for creating complex style properties like CSS `drop-shadow` that depend on the positions of multiple motion values.
```javascript
import { Motion, useMotionValue, useMotionTemplate } from "svelte-motion";
const x = useMotionValue(0);
const y = useMotionValue(0);
const shadow = useMotionTemplate`drop-shadow(${x}px ${y}px 20px rgba(0,0,0,0.8))`
```