Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/src/examples/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export default {
// When true, this will enable animations even if the user has indicated
// they don’t want them via prefers-reduced-motion.
disrespectUserMotionPreference: false,
// Milliseconds between the entry animations of items added at the same
// time, so a list "cascades" in (default: 0)
stagger: 0,
// Turn individual animations off and keep the defaults for the rest,
// e.g. { remain: false } when a drag-and-drop library already moves items.
// (default: all true)
Expand Down
31 changes: 30 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,30 @@ const handleMutations: MutationCallback = (mutations) => {
const elements = getElements(mutations)
// If elements is "false" that means this mutation that should be ignored.
if (elements) {
elements.forEach((el) => animate(el))
// Count the elements added to each parent in this batch (in DOM order) so
// the `stagger` option can offset their entry animations.
const addCounts = new Map<Element, number>()
elements.forEach((el) => {
if (NEW in el || !coords.has(el)) {
const target = getTarget(el)
const count = target ? addCounts.get(target) ?? 0 : 0
if (target) addCounts.set(target, count + 1)
addIndex = count
} else {
addIndex = 0
}
animate(el)
})
addIndex = 0
}
}

/**
* The position of the element currently being added within its batch, used
* for the `stagger` option.
*/
let addIndex = 0

/**
*
* @param entries - Elements that have been resized.
Expand Down Expand Up @@ -721,6 +741,9 @@ function add(el: Element) {
{
duration: (pluginOrOptions as AutoAnimateOptions).duration * 1.5,
easing: "ease-in",
// Hold the first (hidden) keyframe while waiting for a staggered start.
delay: ((pluginOrOptions as AutoAnimateOptions).stagger ?? 0) * addIndex,
fill: "backwards",
},
)
} else {
Expand Down Expand Up @@ -971,6 +994,12 @@ export interface AutoAnimateOptions {
* Default: all `true`.
*/
animations?: Partial<Record<AutoAnimateAction, boolean>>
/**
* Milliseconds between the entry animations of elements added at the same
* time (for example a list loading in), so they appear one after another.
* Only affects `add`; plugins control their own timing. Default: 0
*/
stagger?: number
/**
* Called when an element's animation finishes (not when it is cancelled or
* skipped). For `remove`, the element has already been taken out of the DOM.
Expand Down
51 changes: 51 additions & 0 deletions tests/e2e/stagger.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { test, expect } from '@playwright/test'
import { fileURLToPath } from 'node:url'

const fixtureUrl = `/@fs${fileURLToPath(new URL('../fixtures/removal.html', import.meta.url))}`
const moduleUrl = `/@fs${fileURLToPath(new URL('../../src/index.ts', import.meta.url))}`

async function delays(page: import('@playwright/test').Page, opts: Record<string, unknown>) {
return page.evaluate(async ({ moduleUrl, opts }) => {
const { default: autoAnimate } = (await import(moduleUrl)) as typeof import('../../src/index')
const parent = document.createElement('ul')
document.body.prepend(parent)
const make = (id: string) => {
const li = document.createElement('li')
li.id = id
li.textContent = id
li.style.height = '20px'
return li
}
parent.append(make('keep'))
autoAnimate(parent, { duration: 200, ...opts })
await new Promise((r) => setTimeout(r, 50))
// add four items in one go, before the existing one (which then moves)
parent.prepend(make('a'), make('b'), make('c'), make('d'))
await new Promise((r) => setTimeout(r, 20))
const out: Record<string, number> = {}
for (const a of document.getAnimations()) {
const t = (a.effect as KeyframeEffect).target as Element
if (t?.id) out[t.id] = Number((a.effect as KeyframeEffect).getTiming().delay)
}
const hiddenWhileWaiting = getComputedStyle(parent.querySelector('#d')!).opacity
parent.remove()
return { out, hiddenWhileWaiting }
}, { moduleUrl, opts })
}

test.beforeEach(async ({ page }) => {
await page.emulateMedia({ reducedMotion: 'no-preference' })
await page.goto(fixtureUrl)
})

test('stagger offsets entry animations of elements added together', async ({ page }) => {
const { out, hiddenWhileWaiting } = await delays(page, { stagger: 100 })
expect([out.a, out.b, out.c, out.d]).toEqual([0, 100, 200, 300])
expect(out.keep ?? 0).toBe(0) // moves are never delayed
expect(hiddenWhileWaiting).toBe('0') // waiting items stay hidden
})

test('no stagger by default', async ({ page }) => {
const { out } = await delays(page, {})
expect([out.a, out.b, out.c, out.d]).toEqual([0, 0, 0, 0])
})
Loading