All files / src/internal/client/dom/elements transitions.js

97.02% Statements 456/470
94.49% Branches 103/109
80.76% Functions 21/26
96.95% Lines 446/460

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 4612x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 779x 779x 779x 2x 2x 2x 2x 2x 1746x 1746x 1746x 624x 624x 624x 624x 624x 624x 624x 624x 2x 2x 2x 2x 2x 900x 900x 900x 900x 900x 1850x 1850x 1746x 1746x 1746x 1746x 900x 900x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 84x 104x 104x 82x 82x 82x 82x 82x 82x 82x 82x 58x 82x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 104x 104x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 104x 104x                   104x 104x 104x 104x 104x 104x 104x 104x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 500x 500x 500x 500x 500x 474x 474x 474x 474x 474x 302x 302x 302x 302x 302x 302x 302x 302x 276x 276x 276x 276x 276x 276x 276x 151x 151x 276x 276x 276x 276x 56x 56x 276x 302x 26x 26x 474x 474x 268x 268x 268x 268x 224x 224x 224x 224x 224x 224x 224x 224x 224x 128x 128x 128x 224x 224x 224x 224x 34x 34x 224x 224x 224x 224x 224x 268x 44x 44x 474x 474x 472x 472x 472x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 241x 241x 241x 168x 168x 168x 168x 7x 14x 14x 7x 168x 168x 168x 241x 241x 218x 218x 218x 218x 241x 474x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 542x 542x 542x 542x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 524x 542x 542x 542x 15x 15x 15x 15x 15x 15x 15x 15x 509x 509x 509x 509x 542x 542x 542x 542x 542x 542x 542x 542x 542x 542x 542x 542x 542x 82x 82x 82x 82x 82x 82x 82x 82x 82x 2x 2x 2x 12x 12x 2x 82x 82x 898x 898x 898x 898x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 30x 30x 30x 22x 22x 82x 82x 86x 86x 86x 86x 86x 86x 86x     82x 82x 542x 427x 427x 209x 209x 427x 427x 814x 276x 276x 276x 276x 538x 814x 526x 526x 526x 538x 538x 427x 427x 509x 509x 509x 289x 289x 289x 509x 509x 76x 76x 509x 509x 26x 26x 26x 509x 509x 76x 76x 76x 509x 509x  
/** @import { AnimateFn, Animation, AnimationConfig, EachItem, Effect, Task, TransitionFn, TransitionManager } from '#client' */
import { noop, is_function } from '../../../shared/utils.js';
import { effect } from '../../reactivity/effects.js';
import { current_effect, untrack } from '../../runtime.js';
import { raf } from '../../timing.js';
import { loop } from '../../loop.js';
import { should_intro } from '../../render.js';
import { current_each_item } from '../blocks/each.js';
import { TRANSITION_GLOBAL, TRANSITION_IN, TRANSITION_OUT } from '../../../../constants.js';
import { BLOCK_EFFECT, EFFECT_RAN, EFFECT_TRANSPARENT } from '../../constants.js';
import { queue_micro_task } from '../task.js';
 
/**
 * @param {Element} element
 * @param {'introstart' | 'introend' | 'outrostart' | 'outroend'} type
 * @returns {void}
 */
function dispatch_event(element, type) {
	element.dispatchEvent(new CustomEvent(type));
}
 
/**
 * @param {string} style
 * @returns {string}
 */
function css_style_from_camel_case(style) {
	const parts = style.split('-');
	if (parts.length === 1) return parts[0];
	return (
		parts[0] +
		parts
			.slice(1)
			.map(/** @param {any} word */ (word) => word[0].toUpperCase() + word.slice(1))
			.join('')
	);
}
 
/**
 * @param {string} css
 * @returns {Keyframe}
 */
