Runtime
Motion
The svelte/motion
module exports two functions, tweened
and spring
, for creating writable stores whose values change over time after set
and update
, rather than immediately.
tweened
Tweened stores update their values over a fixed duration. The following options are available:
delay
(number
, default 0) — milliseconds before startingduration
(number
|function
, default 400) — milliseconds the tween lastseasing
(function
, defaultt => t
) — an easing functioninterpolate
(function
) — see below
store.set
and store.update
can accept a second options
argument that will override the options passed in upon instantiation.
Both functions return a Promise that resolves when the tween completes. If the tween is interrupted, the promise will never resolve.
Out of the box, Svelte will interpolate between two numbers, two arrays or two objects (as long as the arrays and objects are the same 'shape', and their 'leaf' properties are also numbers).
If the initial value is undefined
or null
, the first value change will take effect immediately. This is useful when you have tweened values that are based on props, and don't want any motion when the component first renders.
The interpolate
option allows you to tween between any arbitrary values. It must be an (a, b) => t => value
function, where a
is the starting value, b
is the target value, t
is a number between 0 and 1, and value
is the result. For example, we can use the d3-interpolate package to smoothly interpolate between two colours.
spring
A spring
store gradually changes to its target value based on its stiffness
and damping
parameters. Whereas tweened
stores change their values over a fixed duration, spring
stores change over a duration that is determined by their existing velocity, allowing for more natural-seeming motion in many situations. The following options are available:
stiffness
(number
, default0.15
) — a value between 0 and 1 where higher means a 'tighter' springdamping
(number
, default0.8
) — a value between 0 and 1 where lower means a 'springier' springprecision
(number
, default0.01
) — determines the threshold at which the spring is considered to have 'settled', where lower means more precise
As with tweened
stores, set
and update
return a Promise that resolves if the spring settles. The store.stiffness
and store.damping
properties can be changed while the spring is in motion, and will take immediate effect.
Both set
and update
can take a second argument — an object with hard
or soft
properties. { hard: true }
sets the target value immediately; { soft: n }
preserves existing momentum for n
seconds before settling. { soft: true }
is equivalent to { soft: 0.5 }
.
See a full example on the spring tutorial.
If the initial value is undefined
or null
, the first value change will take effect immediately, just as with tweened
values (see above).