···
+
import type { Style, Ref } from './types';
+
import { useState, useCallback } from 'react';
+
import { useLayoutEffect } from './utils/react';
+
interface AnimationState {
+
const animations = new WeakMap<HTMLElement, AnimationState>();
+
export interface TransitionOptions {
+
duration?: number | string;
+
easing?: string | [number, number, number, number];
+
const animate = (element: HTMLElement, options: TransitionOptions) => {
+
const prevState = animations.get(element);
+
const prevTo = prevState ? prevState.to : {};
+
const computed = getComputedStyle(element);
+
const from: Keyframe = {};
+
const to: Keyframe = {};
+
let changed = !prevState;
+
for (const propName in options.style) {
+
let value: string = options.style[propName];
+
if (typeof value === 'number') (value as string) += 'px';
+
if (/^--/.test(propName)) {
+
from[key] = element.style.getPropertyValue(propName);
+
element.style.setProperty(key, (to[key] = options.style[propName]));
+
if (propName === 'float') {
+
} else if (propName === 'offset') {
+
} else if (propName === 'transform') {
+
('' + value || '').replace(/\w+\((?:0\w*\s*)+\)\s*/g, '') || 'none';
+
key = propName.replace(/[A-Z]/g, '-$&').toLowerCase();
+
from[key] = computed[key];
+
element.style[key] = to[key] = value;
+
changed = changed || prevState!.to[key] !== to[key];
+
if (!changed && Object.keys(to).length === Object.keys(prevTo).length) return;
+
const effect: KeyframeEffectOptions = {
+
typeof options.duration === 'number'
+
? options.duration * 1000
+
easing: Array.isArray(options.easing)
+
? `cubic-bezier(${options.easing.join(', ')})`
+
if (prevState) prevState.animation.cancel();
+
const animation = element.animate([from, to], effect);
+
animation.playbackRate = 1.000001;
+
animation.currentTime = 0.1;
+
for (const propName in from) {
+
const value = /^--/.test(propName)
+
? element.style.getPropertyValue(propName)
+
if (value !== from[propName]) {
+
animations.delete(element);
+
return new Promise<unknown>((resolve, reject) => {
+
animations.set(element, { animation, to });
+
animation.addEventListener('cancel', reject);
+
animation.addEventListener('finish', resolve);
+
export function useTransition<T extends HTMLElement>(
+
options: TransitionOptions
+
): [boolean, (options: TransitionOptions) => Promise<void>] {
+
const [animating, setAnimating] = useState(false);
+
const animateTo = useCallback(
+
(options: TransitionOptions) => {
+
const animation = animate(ref.current!, options);
+
return Promise.resolve();
+
useLayoutEffect(() => {
+
}, [animateTo, options.style]);
+
return [animating, animateTo];