All files / src/compiler/phases/3-transform/client/visitors/shared utils.js

100% Statements 348/348
95.77% Branches 68/71
100% Functions 10/10
100% Lines 340/340

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 3412x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 843x 843x 843x 843x 843x 843x 843x 843x 843x 843x 843x 2830x 2830x 2830x 1596x 75x 12x 12x 75x 75x 1596x 1596x 1596x 2830x 843x 843x 2830x 2830x 2830x 1234x 2827x 9x 9x 9x 1596x 1587x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1587x 1567x 1567x 1587x 1587x 1587x 1587x 2830x 843x 843x 843x 843x 843x 2x 2x 2x 2x 2x 1243x 1243x 1243x 1243x 1243x 2x 2x 2x 2x 2x 1246x 1246x 1246x 1246x 2x 2x 2x 2x 2x 2x 2x 199x 199x 199x 199x 199x 199x 199x 199x 14x 14x 14x 199x 199x 199x 2x 2x 2x 2x 2x 2x 2x 2x 2x 56x 56x 56x 56x 56x 2x 2x 2x 2x 2x 2x 2x 2x 726x 726x 726x 726x 706x 706x 706x 706x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 706x 706x 706x 706x 134x 134x 127x 134x 706x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 706x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 36x 201x 165x 165x 623x 2x 422x 420x 420x 726x 20x 20x 20x 20x 20x 20x 20x 20x 20x 726x 726x 2x 2x 726x 1x 1x 726x 4x 4x 726x 2x 2x 726x 1x 1x 726x 726x 726x 2x 2x 2x 2x 2x 2x 2x 2x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 141x 141x 141x 141x 131x 131x 141x 130x 140x 922x 21x 21x 21x 21x 21x 922x 141x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 29x 29x 29x 111x 111x 111x 111x 111x 111x 111x 111x 111x 2x 2x 2x 2x 2x 2x 2x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x  
/** @import { Expression, ExpressionStatement, Identifier, MemberExpression, Statement, Super, TemplateElement, TemplateLiteral } from 'estree' */
/** @import { BindDirective, ExpressionMetadata, ExpressionTag, OnDirective, SvelteNode, Text } from '#compiler' */
/** @import { ComponentClientTransformState, ComponentContext } from '../../types' */
import { walk } from 'zimmerframe';
import { object } from '../../../../../utils/ast.js';
import * as b from '../../../../../utils/builders.js';
import { sanitize_template_string } from '../../../../../utils/sanitize_template_string.js';
import { regex_is_valid_identifier } from '../../../../patterns.js';
import { create_derived } from '../../utils.js';
import is_reference from 'is-reference';
import { locator } from '../../../../../state.js';
 
/**
 * @param {Array<Text | ExpressionTag>} values
 * @param {(node: SvelteNode, state: any) => any} visit
 * @param {ComponentClientTransformState} state
 */
export function build_template_literal(values, visit, state) {
	/** @type {Expression[]} */
	const expressions = [];
 
	let quasi = b.quasi('');
	const quasis = [quasi];
 
	let has_call = false;
	let has_state = false;
	let contains_multiple_call_expression = false;
 
	for (let i = 0; i < values.length; i++) {
		const node = values[i];
 
		if (node.type === 'ExpressionTag') {
			if (node.metadata.expression.has_call) {
				if (has_call) {
					contains_multiple_call_expression = true;
				}
				has_call = true;
			}
 
			has_state ||= node.metadata.expression.has_state;
		}
	}
 
	for (let i = 0; i < values.length; i++) {
		const node = values[i];
 
		if (node.type === 'Text') {
			quasi.value.raw += sanitize_template_string(node.data);
		} else if (node.type === 'ExpressionTag' && node.expression.type === 'Literal') {
			if (node.expression.value != null) {
				quasi.value.raw += sanitize_template_string(node.expression.value + '');
			}
		} else {
			if (contains_multiple_call_expression) {
				const id = b.id(state.scope.generate('stringified_text'));
 
				state.init.push(
					b.const(
						id,
						create_derived(
							state,
							b.thunk(/** @type {Expression} */ (visit(node.expression, state)))
						)
					)
				);
				expressions.push(b.call('$.get', id));
			} else {
				expressions.push(b.logical('??', visit(node.expression, state), b.literal('')));
			}
 
			quasi = b.quasi('', i + 1 === values.length);
			quasis.push(quasi);
		}
	}
 
	const value = b.template(quasis, expressions);
 
	return { value, has_state, has_call };
}
 