function css_to_keyframe(css) {
	/** @type {Keyframe} */
	const keyframe = {};
	const parts = css.split(';');
	for (const part of parts) {
		const [property, value] = part.split(':');
		if (!property || value === undefined) break;
 
		const formatted_property = css_style_from_camel_case(property.trim());
		keyframe[formatted_property] = value.trim();
	}
	return keyframe;
}
 
/** @param {number} t */
const linear = (t) => t;
 
/**
 * Called inside keyed `{#each ...}` blocks (as `$.animation(...)`). This creates an animation manager
 * and attaches it to the block, so that moves can be animated following reconciliation.
 * @template P
 * @param {Element} element
 * @param {() => AnimateFn<P | undefined>} get_fn
 * @param {(() => P) | null} get_params
 */
export function animation(element, get_fn, get_params) {
	var item = /** @type {EachItem} */ (current_each_item);
 
	/** @type {DOMRect} */
	var from;
 
	/** @type {DOMRect} */
	var to;
 
	/** @type {Animation | undefined} */
	var animation;
 
	/** @type {null | { position: string, width: string, height: string, transform: string }} */
	var original_styles = null;
 
	item.a ??= {
		element,
		measure() {
			from = this.element.getBoundingClientRect();
		},
		apply() {
			animation?.abort();
 
			to = this.element.getBoundingClientRect();
 
			if (
				from.left !== to.left ||
				from.right !== to.right ||
				from.top !== to.top ||
				from.bottom !== to.bottom
			) {
				const options = get_fn()(this.element, { from, to }, get_params?.());
 
				animation = animate(
					this.element,
					options,
					undefined,
					1,
					() => {
						animation?.abort();
						animation = undefined;
					},
					undefined
				);
			}
		},
		fix() {
			// If an animation is already running, transforming the element is likely to fail,
			// because the styles applied by the animation take precedence. In the case of crossfade,
			// that means the `translate(...)` of the crossfade transition overrules the `translate(...)`
			// we would apply below, leading to the element jumping somewhere to the top left.
			if (element.getAnimations().length) return;
 
			// It's important to destructure these to get fixed values - the object itself has getters,
			// and changing the style to 'absolute' can for example influence the width.
			var { position, width, height } = getComputedStyle(element);
 
			if (position !== 'absolute' && position !== 'fixed') {
				var style = /** @type {HTMLElement | SVGElement} */ (element).style;
 
				original_styles = {
					position: style.position,
					width: style.width,
					height: style.height,
					transform: style.transform
				};
 
				style.position = 'absolute';
				style.width = width;
				style.height = height;
				var to = element.getBoundingClientRect();
 
				if (from.left !== to.left || from.top !== to.top) {
					var transform = `translate(${from.left - to.left}px, ${from.top - to.top}px)`;
					style.transform = style.transform ? `${style.transform} ${transform}` : transform;
				}
			}
		},
		unfix() {
			if (original_styles) {
				var style = /** @type {HTMLElement | SVGElement} */ (element).style;

				style.position = original_styles.position;
				style.width = original_styles.width;
				style.height = original_styles.height;
				style.transform = original_styles.transform;
			}
		}
	};
 
	// in the case of a `<svelte:element>`, it's possible for `$.animation(...)` to be called
	// when an animation manager already exists, if the tag changes. in that case, we need to
	// swap out the element rather than creating a new manager, in case it happened at the same
	// moment as a reconciliation
	item.a.element = element;
}
 
/**
 * Called inside block effects as `$.transition(...)`. This creates a transition manager and
 * attaches it to the current effect — later, inside `pause_effect` and `resume_effect`, we
 * use this to create `intro` and `outro` transitions.
 * @template P
 * @param {number} flags
 * @param {HTMLElement} element
 * @param {() => TransitionFn<P | undefined>} get_fn
 * @param {(() => P) | null} get_params
 * @returns {void}
 */
