Debian Codegraph @

src/modules/awaitAnimations.ts

raw
1 import { queryAll } from '../utils.js';
2 import type Swup from '../Swup.js';
3 import type { Options } from '../Swup.js';
4
5 const TRANSITION = 'transition';
6 const ANIMATION = 'animation';
7
8 type AnimationType = typeof TRANSITION | typeof ANIMATION;
9 type AnimationEndEvent = `${AnimationType}end`;
10 type AnimationProperty = 'Delay' | 'Duration';
11 type AnimationStyleKey = `${AnimationType}${AnimationProperty}` | 'transitionProperty';
12
13 export type AnimationDirection = 'in' | 'out';
14
15 /**
16 * Return a Promise that resolves when all CSS animations and transitions
17 * are done on the page. Filters by selector or takes elements directly.
18 */
19 export async function awaitAnimations(
20 this: Swup,
21 {
22 selector,
23 elements
24 }: {
25 selector: Options['animationSelector'];
26 elements?: NodeListOf<HTMLElement> | HTMLElement[];
27 }
28 ): Promise<void> {
29 // Allow usage of swup without animations: { animationSelector: false }
30 if (selector === false && !elements) {
31 return;
32 }
33
34 // Allow passing in elements
35 let animatedElements: HTMLElement[] = [];
36 if (elements) {
37 animatedElements = Array.from(elements);
38 } else if (selector) {
39 animatedElements = queryAll(selector, document.body);
40 // Warn if no elements match the selector, but keep things going
41 if (!animatedElements.length) {
42 console.warn(`[swup] No elements found matching animationSelector \`${selector}\``);
43 return;
44 }
45 }
46
47 const awaitedAnimations = animatedElements.map((el) => awaitAnimationsOnElement(el));
48 const hasAnimations = awaitedAnimations.filter(Boolean).length > 0;
49 if (!hasAnimations) {
50 if (selector) {
51 console.warn(
52 `[swup] No CSS animation duration defined on elements matching \`${selector}\``
53 );
54 }
55 return;
56 }
57
58 await Promise.all(awaitedAnimations);
59 }
60
61 function awaitAnimationsOnElement(element: HTMLElement): Promise<void> | false {
62 const { type, timeout, propCount } = getTransitionInfo(element);
63
64 // Resolve immediately if no transition defined
65 if (!type || !timeout) {
66 return false;
67 }
68
69 return new Promise((resolve) => {
70 const endEvent: AnimationEndEvent = `${type}end`;
71 const startTime = performance.now();
72 let propsTransitioned = 0;
73
74 const end = () => {
75 element.removeEventListener(endEvent, onEnd);
76 resolve();
77 };
78
79 const onEnd = (event: TransitionEvent | AnimationEvent) => {
80 // Skip transitions on child elements
81 if (event.target !== element) {
82 return;
83 }
84
85 // Skip transitions that happened before we started listening
86 const elapsedTime = (performance.now() - startTime) / 1000;
87 if (elapsedTime < event.elapsedTime) {
88 return;
89 }
90
91 // End if all properties have transitioned
92 if (++propsTransitioned >= propCount) {
93 end();
94 }
95 };
96
97 setTimeout(() => {
98 if (propsTransitioned < propCount) {
99 end();
100 }
101 }, timeout + 1);
102
103 element.addEventListener(endEvent, onEnd);
104 });
105 }
106
107 function getTransitionInfo(element: Element) {
108 const styles = window.getComputedStyle(element);
109
110 const transitionDelays = getStyleProperties(styles, `${TRANSITION}Delay`);
111 const transitionDurations = getStyleProperties(styles, `${TRANSITION}Duration`);
112 const transitionTimeout = calculateTimeout(transitionDelays, transitionDurations);
113
114 const animationDelays = getStyleProperties(styles, `${ANIMATION}Delay`);
115 const animationDurations = getStyleProperties(styles, `${ANIMATION}Duration`);
116 const animationTimeout = calculateTimeout(animationDelays, animationDurations);
117
118 const timeout = Math.max(transitionTimeout, animationTimeout);
119 const type: AnimationType | null =
120 timeout > 0 ? (transitionTimeout > animationTimeout ? TRANSITION : ANIMATION) : null;
121 const propCount = type
122 ? type === TRANSITION
123 ? transitionDurations.length
124 : animationDurations.length
125 : 0;
126
127 return {
128 type,
129 timeout,
130 propCount
131 };
132 }
133
134 export function getStyleProperties(styles: CSSStyleDeclaration, key: AnimationStyleKey): string[] {
135 return (styles[key] || '').split(', ');
136 }
137
138 export function calculateTimeout(delays: string[], durations: string[]): number {
139 while (delays.length < durations.length) {
140 delays = delays.concat(delays);
141 }
142
143 return Math.max(...durations.map((duration, i) => toMs(duration) + toMs(delays[i])));
144 }
145
146 export function toMs(time: string): number {
147 return parseFloat(time) * 1000;
148 }