diff --git a/docs/src/examples/config/index.ts b/docs/src/examples/config/index.ts index 6e96c619..97743290 100644 --- a/docs/src/examples/config/index.ts +++ b/docs/src/examples/config/index.ts @@ -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) diff --git a/src/index.ts b/src/index.ts index e0888367..8e47c380 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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() + 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. @@ -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 { @@ -971,6 +994,12 @@ export interface AutoAnimateOptions { * Default: all `true`. */ animations?: Partial> + /** + * 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. diff --git a/tests/e2e/stagger.spec.ts b/tests/e2e/stagger.spec.ts new file mode 100644 index 00000000..d8baa9e5 --- /dev/null +++ b/tests/e2e/stagger.spec.ts @@ -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) { + 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 = {} + 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]) +})