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

96.78% Statements 391/404
94.56% Branches 87/92
79.16% Functions 19/24
96.7% Lines 381/394

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 3952x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 739x 739x 739x 2x 2x 2x 2x 2x 1484x 1484x 1484x 624x 624x 624x 624x 624x 624x 624x 624x 2x 2x 2x 2x 2x 638x 638x 638x 638x 638x 1588x 1588x 1484x 1484x 1484x 1484x 638x 638x 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 104x 104x 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 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 457x 457x 457x 457x 457x 467x 467x 467x 467x 467x 269x 269x 269x 245x 245x 146x 146x 245x 269x 24x 24x 24x 467x 467x 250x 212x 212x 212x 212x 136x 136x 136x 212x 212x 212x 212x 212x 250x 38x 38x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 467x 233x 233x 233x 170x 170x 170x 170x 2x 4x 4x 2x 170x 170x 170x 233x 233x 203x 203x 203x 203x 233x 467x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 499x 499x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 481x 499x 499x 499x 14x 14x 14x 14x 14x 14x 14x 14x 467x 467x 467x 467x 499x 499x 499x 499x 499x 499x 499x 499x 499x 499x 499x 499x 499x 52x 52x 52x 52x 52x 638x 638x 638x 638x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 20x 20x 20x 10x 10x 52x 52x 48x 48x 48x 48x 48x 48x 48x     52x 499x 415x 415x 211x 211x 415x 415x 860x 318x 318x 318x 318x 542x 860x 530x 530x 530x 542x 542x 415x 415x 467x 467x 467x 201x 201x 467x 467x 58x 467x 467x 24x 24x 24x 467x 467x 58x 58x 58x 467x 467x  
import { noop } 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 { is_function } from '../../utils.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';
 
/**
 * @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 {() => import('#client').AnimateFn<P | undefined>} get_fn
 * @param {(() => P) | null} get_params
 */
export function animation(element, get_fn, get_params) {
	var item = /** @type {import('#client').EachItem} */ (current_each_item);
 
	/** @type {DOMRect} */
	var from;
 
	/** @type {DOMRect} */
	var to;
 
	/** @type {import('#client').Animation | undefined} */
	var animation;
 
	/** @type {null | { position: string, width: string, height: 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() {
			var computed_style = getComputedStyle(element);
 
			if (computed_style.position !== 'absolute' && computed_style.position !== 'fixed') {
				var style = /** @type {HTMLElement | SVGElement} */ (element).style;
 
				original_styles = {
					position: style.position,
					width: style.width,
					height: style.height
				};
 
				style.position = 'absolute';
				style.width = computed_style.width;
				style.height = computed_style.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;
			}
		}
	};
 
	// 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 {() => import('#client').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_global = (flags & TRANSITION_GLOBAL) !== 0;
 
	/** @type {'in' | 'out' | 'both'} */
	var direction = is_intro && is_outro ? 'both' : is_intro ? 'in' : 'out';
 
	/** @type {import('#client').AnimationConfig | ((opts: { direction: 'in' | 'out' }) => import('#client').AnimationConfig) | undefined} */
	var current_options;
 
	var inert = element.inert;
 
	/** @type {import('#client').Animation | undefined} */
	var intro;
 
	/** @type {import('#client').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 {import('#client').TransitionManager} */
	var transition = {
		is_global,
		in() {
			element.inert = inert;
 
			if (is_intro) {
				dispatch_event(element, 'introstart');
				intro = animate(element, get_options(), outro, 1, () => {
					dispatch_event(element, 'introend');
					intro = current_options = undefined;
				});
			} else {
				outro?.abort();
				reset?.();
			}
		},
		out(fn) {
			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?.();
				});
 
				// 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 {import('#client').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 {import('#client').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 {import('#client').AnimationConfig | ((opts: { direction: 'in' | 'out' }) => import('#client').AnimationConfig)} options
 * @param {import('#client').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} callback
 * @returns {import('#client').Animation}
 */
function animate(element, options, counterpart, t2, callback) {
	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 {import('#client').Animation} */
		var a;
 
		effect(() => {
			var o = untrack(() => options({ direction: t2 === 1 ? 'in' : 'out' }));
			a = animate(element, o, counterpart, t2, callback);
		});
 
		// ...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) {
		callback?.();
		return {
			abort: noop,
			deactivate: noop,
			reset: noop,
			t: () => t2
		};
	}
 
	var { delay = 0, duration, css, tick, easing = linear } = options;
 
	var start = raf.now() + delay;
	var t1 = counterpart?.t(start) ?? 1 - t2;
	var delta = t2 - t1;
 
	duration *= Math.abs(delta);
	var end = start + duration;
 
	/** @type {Animation} */
	var animation;
 
	/** @type {import('#client').Task} */
	var task;
 
	if (css) {
		// WAAPI
		var keyframes = [];
		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));
		}
 
		animation = element.animate(keyframes, {
			delay,
			duration,
			easing: 'linear',
			fill: 'forwards'
		});
 
		animation.finished
			.then(() => {
				callback?.();
 
				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);
				callback?.();
				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();
		},
		deactivate: () => {
			callback = 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));
		}
	};
}