···
1
+
import type { Style, Ref } from './types';
2
+
import { useState, useCallback } from 'react';
3
+
import { useLayoutEffect } from './utils/react';
5
+
interface AnimationState {
6
+
animation: Animation;
10
+
const animations = new WeakMap<HTMLElement, AnimationState>();
12
+
export interface TransitionOptions {
14
+
duration?: number | string;
15
+
easing?: string | [number, number, number, number];
18
+
const animate = (element: HTMLElement, options: TransitionOptions) => {
19
+
const prevState = animations.get(element);
20
+
const prevTo = prevState ? prevState.to : {};
21
+
const computed = getComputedStyle(element);
22
+
const from: Keyframe = {};
23
+
const to: Keyframe = {};
25
+
let changed = !prevState;
26
+
for (const propName in options.style) {
27
+
let value: string = options.style[propName];
28
+
if (typeof value === 'number') (value as string) += 'px';
31
+
if (/^--/.test(propName)) {
33
+
from[key] = element.style.getPropertyValue(propName);
34
+
element.style.setProperty(key, (to[key] = options.style[propName]));
36
+
if (propName === 'float') {
38
+
} else if (propName === 'offset') {
40
+
} else if (propName === 'transform') {
43
+
('' + value || '').replace(/\w+\((?:0\w*\s*)+\)\s*/g, '') || 'none';
45
+
key = propName.replace(/[A-Z]/g, '-$&').toLowerCase();
48
+
from[key] = computed[key];
49
+
element.style[key] = to[key] = value;
52
+
changed = changed || prevState!.to[key] !== to[key];
55
+
if (!changed && Object.keys(to).length === Object.keys(prevTo).length) return;
57
+
const effect: KeyframeEffectOptions = {
59
+
typeof options.duration === 'number'
60
+
? options.duration * 1000
62
+
easing: Array.isArray(options.easing)
63
+
? `cubic-bezier(${options.easing.join(', ')})`
67
+
if (prevState) prevState.animation.cancel();
69
+
const animation = element.animate([from, to], effect);
70
+
animation.playbackRate = 1.000001;
71
+
animation.currentTime = 0.1;
73
+
let animating = false;
74
+
for (const propName in from) {
75
+
const value = /^--/.test(propName)
76
+
? element.style.getPropertyValue(propName)
77
+
: computed[propName];
78
+
if (value !== from[propName]) {
85
+
animations.delete(element);
90
+
return new Promise<unknown>((resolve, reject) => {
91
+
animations.set(element, { animation, to });
92
+
animation.addEventListener('cancel', reject);
93
+
animation.addEventListener('finish', resolve);
97
+
export function useTransition<T extends HTMLElement>(
99
+
options: TransitionOptions
100
+
): [boolean, (options: TransitionOptions) => Promise<void>] {
101
+
const [animating, setAnimating] = useState(false);
103
+
const animateTo = useCallback(
104
+
(options: TransitionOptions) => {
105
+
const animation = animate(ref.current!, options);
107
+
setAnimating(true);
110
+
setAnimating(false);
114
+
return Promise.resolve();
120
+
useLayoutEffect(() => {
121
+
animateTo(options);
122
+
}, [animateTo, options.style]);
124
+
return [animating, animateTo];