export function transition(flags, element, get_fn, get_params) {
	var is_intro = (flags & TRANSITION_IN) !== 0;
	var is_outro = (flags & TRANSITION_OUT) !== 0;
	var is_both = is_intro && is_outro;
	var is_global = (flags & TRANSITION_GLOBAL) !== 0;
 
	/** @type {'in' | 'out' | 'both'} */
	var direction = is_both ? 'both' : is_intro ? 'in' : 'out';
 
	/** @type {AnimationConfig | ((opts: { direction: 'in' | 'out' }) => AnimationConfig) | undefined} */
	var current_options;
 
	var inert = element.inert;
 
	/** @type {Animation | undefined} */
	var intro;
 
	/** @type {Animation | undefined} */
	var outro;
 
	/** @type {(() => void) | undefined} */
	var reset;
 
	function get_options() {
		// If a transition is still ongoing, we use the existing options rather than generating
		// new ones. This ensures that reversible transitions reverse smoothly, rather than
		// jumping to a new spot because (for example) a different `duration` was used
		return (current_options ??= get_fn()(element, get_params?.(), { direction }));
	}
 
	/** @type {TransitionManager} */
	var transition = {
		is_global,
		in() {
			element.inert = inert;
 
			// abort the outro to prevent overlap with the intro
			outro?.abort();
			// abort previous intro (can happen if an element is intro'd, then outro'd, then intro'd again)
			intro?.abort();
 
			if (is_intro) {
				dispatch_event(element, 'introstart');
				intro = animate(
					element,
					get_options(),
					outro,
					1,
					() => {
						dispatch_event(element, 'introend');
						intro = current_options = undefined;
					},
					is_both
						? undefined
						: () => {
								intro = current_options = undefined;
							}
				);
			} else {
				reset?.();
			}
		},
		out(fn) {
			// abort previous outro (can happen if an element is outro'd, then intro'd, then outro'd again)
			outro?.abort();
 
			if (is_outro) {
				element.inert = true;
 
				dispatch_event(element, 'outrostart');
				outro = animate(
					element,
					get_options(),
					intro,
					0,
					() => {
						dispatch_event(element, 'outroend');
						outro = current_options = undefined;
						fn?.();
					},
					is_both
						? undefined
						: () => {
								outro = current_options = undefined;
							}
				);
 
				// TODO arguably the outro should never null itself out until _all_ outros for this effect have completed...
				// in that case we wouldn't need to store `reset` separately
				reset = outro.reset;
			} else {
				fn?.();
			}
		},
		stop: () => {
			intro?.abort();
			outro?.abort();
		}
	};
 
	var e = /** @type {Effect} */ (current_effect);
 
	(e.transitions ??= []).push(transition);
 
	// if this is a local transition, we only want to run it if the parent (branch) effect's
	// parent (block) effect is where the state change happened. we can determine that by
	// looking at whether the block effect is currently initializing
	if (is_intro && should_intro) {
		let run = is_global;
 
		if (!run) {
			var block = /** @type {Effect | null} */ (e.parent);
 
			// skip over transparent blocks (e.g. snippets, else-if blocks)
			while (block && (block.f & EFFECT_TRANSPARENT) !== 0) {
				while ((block = block.parent)) {
					if ((block.f & BLOCK_EFFECT) !== 0) break;
				}
			}
 
			run = !block || (block.f & EFFECT_RAN) !== 0;
		}
 
		if (run) {
			effect(() => {
				untrack(() => transition.in());
			});
		}
	}
}
 
/**
 * Animates an element, according to the provided configuration
 * @param {Element} element
 * @param {AnimationConfig | ((opts: { direction: 'in' | 'out' }) => AnimationConfig)} options
 * @param {Animation | undefined} counterpart The corresponding intro/outro to this outro/intro
 * @param {number} t2 The target `t` value — `1` for intro, `0` for outro
 * @param {(() => void) | undefined} on_finish Called after successfully completing the animation
 * @param {(() => void) | undefined} on_abort Called if the animation is aborted
 * @returns {Animation}
 */
