Designing reusable animation library
I've planned a reusable animation function using the Web Animations API that accepts Elements or ShadowRoots by animating their host elements, handles prefers-reduced-motion by skipping or minimizing animation, and returns a Promise resolving when the animation finishes. Next, I'll provide a concise ES module with defaults and usage examples, ensuring it gracefully supports shadow DOM contexts.
Below is a small, self‑contained ES module you can drop into a project to give you a single, reusable “entry” animation function. It uses the Web Animations API under the hood, resolves a Promise when the animation completes, and short‑circuits for users who have prefers-reduced-motion enabled.
// entry-animations.js
// Re‑use the same media query object so we can respond to changes if needed.
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
/**
* Animate an element into view.
*
* @param {Element|ShadowRoot} target An element to animate, or a shadow root (in which case its host will be animated).
* @param {Object} [opts]
* @param {Keyframe[]|PropertyIndexedKeyframes} [opts.keyframes] Custom keyframes. Defaults to a simple fade/slide.
* @param {number|KeyframeAnimationOptions} [opts.options] Options passed to Element.animate().
*
* @returns {Promise<void>} A promise that resolves when the animation finishes.
*/
export function animateEntry(target, opts = {}) {
// Resolve the actual element to animate.
const element = target instanceof ShadowRoot ? target.host : target;
if (!element || typeof element.animate !== 'function') {
return Promise.reject(
new TypeError('animateEntry target must be an Element or ShadowRoot whose host supports .animate()')
);
}
// Default keyframes and options can be overridden.
const keyframes = opts.keyframes || [
{ opacity: 0, transform: 'translateY(1rem)' },
{ opacity: 1, transform: 'translateY(0)' }
];
const options = {
duration: 300,
easing: 'ease-out',
fill: 'forwards',
...(opts.options || opts) // allow passing plain duration/options directly as second arg
};
// Respect reduced motion preferences: immediately apply the end state and resolve.
if (prefersReducedMotion.matches) {
const last = Array.isArray(keyframes)
? keyframes[keyframes.length - 1]
: Object.fromEntries(Object.keys(keyframes).map(p => [p, keyframes[p][keyframes[p].length - 1]]));
Object.assign(element.style, last);
return Promise.resolve();
}
// Start the animation.
const animation = element.animate(keyframes, options);
// The Web Animations API exposes a .finished promise in modern browsers.
// Fallback to onfinish if needed.
const finished = animation.finished || new Promise(resolve => {
animation.addEventListener('finish', () => resolve(), { once: true });
});
return finished.then(() => {
// Ensure final styles persist if fill mode wasn't set.
if (options.fill !== 'forwards' && options.fill !== 'both') {
Object.assign(element.style, Array.isArray(keyframes) ? keyframes[keyframes.length - 1] : {});
}
});
}
Usage in the light DOM
import { animateEntry } from './entry-animations.js';
const box = document.querySelector('.box');
animateEntry(box).then(() => {
console.log('Animation complete!');
});
Usage inside a shadow DOM
class MyCard extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' }).innerHTML = `<style>/* … */</style><div class="card">Hello</div>`;
}
connectedCallback() {
const card = this.shadowRoot.querySelector('.card');
animateEntry(card);
}
}
customElements.define('my-card', MyCard);
The function will animate elements regardless of whether they live in the main document or within a shadow tree because it operates on Element.animate(), which is available in both contexts. For users who prefer reduced motion, it skips the animation and applies the final keyframe immediately.