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

97.19% Statements 416/428
94.68% Branches 89/94
79.31% Functions 23/29
97.13% Lines 407/419

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 4202x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 787x 787x 787x 2x 2x 2x 2x 2x 1834x 1834x 1834x 636x 636x 636x 636x 636x 636x 636x 636x 2x 2x 2x 2x 2x 972x 972x 972x 972x 972x 1940x 1940x 1834x 1834x 1834x 1834x 972x 972x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 94x 114x 114x 92x 92x 92x 92x 92x 92x 92x 92x 64x 92x 28x 28x 28x 28x 28x 28x 28x 114x 114x 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 114x 114x                   114x 114x 114x 114x 114x 114x 114x 114x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 508x 508x 508x 508x 508x 508x 508x 490x 490x 490x 490x 490x 304x 304x 304x 26x 26x 26x 26x 278x 304x 92x 92x 92x 92x 278x 278x 278x 278x 153x 153x 153x 153x 153x 278x 490x 490x 274x 44x 44x 44x 44x 230x 230x 230x 230x 230x 230x 126x 126x 230x 490x 490x 488x 488x 488x 490x 490x 490x 490x 490x 490x 490x 490x 490x 490x 243x 243x 243x 170x 170x 170x 170x 7x 14x 14x 7x 170x 170x 170x 243x 243x 220x 220x 220x 220x 243x 490x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 554x 554x 554x 554x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 536x 554x 554x 554x 15x 15x 15x 15x 15x 15x 15x 15x 15x 521x 521x 521x 521x 521x 554x 255x 201x 201x 255x 255x 48x 48x 48x 255x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 521x 519x 84x 84x 84x 924x 924x 924x 924x 84x 519x 519x 592x 592x 592x 592x 592x 519x 519x 519x 411x 868x 522x 522x 522x 522x 522x 411x 411x 519x 521x 521x 521x 521x 294x 294x 294x 521x 521x 521x 521x 521x 601x 601x 601x 601x 601x 521x 521x 78x 521x 521x 26x 26x 26x 521x 521x 521x 521x  
/** @import { AnimateFn, Animation, AnimationConfig, EachItem, Effect, TransitionFn, TransitionManager } from '#client' */
import { noop, is_function } from '../../../shared/utils.js';
import { effect } from '../../reactivity/effects.js';
import { active_effect, untrack } from '../../runtime.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;
				});
			}
		},
		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;
 
	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?.() ?? /** @type {P} */ ({}), {
			direction
		}));
	}
 
	/** @type {TransitionManager} */
	var transition = {
		is_global,
		in() {
			element.inert = inert;
 
			if (!is_intro) {
				outro?.abort();
				outro?.reset?.();
				return;
			}
 
			if (!is_outro) {
				// if we intro then outro then intro again, we want to abort the first intro,
				// if it's not a bidirectional transition
				intro?.abort();
			}
 
			dispatch_event(element, 'introstart');
 
			intro = animate(element, get_options(), outro, 1, () => {
				dispatch_event(element, 'introend');
 
				// Ensure we cancel the animation to prevent leaking
				intro?.abort();
				intro = current_options = undefined;
			});
		},
		out(fn) {
			if (!is_outro) {
				fn?.();
				current_options = undefined;
				return;
			}
 
			element.inert = true;
 
			dispatch_event(element, 'outrostart');
 
			outro = animate(element, get_options(), intro, 0, () => {
				dispatch_event(element, 'outroend');
				fn?.();
			});
		},
		stop: () => {
			intro?.abort();
			outro?.abort();
		}
	};
 
	var e = /** @type {Effect} */ (active_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) {
		var 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)} on_finish Called after successfully completing the animation
 * @returns {Animation}
 */
function animate(element, options, counterpart, t2, on_finish) {
	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 the DOM has been updated...
		/** @type {Animation} */
		var a;
		var aborted = false;
 
		queue_micro_task(() => {
			if (aborted) return;
			var o = options({ direction: is_intro ? 'in' : 'out' });
			a = animate(element, o, counterpart, t2, on_finish);
		});
 
		// ...but we want to do so without using `async`/`await` everywhere, so
		// we return a facade that allows everything to remain synchronous
		return {
			abort: () => {
				aborted = true;
				a?.abort();
			},
			deactivate: () => a.deactivate(),
			reset: () => a.reset(),
			t: () => a.t()
		};
	}
 
	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 keyframes = [];
 
	if (is_intro && counterpart === undefined) {
		if (tick) {
			tick(0, 1); // TODO put in nested effect, to avoid interleaved reads/writes?
		}
 
		if (css) {
			var styles = css_to_keyframe(css(0, 1));
			keyframes.push(styles, styles);
		}
	}
 
	var get_t = () => 1 - t2;
 
	// create a dummy animation that lasts as long as the delay (but with whatever devtools
	// multiplier is in effect). in the common case that it is `0`, we keep it anyway so that
	// the CSS keyframes aren't created until the DOM is updated
	var animation = element.animate(keyframes, { duration: delay });
 
	animation.onfinish = () => {
		// for bidirectional transitions, we start from the current position,
		// rather than doing a full intro/outro
		var t1 = counterpart?.t() ?? 1 - t2;
		counterpart?.abort();
 
		var delta = t2 - t1;
		var duration = /** @type {number} */ (options.duration) * Math.abs(delta);
		var keyframes = [];
 
		if (duration > 0) {
			if (css) {
				var n = Math.ceil(duration / (1000 / 60)); // `n` must be an integer, or we risk missing the `t2` value
 
				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));
				}
			}
 
			get_t = () => {
				var time = /** @type {number} */ (
					/** @type {globalThis.Animation} */ (animation).currentTime
				);
 
				return t1 + delta * easing(time / duration);
			};
 
			if (tick) {
				loop(() => {
					if (animation.playState !== 'running') return false;
 
					var t = get_t();
					tick(t, 1 - t);
 
					return true;
				});
			}
		}
 
		animation = element.animate(keyframes, { duration, fill: 'forwards' });
 
		animation.onfinish = () => {
			get_t = () => t2;
			tick?.(t2, 1 - t2);
			on_finish();
		};
	};
 
	return {
		abort: () => {
			if (animation) {
				animation.cancel();
				// This prevents memory leaks in Chromium
				animation.effect = null;
			}
		},
		deactivate: () => {
			on_finish = noop;
		},
		reset: () => {
			if (t2 === 0) {
				tick?.(1, 0);
			}
		},
		t: () => get_t()
	};
}