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
9 changes: 8 additions & 1 deletion docs/src/examples/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {}
})`,
},
}
73 changes: 61 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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 },
)
}

/**
Expand All @@ -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)
Expand All @@ -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 },
)
}

/**
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 },
)
}

/**
Expand Down Expand Up @@ -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<Record<AutoAnimateAction, boolean>>
/**
* 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
*/
Expand Down
87 changes: 87 additions & 0 deletions tests/e2e/animations-option.spec.ts
Original file line number Diff line number Diff line change
@@ -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<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.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)
})
Loading