···
const animations = new WeakMap<HTMLElement, Animation>();
export interface TransitionOptions {
8
-
style?: Style | null;
9
+
final?: Style | null;
duration?: number | string;
easing?: string | [number, number, number, number];
13
-
const animate = (element: HTMLElement, options: TransitionOptions) => {
14
-
const style = options.style || {};
14
+
const applyKeyframe = (
15
+
element: HTMLElement,
17
+
): [Keyframe, Keyframe] => {
const computed = getComputedStyle(element);
const from: Keyframe = {};
for (const propName in style) {
20
-
let value: string = style[propName];
21
-
if (typeof value === 'number' && propName !== 'opacity') {
22
-
(value as string) += 'px';
26
+
(typeof style[propName] === 'number' && propName !== 'opacity'
if (/^--/.test(propName)) {
from[key] = element.style.getPropertyValue(propName);
29
-
element.style.setProperty(key, (to[key] = value));
32
+
element.style.setProperty(key, value);
if (propName === 'transform') {
···
from[key] = computed[key];
40
-
element.style[key] = to[key] = value;
43
+
element.style[key] = value;
46
+
if (from[key] !== value) to[key] = value;
52
+
const animate = (element: HTMLElement, options: TransitionOptions) => {
const effect: KeyframeEffectOptions = {
typeof options.duration === 'number'
···
const prevAnimation = animations.get(element);
if (prevAnimation) prevAnimation.cancel();
57
-
const animation = element.animate([from, to], effect);
66
+
const keyframes = applyKeyframe(element, options.to || {});
67
+
const animation = element.animate(keyframes, effect);
animation.playbackRate = 1.000001;
animation.currentTime = 0.1;
const media = matchMedia('(prefers-reduced-motion: reduce)');
74
+
const computed = getComputedStyle(element);
64
-
for (const propName in from) {
76
+
for (const propName in keyframes[1]) {
const value = /^--/.test(propName)
? element.style.getPropertyValue(propName)
68
-
if (value !== from[propName]) {
80
+
if (value !== keyframes[0][propName]) {
···
81
-
return new Promise<unknown>((resolve, reject) => {
93
+
const promise = new Promise<unknown>((resolve, reject) => {
animations.set(element, animation);
animation.addEventListener('cancel', reject);
animation.addEventListener('finish', resolve);
99
+
if (options.final) {
100
+
return promise.then(() => {
101
+
applyKeyframe(element, options.final!);
export function useStyleTransition<T extends HTMLElement>(
···
): [boolean, (options: TransitionOptions) => Promise<void>] {
if (!options) options = {};
94
-
const style = options.style || {};
114
+
const style = options.to || {};
const [state, setState] = useState<[boolean, Style]>([false, style]);
if (JSON.stringify(style) !== JSON.stringify(state[1])) {