/**
 * @param {Statement} statement
 */
export function build_update(statement) {
	const body =
		statement.type === 'ExpressionStatement' ? statement.expression : b.block([statement]);
 
	return b.stmt(b.call('$.template_effect', b.thunk(body)));
}
 
/**
 * @param {Statement[]} update
 */
export function build_render_statement(update) {
	return update.length === 1
		? build_update(update[0])
		: b.stmt(b.call('$.template_effect', b.thunk(b.block(update))));
}
 
/**
 * For unfortunate legacy reasons, directive names can look like this `use:a.b-c`
 * This turns that string into a member expression
 * @param {string} name
 */
export function parse_directive_name(name) {
	// this allow for accessing members of an object
	const parts = name.split('.');
	let part = /** @type {string} */ (parts.shift());
 
	/** @type {Identifier | MemberExpression} */
	let expression = b.id(part);
 
	while ((part = /** @type {string} */ (parts.shift()))) {
		const computed = !regex_is_valid_identifier.test(part);
		expression = b.member(expression, computed ? b.literal(part) : b.id(part), computed);
	}
 
	return expression;
}
 
/**
 * @param {ComponentClientTransformState} state
 * @param {string} id
 * @param {Expression | undefined} init
 * @param {Expression} value
 * @param {ExpressionStatement} update
 */
export function build_update_assignment(state, id, init, value, update) {
	state.init.push(b.var(id, init));
	state.update.push(
		b.if(b.binary('!==', b.id(id), b.assignment('=', b.id(id), value)), b.block([update]))
	);
}
 
/**
 * Serializes the event handler function of the `on:` directive
 * @param {Pick<OnDirective, 'name' | 'modifiers' | 'expression'>} node
 * @param {null | ExpressionMetadata} metadata
 * @param {ComponentContext} context
 */
export function build_event_handler(node, metadata, { state, visit }) {
	/** @type {Expression} */
	let handler;
 
	if (node.expression) {
		handler = node.expression;
 
		// Event handlers can be dynamic (source/store/prop/conditional etc)
		const dynamic_handler = () =>
			b.function(
				null,
				[b.rest(b.id('$$args'))],
				b.block([
					b.return(
						b.call(
							b.member(/** @type {Expression} */ (visit(handler)), b.id('apply'), false, true),
							b.this,
							b.id('$$args')
						)
					)
				])
			);
 
		if (
			metadata?.has_call &&
			!(
				(handler.type === 'ArrowFunctionExpression' || handler.type === 'FunctionExpression') &&
				handler.metadata.hoistable
			)
		) {
			// Create a derived dynamic event handler
			const id = b.id(state.scope.generate('event_handler'));
 
			state.init.push(
				b.var(id, b.call('$.derived', b.thunk(/** @type {Expression} */ (visit(handler)))))
			);
 
			handler = b.function(
				null,
				[b.rest(b.id('$$args'))],
				b.block([
					b.return(
						b.call(
							b.member(b.call('$.get', id), b.id('apply'), false, true),
							b.this,
							b.id('$$args')
						)
					)
				])
			);
		} else if (handler.type === 'Identifier' || handler.type === 'MemberExpression') {
			const id = object(handler);
			const binding = id === null ? null : state.scope.get(id.name);
			if (
				binding !== null &&
				(binding.kind === 'state' ||
					binding.kind === 'frozen_state' ||
					binding.declaration_kind === 'import' ||
					binding.kind === 'legacy_reactive' ||
					binding.kind === 'derived' ||
					binding.kind === 'prop' ||
					binding.kind === 'bindable_prop' ||
					binding.kind === 'store_sub')
			) {
				handler = dynamic_handler();
			} else {
				handler = /** @type {Expression} */ (visit(handler));
			}
		} else if (handler.type === 'ConditionalExpression' || handler.type === 'LogicalExpression') {
			handler = dynamic_handler();
		} else {
			handler = /** @type {Expression} */ (visit(handler));
		}
	} else {
		state.analysis.needs_props = true;
 
		// Function + .call to preserve "this" context as much as possible
		handler = b.function(
			null,
			[b.id('$$arg')],
			b.block([b.stmt(b.call('$.bubble_event.call', b.this, b.id('$$props'), b.id('$$arg')))])
		);
	}
 
	if (node.modifiers.includes('stopPropagation')) {
		handler = b.call('$.stopPropagation', handler);
	}
	if (node.modifiers.includes('stopImmediatePropagation')) {
		handler = b.call('$.stopImmediatePropagation', handler);
	}
	if (node.modifiers.includes('preventDefault')) {
		handler = b.call('$.preventDefault', handler);
	}
	if (node.modifiers.includes('self')) {
		handler = b.call('$.self', handler);
	}
	if (node.modifiers.includes('trusted')) {
		handler = b.call('$.trusted', handler);
	}
 
	return handler;
}
 
