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

99.45% Statements 363/365
95.34% Branches 82/86
82.6% Functions 19/23
99.43% Lines 353/355

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 3562x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 735x 735x 735x 735x 735x 2x 2x 2x 2x 2x 2x 735x 735x 735x 2x 2x 2x 2x 2x 1416x 1416x 1416x 600x 600x 600x 600x 600x 600x 600x 600x 2x 2x 2x 2x 2x 602x 602x 602x 602x 602x 1516x 1516x 1416x 1416x 1416x 1416x 602x 602x 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 82x 104x 104x 82x 82x 82x 82x 82x 82x 82x 82x 58x 82x 24x 24x 24x 24x 24x 24x 24x 82x 104x 104x 104x 104x 104x 104x 104x 104x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 453x 453x 453x 453x 453x 465x 465x 465x 465x 465x 267x 267x 267x 243x 243x 146x 146x 243x 267x 24x 24x 24x 465x 465x 248x 210x 210x 210x 210x 136x 136x 136x 210x 210x 210x 210x 210x 248x 38x 38x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 231x 231x 231x 201x 201x 201x 201x 231x 465x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 495x 495x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 477x 495x 495x 495x 14x 14x 14x 14x 14x 14x 14x 14x 463x 463x 463x 463x 495x 495x 495x 495x 495x 495x 495x 495x 495x 495x 495x 495x 495x 48x 48x 48x 48x 48x 602x 602x 602x 602x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 20x 48x 48x 34x 34x 34x 34x 34x 34x 34x     48x 495x 415x 415x 211x 211x 415x 415x 860x 318x 318x 318x 318x 542x 860x 530x 530x 530x 542x 542x 415x 415x 463x 463x 463x 197x 197x 463x 463x 56x 463x 463x 24x 24x 24x 463x 463x 56x 56x 56x 463x 463x  
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 { EFFECT_RAN } from '../../constants.js';
 
/**
 * @template T
 * @param {string} type
 * @param {T} [detail]
 * @param {any}params_0
 * @returns {Event}
 */
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
	const e = document.createEvent('CustomEvent');
	e.initCustomEvent(type, bubbles, cancelable, detail);
	return e;
}
 
/**
 * @param {Element} dom
 * @param {'introstart' | 'introend' | 'outrostart' | 'outroend'} type
 * @returns {void}
 */
function dispatch_event(dom, type) {
	dom.dispatchEvent(custom_event(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;
 
	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;
				});
			}
		}
	};
 
	// 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 (block) effect's
	// parent (branch) effect is where the state change happened. we can determine that by
	// looking at whether the branch effect is currently initializing
	if (is_intro && should_intro) {
		var parent = /** @type {import('#client').Effect} */ (e.parent);
 
		if (is_global || (parent.f & EFFECT_RAN) !== 0) {
			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 = duration / (1000 / 60);
 
		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?.();
			})
			.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));
		}
	};
}