···
import { useState, useCallback } from 'react';
import { useLayoutEffect } from './utils/react';
+
const animations = new WeakMap<HTMLElement, Animation>();
export interface TransitionOptions {
duration?: number | string;
easing?: string | [number, number, number, number];
const animate = (element: HTMLElement, options: TransitionOptions) => {
+
const style = options.style || {};
const computed = getComputedStyle(element);
const from: Keyframe = {};
+
for (const propName in style) {
+
let value: string = 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] = value));
+
if (propName === 'transform') {
('' + value || '').replace(/\w+\((?:0\w*\s*)+\)\s*/g, '') || 'none';
···
from[key] = computed[key];
element.style[key] = to[key] = value;
const effect: KeyframeEffectOptions = {
typeof options.duration === 'number'
? options.duration * 1000
+
: options.duration || 1000,
easing: Array.isArray(options.easing)
? `cubic-bezier(${options.easing.join(', ')})`
+
: options.easing || 'ease',
+
const prevAnimation = animations.get(element);
+
if (prevAnimation) prevAnimation.cancel();
const animation = element.animate([from, to], effect);
animation.playbackRate = 1.000001;
···
return new Promise<unknown>((resolve, reject) => {
+
animations.set(element, animation);
animation.addEventListener('cancel', reject);
animation.addEventListener('finish', resolve);
···
export function useTransition<T extends HTMLElement>(
+
options?: TransitionOptions
): [boolean, (options: TransitionOptions) => Promise<void>] {
+
if (!options) options = {};
+
const style = options.style || {};
+
const [state, setState] = useState<[boolean, Style]>([false, style]);
+
if (JSON.stringify(style) !== JSON.stringify(state[1])) {
+
setState([true, style]);
const animateTo = useCallback(
(options: TransitionOptions) => {
+
const updateAnimating = (animating: boolean) => {
+
state[0] !== animating ? [animating, state[1]] : state
const animation = animate(ref.current!, options);
+
updateAnimating(false);
+
updateAnimating(false);
return Promise.resolve();
···
+
}, [animateTo, state[1]]);
+
return [state[0], animateTo];