/**
 * Serializes `bind:this` for components and elements.
 * @param {Identifier | MemberExpression} expression
 * @param {Expression} value
 * @param {import('zimmerframe').Context<SvelteNode, ComponentClientTransformState>} context
 */
export function build_bind_this(expression, value, { state, visit }) {
	/** @type {Identifier[]} */
	const ids = [];
 
	/** @type {Expression[]} */
	const values = [];
 
	/** @type {typeof state.getters} */
	const getters = {};
 
	// Pass in each context variables to the get/set functions, so that we can null out old values on teardown.
	// Note that we only do this for each context variables, the consequence is that the value might be stale in
	// some scenarios where the value is a member expression with changing computed parts or using a combination of multiple
	// variables, but that was the same case in Svelte 4, too. Once legacy mode is gone completely, we can revisit this.
	walk(expression, null, {
		Identifier(node, { path }) {
			if (Object.hasOwn(getters, node.name)) return;
 
			const parent = /** @type {Expression} */ (path.at(-1));
			if (!is_reference(node, parent)) return;
 
			const binding = state.scope.get(node.name);
			if (!binding) return;
 
			for (const [owner, scope] of state.scopes) {
				if (owner.type === 'EachBlock' && scope === binding.scope) {
					ids.push(node);
					values.push(/** @type {Expression} */ (visit(node)));
					getters[node.name] = node;
					break;
				}
			}
		}
	});
 
	const child_state = { ...state, getters: { ...state.getters, ...getters } };
 
	const get = /** @type {Expression} */ (visit(expression, child_state));
	const set = /** @type {Expression} */ (
		visit(b.assignment('=', expression, b.id('$$value')), child_state)
	);
 
	// If we're mutating a property, then it might already be non-existent.
	// If we make all the object nodes optional, then it avoids any runtime exceptions.
	/** @type {Expression | Super} */
	let node = get;
 
	while (node.type === 'MemberExpression') {
		node.optional = true;
		node = node.object;
	}
 
	return b.call(
		'$.bind_this',
		value,
		b.arrow([b.id('$$value'), ...ids], set),
		b.arrow([...ids], get),
		values.length > 0 && b.thunk(b.array(values))
	);
}
 
/**
 * @param {ComponentClientTransformState} state
 * @param {BindDirective} binding
 * @param {MemberExpression} expression
 */
export function build_validate_binding(state, binding, expression) {
	const string = state.analysis.source.slice(binding.start, binding.end);
 
	const get_object = b.thunk(/** @type {Expression} */ (expression.object));
	const get_property = b.thunk(
		/** @type {Expression} */ (
			expression.computed
				? expression.property
				: b.literal(/** @type {Identifier} */ (expression.property).name)
		)
	);
 
	const loc = locator(binding.start);
 
	return b.stmt(
		b.call(
			'$.validate_binding',
			b.literal(string),
			get_object,
			get_property,
			loc && b.literal(loc.line),
			loc && b.literal(loc.column)
		)
	);
}