From e0fcb0a75dc6960da97b23566520a26ef4588582 Mon Sep 17 00:00:00 2001 From: Justin Schroeder Date: Sun, 22 Nov 2026 14:43:49 -0500 Subject: [PATCH] feat: animations option to turn off add/remove/remain, and onAnimationEnd callback (#153, #37) --- docs/src/examples/config/index.ts | 9 ++- src/index.ts | 73 ++++++++++++++++++++---- tests/e2e/animations-option.spec.ts | 87 +++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 13 deletions(-) create mode 100644 tests/e2e/animations-option.spec.ts diff --git a/docs/src/examples/config/index.ts b/docs/src/examples/config/index.ts index 7a680f5a..6e96c619 100644 --- a/docs/src/examples/config/index.ts +++ b/docs/src/examples/config/index.ts @@ -9,7 +9,14 @@ export default { easing: 'ease-in-out', // When true, this will enable animations even if the user has indicated // they don’t want them via prefers-reduced-motion. - disrespectUserMotionPreference: false + disrespectUserMotionPreference: false, + // 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) + animations: { add: true, remove: true, remain: true }, + // Called when an element's animation finishes ('add' | 'remove' | 'remain'). + // For 'remove' the element is already out of the DOM. + onAnimationEnd: (el, action) => {} })`, }, } diff --git a/src/index.ts b/src/index.ts index e56e37c4..e0888367 100644 --- a/src/index.ts +++ b/src/index.ts @@ -607,6 +607,22 @@ function isPlugin( return typeof config === "function" } +/** + * Whether the given animation is turned on for the element (plugins always + * decide for themselves). + */ +function allowed(el: Element, action: AutoAnimateAction): boolean { + const opts = getOptions(el) + return isPlugin(opts) || opts.animations?.[action] !== false +} + +/** + * Notify the onAnimationEnd option, if any, that an animation finished. + */ +function ended(el: Element, action: AutoAnimateAction, opts = getOptions(el)) { + if (!isPlugin(opts)) opts.onAnimationEnd?.(el, action) +} + /** * The element in question is remaining in the DOM. * @param el - Element to flip @@ -615,7 +631,7 @@ function isPlugin( function remain(el: Element) { const oldCoords = coords.get(el) const newCoords = getCoords(el) - if (!isEnabled(el)) return coords.set(el, newCoords) + if (!isEnabled(el) || !allowed(el, "remain")) return coords.set(el, newCoords) if (isOffscreen(el)) { // When element is offscreen, skip FLIP to avoid broken transforms coords.set(el, newCoords) @@ -669,9 +685,14 @@ function remain(el: Element) { } animations.set(el, animation) coords.set(el, newCoords) - animation.addEventListener("finish", updatePos.bind(null, el, false), { - once: true, - }) + animation.addEventListener( + "finish", + () => { + updatePos(el, false) + ended(el, "remain") + }, + { once: true }, + ) } /** @@ -683,7 +704,7 @@ function add(el: Element) { const newCoords = getCoords(el) coords.set(el, newCoords) const pluginOrOptions = getOptions(el) - if (!isEnabled(el)) return + if (!isEnabled(el) || !allowed(el, "add")) return if (isOffscreen(el)) { // Skip entry animation if element is not visible in viewport observePosition(el) @@ -708,9 +729,14 @@ function add(el: Element) { animation.play() } animations.set(el, animation) - animation.addEventListener("finish", updatePos.bind(null, el, false), { - once: true, - }) + animation.addEventListener( + "finish", + () => { + updatePos(el, false) + ended(el, "add") + }, + { once: true }, + ) } /** @@ -761,7 +787,7 @@ function remove(el: Element) { } else { getTarget(el)?.appendChild(el) } - if (!isEnabled(el)) return cleanUp(el) + if (!isEnabled(el) || !allowed(el, "remove")) return cleanUp(el) const [top, left, width, height] = deletePosition(el) const optionsOrPlugin = getOptions(el) @@ -817,9 +843,16 @@ function remove(el: Element) { animation.play() } animations.set(el, animation) - animation.addEventListener("finish", () => cleanUp(el, styleReset), { - once: true, - }) + animation.addEventListener( + "finish", + () => { + // Read the options before cleanUp detaches the element from its parent. + const opts = getOptions(el) + cleanUp(el, styleReset) + ended(el, "remove", opts) + }, + { once: true }, + ) } /** @@ -932,8 +965,24 @@ export interface AutoAnimateOptions { * recommended to use this. */ disrespectUserMotionPreference?: boolean + /** + * Turn individual animations off while keeping the defaults for the rest, + * e.g. `{ remain: false }` when another library already moves items. + * Default: all `true`. + */ + animations?: Partial> + /** + * 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. + */ + onAnimationEnd?: (el: Element, action: AutoAnimateAction) => void } +/** + * The kinds of animation AutoAnimate runs. + */ +export type AutoAnimateAction = "add" | "remove" | "remain" + /** * A custom plugin config object */ diff --git a/tests/e2e/animations-option.spec.ts b/tests/e2e/animations-option.spec.ts new file mode 100644 index 00000000..03edcca5 --- /dev/null +++ b/tests/e2e/animations-option.spec.ts @@ -0,0 +1,87 @@ +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))}` + +test.beforeEach(async ({ page }) => { + await page.emulateMedia({ reducedMotion: 'no-preference' }) + await page.goto(fixtureUrl) +}) + +/** Runs add, move (remain) and remove against a fresh list with the given options. */ +async function run(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.appendChild(parent) + for (const n of ['a', 'b', 'c']) { + const li = document.createElement('li') + li.id = n + li.textContent = n + li.style.height = '20px' + parent.appendChild(li) + } + const ended: string[] = [] + autoAnimate(parent, { + duration: 300, + ...opts, + onAnimationEnd: (el: Element, action: string) => ended.push(`${action}:${el.id}`), + }) + await new Promise((r) => setTimeout(r, 50)) + const record = () => + [...new Set(document.getAnimations().map((a) => ((a.effect as KeyframeEffect | null)?.target as Element | null)?.id).filter(Boolean))].sort() as string[] + // add + const d = document.createElement('li') + d.id = 'd' + d.textContent = 'd' + d.style.height = '20px' + parent.prepend(d) // also moves a, b, c (remain) + await new Promise((r) => setTimeout(r, 30)) + const onAdd = record() + await new Promise((r) => setTimeout(r, 600)) + // remove + parent.querySelector('#b')!.remove() + await new Promise((r) => setTimeout(r, 30)) + const onRemove = record() + const removedStillInDom = !!document.getElementById('b') + await new Promise((r) => setTimeout(r, 700)) + return { + onAdd, + onRemove, + ended: ended.sort(), + removedStillInDom, + bGone: !document.getElementById('b'), + } + }, { moduleUrl, opts }) +} + +test('runs every animation by default and reports each one ending', async ({ page }) => { + const r = await run(page, {}) + expect(r.onAdd).toEqual(['a', 'b', 'c', 'd']) + expect(r.onRemove).toContain('b') + expect(r.removedStillInDom).toBe(true) // animating out + expect(r.bGone).toBe(true) + expect(r.ended).toContain('add:d') + expect(r.ended).toContain('remain:a') + expect(r.ended).toContain('remove:b') +}) + +test('animations: { remain: false } keeps add/remove but skips moves', async ({ page }) => { + const r = await run(page, { animations: { remain: false } }) + expect(r.onAdd).toEqual(['d']) + expect(r.onRemove).toEqual(['b']) + expect(r.ended.filter((e) => e.startsWith('remain'))).toEqual([]) + expect(r.ended).toContain('add:d') + expect(r.ended).toContain('remove:b') +}) + +test('animations: { add: false, remove: false } only animates moves', async ({ page }) => { + const r = await run(page, { animations: { add: false, remove: false } }) + expect(r.onAdd).toEqual(['a', 'b', 'c']) + expect(r.onRemove).not.toContain('b') + expect(r.removedStillInDom).toBe(false) // removed immediately + expect(r.bGone).toBe(true) + expect(r.ended.some((e) => e.startsWith('remain'))).toBe(true) + expect(r.ended.some((e) => e.startsWith('add') || e.startsWith('remove'))).toBe(false) +})