function animate(element, options, counterpart, t2, on_finish, on_abort) {
	var is_intro = t2 === 1;
 
	if (is_function(options)) {
		// In the case of a deferred transition (such as `crossfade`), `option` will be
		// a function rather than an `AnimationConfig`. We need to call this function
		// once DOM has been updated...
		/** @type {Animation} */
		var a;
 
		queue_micro_task(() => {
			var o = options({ direction: is_intro ? 'in' : 'out' });
			a = animate(element, o, counterpart, t2, on_finish, on_abort);
		});
 
		// ...but we want to do so without using `async`/`await` everywhere, so
		// we return a facade that allows everything to remain synchronous
		return {
			abort: () => a.abort(),
			deactivate: () => a.deactivate(),
			reset: () => a.reset(),
			t: (now) => a.t(now)
		};
	}
 
	counterpart?.deactivate();
 
	if (!options?.duration) {
		on_finish?.();
		return {
			abort: noop,
			deactivate: noop,
			reset: noop,
			t: () => t2
		};
	}
 
	const { delay = 0, css, tick, easing = linear } = options;
 
	var start = raf.now() + delay;
	var t1 = counterpart?.t(start) ?? 1 - t2;
	var delta = t2 - t1;
 
	var duration = options.duration * Math.abs(delta);
	var end = start + duration;
 
	/** @type {globalThis.Animation} */
	var animation;
 
	/** @type {Task} */
	var task;
 
	if (css) {
		// run after a micro task so that all transitions that are lining up and are about to run can correctly measure the DOM
		queue_micro_task(() => {
			// WAAPI
			var keyframes = [];
			var n = Math.ceil(duration / (1000 / 60)); // `n` must be an integer, or we risk missing the `t2` value
 
			// In case of a delayed intro, apply the initial style for the duration of the delay;
			// else in case of a fade-in for example the element would be visible until the animation starts
			if (is_intro && delay > 0) {
				let m = Math.ceil(delay / (1000 / 60));
				let keyframe = css_to_keyframe(css(0, 1));
				for (let i = 0; i < m; i += 1) {
					keyframes.push(keyframe);
				}
			}
 
			for (var i = 0; i <= n; i += 1) {
				var t = t1 + delta * easing(i / n);
				var styles = css(t, 1 - t);
				keyframes.push(css_to_keyframe(styles));
			}
 
			animation = element.animate(keyframes, {
				delay: is_intro ? 0 : delay,
				duration: duration + (is_intro ? delay : 0),
				easing: 'linear',
				fill: 'forwards'
			});
 
			animation.finished
				.then(() => {
					on_finish?.();
 
					if (t2 === 1) {
						animation.cancel();
					}
				})
				.catch((e) => {
					// Error for DOMException: The user aborted a request. This results in two things:
					// - startTime is `null`
					// - currentTime is `null`
					// We can't use the existence of an AbortError as this error and error code is shared
					// with other Web APIs such as fetch().
 
					if (animation.startTime !== null && animation.currentTime !== null) {
						throw e;
					}
				});
		});
	} else {
		// Timer
		if (t1 === 0) {
			tick?.(0, 1); // TODO put in nested effect, to avoid interleaved reads/writes?
		}
 
		task = loop((now) => {
			if (now >= end) {
				tick?.(t2, 1 - t2);
				on_finish?.();
				return false;
			}
 
			if (now >= start) {
				var p = t1 + delta * easing((now - start) / duration);
				tick?.(p, 1 - p);
			}
 
			return true;
		});
	}
 
	return {
		abort: () => {
			animation?.cancel();
			task?.abort();
			on_abort?.();
		},
		deactivate: () => {
			on_finish = undefined;
			on_abort = undefined;
		},
		reset: () => {
			if (t2 === 0) {
				tick?.(1, 0);
			}
		},
		t: (now) => {
			var t = t1 + delta * easing((now - start) / duration);
			return Math.min(1, Math.max(0, t));
		}
	};
}