···
const animations = new WeakMap<HTMLElement, Animation>();
export interface TransitionOptions {
duration?: number | string;
easing?: string | [number, number, number, number];
+
const applyKeyframe = (
+
): [Keyframe, Keyframe] => {
const computed = getComputedStyle(element);
const from: Keyframe = {};
for (const propName in style) {
+
(typeof style[propName] === 'number' && propName !== 'opacity'
if (/^--/.test(propName)) {
from[key] = element.style.getPropertyValue(propName);
+
element.style.setProperty(key, value);
if (propName === 'transform') {
···
from[key] = computed[key];
+
element.style[key] = value;
+
if (from[key] !== value) to[key] = value;
+
const animate = (element: HTMLElement, options: TransitionOptions) => {
const effect: KeyframeEffectOptions = {
typeof options.duration === 'number'
···
const prevAnimation = animations.get(element);
if (prevAnimation) prevAnimation.cancel();
+
const keyframes = applyKeyframe(element, options.to || {});
+
const animation = element.animate(keyframes, effect);
animation.playbackRate = 1.000001;
animation.currentTime = 0.1;
const media = matchMedia('(prefers-reduced-motion: reduce)');
+
const computed = getComputedStyle(element);
+
for (const propName in keyframes[1]) {
const value = /^--/.test(propName)
? element.style.getPropertyValue(propName)
+
if (value !== keyframes[0][propName]) {
···
+
const promise = new Promise<unknown>((resolve, reject) => {
animations.set(element, animation);
animation.addEventListener('cancel', reject);
animation.addEventListener('finish', resolve);
+
return promise.then(() => {
+
applyKeyframe(element, options.final!);
export function useStyleTransition<T extends HTMLElement>(
···
): [boolean, (options: TransitionOptions) => Promise<void>] {
if (!options) options = {};
+
const style = options.to || {};
const [state, setState] = useState<[boolean, Style]>([false, style]);
if (JSON.stringify(style) !== JSON.stringify(state[1])) {