useWaapiTimeline
useWaapiTimeline builds a timeline of CSS tweens on the browser's native
Web Animations
clock, so the browser drives the animation and not a JavaScript loop. It is
not auto-imported, so import it from #nanime/experimental, or from
nanime/experimental in a Vue app.
Build a timeline
import { useWaapiTimeline } from '#nanime/experimental'
const box = useTemplateRef('box')
const step = ref('idle')
const timeline = useWaapiTimeline({ defaults: { duration: 600 } })
timeline
.tween(box, { translate: ['0px', '160px'] })
.tween(box, { rotate: ['0deg', '180deg'], at: '< + 50%' })
.point('turned', '< + 100%')
.tween(box, { scale: ['1', '1.25', '0.5'], at: '< + 50%' })
.callback(() => (step.value = 'moving'), 0)
.callback(() => (step.value = 'turned'), 'turned')
<template>
<div class="flex h-14 w-56 items-center">
<div ref="box" class="size-10 rounded-lg bg-primary" />
</div>
</template>
point(name, at) names a time, so later tweens and callbacks can start
there.
Place tweens with at
timeline
.point('open', 2000)
.tween(box, { translate: ['0px', '160px'], at: 400, duration: 1000 })
.tween(box, { opacity: [0, 1], at: 'open + 150' })
The table shows where the last tween starts for each form of at, so
replace 'open + 150' to try them. A delay on that tween is added to the
time.
at | Starts at | How |
|---|---|---|
| omitted | 1400 | The previous tween's end. The first tween starts at 0. |
120 | 120 | 120ms from the start. Negative numbers are allowed. |
'open' | 2000 | The time of a point registered earlier with point(). |
'<' | 400 | The previous tween's start. |
'< + 150' | 550 | 150ms after the previous start. |
'< + 20%' | 600 | 20% of the previous duration (200ms) after its start. |
'< + 0.2s' | 600 | s and ms work as units. |
'open + 150' | 2150 | 150ms after open. |
< shift, such as '20%' or '120', is
read as a point name, so it is an error unless a point has that name. Write a
time as a number: 120.Run a function at a particular time
import { useWaapiTimeline } from '#nanime/experimental'
const box = useTemplateRef('box')
const last = ref('none')
const timeline = useWaapiTimeline()
timeline
.point('move', 0)
.point('mid move', 400)
.point('moved', 800)
.tween(box, { opacity: [0, 1], duration: 400, at: 'move' })
.tween(box, { translate: ['0px', '160px'], duration: 800, at: 'move' })
.callback(() => (last.value = 'move'), 'move')
.callback(() => (last.value = 'mid move'), 'mid move')
.callback(() => (last.value = 'moved'), 'moved')
<template>
<div class="flex h-12 w-56 items-center">
<div ref="box" class="size-10 rounded-lg bg-primary" />
</div>
</template>
A callback runs fn when the playhead crosses at, going forward or
backward. at takes the same forms as a tween, and callback({ fn, at }) is
the same call. Without at it runs at 0. seek() skips the callbacks it
jumps over.
'<'.0 is an error.Control playback
While the timeline runs or is paused, reverse() plays backward from the
current playhead. Before the first play or after the end, it starts from the
end. To drive a scrub bar, call seek(value * timeline.duration) on input,
where value is the bar's position from 0 to 1.
progress, currentTime, paused and completed are plain getters that
do not update a template.
Only isRunning is a ref.API
function useWaapiTimeline(options?: WaapiTimelineOptions): WaapiTimelineRef
Options
duration. Defaults to 300.setup() it plays after the
current synchronous code, so register the tweens right after creating the
timeline. Defaults to false.'auto' gives the first tween on each property of an element
fill: 'both' and every later one fill: 'forwards'. Any other value
applies to every tween as-is. Defaults to 'auto'.'auto', a later tween on the same property does not apply its from
before it starts, so each end value holds until the next tween begins. With
'both' it does, so the first tween in a sequence on one property is never
seen. With 'none', the element shows its own CSS outside each tween.true, playback jumps to the end it moves toward: the last
frame going forward, the first going backward. Callbacks run once in
playback order. Defaults to the module's
reducedMotion setting.true when the timeline starts running, and with false each
time its status changes to paused, finished or idle.Tween parameters
timeline.tween(panel, {
opacity: [0, 1, 0.6],
transform: { from: 'translateY(12px)', to: 'translateY(0)' },
duration: 400,
ease: 'ease-out',
at: 'open',
})
The target is an element, an array of elements, a CSS selector, a component
instance, or a template ref or getter that returns one. Every key other than
at, duration, delay and ease is a CSS property. Its value takes one
of these forms:
| Value | Example | Animates |
|---|---|---|
| One value | opacity: 1 | From the element's current value to it. |
[from, to] | opacity: [0, 1] | From the first value to the second. |
{ from, to } | opacity: { from: 0 } | Either key can be left out, and the element's current value fills the gap. |
| Three or more stops | opacity: [0, 1, 0.6] | Through each stop in turn, evenly spaced. |
The values in a pair or in stops are all numbers or all strings. When stops need different timing or easing, use one tween per stop.
ease shapes the progress of the whole tween, not each segment
between stops. Keyframe offsets and per-keyframe easing are not supported.A tween with a from starts there, not where an earlier tween on the same
property left off. Give each later tween the previous one's to as its
from:
timeline
.tween(box, { translate: ['0px', '80px'] })
// wrong: translate: ['0px', '160px'] jumps the box back to 0px
.tween(box, { translate: ['80px', '160px'] })
at
for every form. Defaults to the end of the previous tween, or 0 for the
first tween.defaults.duration.at. Defaults to 0.defaults.ease.translate, rotate and scale work, but lengths need units, and
AnimeJS-only names such as x and y do nothing, with no error. A
stagger() value as a CSS property is an error, and as delay or duration it
becomes 0. Use useWaapiAnimate for x,
y and stagger().Easing
ease takes a CSS easing string ('ease-out', 'cubic-bezier(...)',
'steps(...)', 'linear(...)'). Pass { forward, reverse } to use another
curve while the timeline plays backward:
timeline.tween(panel, {
opacity: [0, 1],
ease: { forward: 'ease-out', reverse: 'ease-in' },
})
reverse defaults to forward. When you call reverse() or play() while
the timeline is running or paused, a tween already in progress keeps its
current value and runs the rest of its course on the other curve.
back or elastic, a tween
can also jump slightly at the direction change. Callbacks still run at their
set times.To use an AnimeJS easing, convert it to a CSS string with waapi.convertEase():
import { waapi } from 'animejs/waapi'
import { eases } from 'animejs/easings'
timeline.tween(panel, {
opacity: [0, 1],
ease: waapi.convertEase(eases.outBack(3)),
})
'linear'.Returns
Returns a WaapiTimelineRef: a plain object whose methods do
not depend on this, so destructuring works. Every method returns the same
timeline, so calls chain. Open the Types block at the end of this section for
each member and what it does.
You can call play() or seek() in setup(). The call waits for the
component to mount, so the timeline builds once template refs point at
elements.
tween(), point() and callback() are errors after the first call to
play(), reverse(), restart(), alternate() or seek().console.error and the call is skipped.createWaapiTimeline
createWaapiTimeline() is the same timeline without mount and unmount
handling. isRunning is a plain boolean, you call cancel() when you are
done, and the module's reducedMotion setting is ignored unless you pass
isReducedMotion:
const timeline = createWaapiTimeline()
timeline.tween('.panel', { opacity: [0, 1] })
timeline.play()
Its targets are DOM elements, arrays, selectors, node lists, or a function that returns one.
interface WaapiTimelineRef {
// add steps; all three are errors after the first playback call
tween: (target: WaapiTimelineRefTarget, params: WaapiTweenParams) => WaapiTimelineRef
// (fn, at) or ({ fn, at }); at defaults to 0, a callback after the last tween moves the timeline end to its time
callback: (input: WaapiTimelineCallbackInput, at?: WaapiTimelinePosition) => WaapiTimelineRef
// register a point before the tweens that use it
point: (name: string, at: WaapiTimelinePosition) => WaapiTimelineRef
// from a pause: continue; running the other way: turn around; finished: replay from 0
play: () => WaapiTimelineRef
// play() in the other direction; finished: replay from the end
reverse: () => WaapiTimelineRef
// does nothing unless running
pause: () => WaapiTimelineRef
// continue a paused timeline in its direction
resume: () => WaapiTimelineRef
// seek to 0 and play forward
restart: () => WaapiTimelineRef
// play the other way; a timeline that has not played yet plays forward
alternate: () => WaapiTimelineRef
// ms, clamped; keeps running unless it lands on an end; skips callbacks
seek: (time: number) => WaapiTimelineRef
// remove the animations so elements show their own CSS; next play rebuilds
cancel: () => WaapiTimelineRef
// true while playing in either direction
readonly isRunning: Readonly<Ref<boolean>>
// ms, known before the first build
readonly duration: number
// ms, 0 before the first build
readonly currentTime: number
// currentTime / duration, 0 to 1
readonly progress: number
// after pause(), or a seek() that stops before the end
readonly paused: boolean
// reached an end and stopped
readonly completed: boolean
}
type WaapiTimelineElement
= | HTMLElement
| SVGElement
| HTMLElement[]
| SVGElement[]
| ComponentPublicInstance
type WaapiTimelineRefTarget
= | WaapiTimelineElement
| string
| null
| undefined
| MaybeRefOrGetter<WaapiTimelineElement | string | null | undefined>
interface WaapiTimelineCallback {
fn: () => void
at?: WaapiTimelinePosition
}
type WaapiTimelineCallbackInput = (() => void) | WaapiTimelineCallback
type WaapiTimelinePosition = number | string
type WaapiTimelineValue = string | number
type WaapiTimelinePair = readonly [string, string] | readonly [number, number]
interface WaapiTimelineRange {
from?: WaapiTimelineValue
to?: WaapiTimelineValue
}
type WaapiTimelineStops = readonly string[] | readonly number[]
type WaapiTimelineFrame = WaapiTimelineValue | WaapiTimelinePair | WaapiTimelineStops | WaapiTimelineRange
type WaapiTimelineFill = 'auto' | 'none' | 'forwards' | 'both'
interface WaapiTimelineEasePair {
forward: string
reverse?: string
}
type WaapiTimelineEase = string | WaapiTimelineEasePair
interface WaapiTimelineDefaults {
duration?: number
ease?: WaapiTimelineEase
}
interface WaapiTimelineOptions {
defaults?: WaapiTimelineDefaults
autoplay?: boolean
fill?: WaapiTimelineFill
isReducedMotion?: () => boolean
onRunningChange?: (running: boolean) => void
}
type WaapiTweenParams = {
at?: WaapiTimelinePosition
duration?: number
delay?: number
ease?: WaapiTimelineEase
} & Record<string, WaapiTimelineFrame | WaapiTimelinePosition | WaapiTimelineEase | undefined>
Avoid common mistakes
Don't use < for the previous end
timeline
.tween(first, { opacity: [0, 1] })
// wrong: at: '<' starts with first, not after it
.tween(second, { opacity: [0, 1] })
With at: '<', the second tween runs together with the first and no error
is raised. In AnimeJS < is the previous tween's end and << is its start.
Here < is the start and << is an error. Leave at out to start after the
previous tween. In AnimeJS an omitted position appends to the end of the
whole timeline, and here it follows the previous tween you registered.
Fix a tween that never runs
const panel = useTemplateRef('panel') // inside v-if="open"
timeline.tween(panel, { opacity: [0, 1] })
watch(panel, (element) => {
// wrong: timeline.play()
if (element) timeline.cancel().play()
})
The timeline looks up its targets once, at the first playback call. A target
that is null then is skipped with no error. Each time the v-if opens, Vue
also renders a new element that the old build never saw. Watch the template
ref, and call cancel() before play() so the timeline looks the ref up
again.
See also
useAnimeTimeline: the stable AnimeJS timeline with labels, stagger,sync, seek and callbacksuseWaapiAnimate: one WAAPI animation with AnimeJS value normalization- Composable lifecycle