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

100% Statements 385/385
98.96% Branches 96/97
100% Functions 5/5
100% Lines 377/377

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 3782x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 1168x 1168x 1168x 1168x 1168x 536x 536x 1168x 665x 665x 9x 17x 4x 4x 17x 9x 665x 665x 701x 72x 68x 68x 701x 27x 3x 3x 27x 27x 27x 27x 27x 27x 27x 27x 2x 2x 27x 27x 629x 26x 26x 17x 17x 17x 1x 1x 1x 1x 17x 17x 26x 9x 9x 602x 424x 1x 1x 1x 1x 1x 423x 424x 9x 9x 423x 424x 2x 2x 423x 423x 423x 424x 291x 291x 291x 291x 291x 291x 295x 295x 295x 41x 295x 291x 291x 291x 19x 19x 19x 19x 291x 291x 424x 132x 132x 576x 152x 152x 152x 152x 152x 152x 10x 152x 9x 9x 152x 152x 37x 151x 115x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 115x 115x 115x 115x 115x 115x 115x 115x 152x 701x 665x 665x 9x 9x 665x 665x 25x 25x 26x 25x 25x 25x 25x 665x 665x 665x 665x 665x 665x 874x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 868x 874x 874x 874x 874x 665x 665x 665x 665x 665x 316x 316x 316x 316x 316x 316x 316x 316x 316x 231x 231x 316x 85x 85x 85x 85x 316x 316x 316x 316x 252x 252x 252x 252x 316x 316x 316x 316x 316x 316x 166x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 166x 59x 59x 59x 59x 59x 59x 316x 86x 86x 316x 665x 665x 221x 221x 665x 665x 665x 501x 665x 97x 97x 665x 665x 665x 541x 665x 665x 26x 26x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 665x 37x 37x 37x 37x 37x 37x 665x 665x 665x 665x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 665x 623x 623x 665x 665x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 665x 664x 664x 664x 665x 665x 665x  
/** @import { BlockStatement, Expression, ExpressionStatement, Identifier, MemberExpression, Property, Statement } from 'estree' */
/** @import { Component, SvelteComponent, SvelteSelf, TemplateNode } from '#compiler' */
/** @import { ComponentContext } from '../../types.js' */
import { dev, is_ignored } from '../../../../../state.js';
import { get_attribute_chunks } from '../../../../../utils/ast.js';
import * as b from '../../../../../utils/builders.js';
import { create_derived } from '../../utils.js';
import { build_bind_this, validate_binding } from '../shared/utils.js';
import { build_attribute_value } from '../shared/element.js';
import { build_event_handler } from './events.js';
import { determine_slot } from '../../../../../utils/slot.js';
 
/**
 * @param {Component | SvelteComponent | SvelteSelf} node
 * @param {string} component_name
 * @param {ComponentContext} context
 * @param {Expression} anchor
 * @returns {Statement}
 */
export function build_component(node, component_name, context, anchor = context.state.node) {
	/** @type {Array<Property[] | Expression>} */
	const props_and_spreads = [];
 
	/** @type {ExpressionStatement[]} */
	const lets = [];
 
	/** @type {Record<string, typeof context.state>} */
	const states = {
		default: {
			...context.state,
			scope: node.metadata.scopes.default,
			transform: { ...context.state.transform }
		}
	};
 
	/** @type {Record<string, TemplateNode[]>} */
	const children = {};
 
	/** @type {Record<string, Expression[]>} */
	const events = {};
 
	/** @type {Property[]} */
	const custom_css_props = [];
 
	/** @type {Identifier | MemberExpression | null} */
	let bind_this = null;
 
	/**
	 * @type {ExpressionStatement[]}
	 */
	const binding_initializers = [];
 
	/**
	 * If this component has a slot property, it is a named slot within another component. In this case
	 * the slot scope applies to the component itself, too, and not just its children.
	 */
	let slot_scope_applies_to_itself = !!determine_slot(node);
 
	/**
	 * Components may have a children prop and also have child nodes. In this case, we assume
	 * that the child component isn't using render tags yet and pass the slot as $$slots.default.
	 * We're not doing it for spread attributes, as this would result in too many false positives.
	 */
	let has_children_prop = false;
 
	/**
	 * @param {Property} prop
	 */
	function push_prop(prop) {
		const current = props_and_spreads.at(-1);
		const current_is_props = Array.isArray(current);
		const props = current_is_props ? current : [];
		props.push(prop);
		if (!current_is_props) {
			props_and_spreads.push(props);
		}
	}
 
	if (slot_scope_applies_to_itself) {
		for (const attribute of node.attributes) {
			if (attribute.type === 'LetDirective') {
				lets.push(/** @type {ExpressionStatement} */ (context.visit(attribute)));
			}
		}
	}
 
	for (const attribute of node.attributes) {
		if (attribute.type === 'LetDirective') {
			if (!slot_scope_applies_to_itself) {
				lets.push(/** @type {ExpressionStatement} */ (context.visit(attribute, states.default)));
			}
		} else if (attribute.type === 'OnDirective') {
			if (!attribute.expression) {
				context.state.analysis.needs_props = true;
			}
 
			let handler = build_event_handler(
				attribute.expression,
				attribute.metadata.expression,
				context
			);
 
			if (attribute.modifiers.includes('once')) {
				handler = b.call('$.once', handler);
			}
 
			(events[attribute.name] ||= []).push(handler);
		} else if (attribute.type === 'SpreadAttribute') {
			const expression = /** @type {Expression} */ (context.visit(attribute));
			if (attribute.metadata.expression.has_state) {
				let value = expression;
 
				if (attribute.metadata.expression.has_call) {
					const id = b.id(context.state.scope.generate('spread_element'));
					context.state.init.push(b.var(id, b.call('$.derived', b.thunk(value))));
					value = b.call('$.get', id);
				}
 
				props_and_spreads.push(b.thunk(value));
			} else {
				props_and_spreads.push(expression);
			}
		} else if (attribute.type === 'Attribute') {
			if (attribute.name.startsWith('--')) {
				custom_css_props.push(
					b.init(attribute.name, build_attribute_value(attribute.value, context).value)
				);
				continue;
			}
 
			if (attribute.name === 'slot') {
				slot_scope_applies_to_itself = true;
			}
 
			if (attribute.name === 'children') {
				has_children_prop = true;
			}
 
			const { value } = build_attribute_value(attribute.value, context);
 
			if (attribute.metadata.expression.has_state) {
				let arg = value;
 
				// When we have a non-simple computation, anything other than an Identifier or Member expression,
				// then there's a good chance it needs to be memoized to avoid over-firing when read within the
				// child component.
				const should_wrap_in_derived = get_attribute_chunks(attribute.value).some((n) => {
					return (
						n.type === 'ExpressionTag' &&
						n.expression.type !== 'Identifier' &&
						n.expression.type !== 'MemberExpression'
					);
				});
 
				if (should_wrap_in_derived) {
					const id = b.id(context.state.scope.generate(attribute.name));
					context.state.init.push(b.var(id, create_derived(context.state, b.thunk(value))));
					arg = b.call('$.get', id);
				}
 
				push_prop(b.get(attribute.name, [b.return(arg)]));
			} else {
				push_prop(b.init(attribute.name, value));
			}
		} else if (attribute.type === 'BindDirective') {
			const expression = /** @type {Expression} */ (context.visit(attribute.expression));
 
			if (
				dev &&
				expression.type === 'MemberExpression' &&
				context.state.analysis.runes &&
				!is_ignored(node, 'binding_property_non_reactive')
			) {
				validate_binding(context.state, attribute, expression);
			}
 
			if (attribute.name === 'this') {
				bind_this = attribute.expression;
			} else {
				if (dev) {
					binding_initializers.push(
						b.stmt(
							b.call(
								b.id('$.add_owner_effect'),
								b.thunk(expression),
								b.id(component_name),
								is_ignored(node, 'ownership_invalid_binding') && b.true
							)
						)
					);
				}
 
				push_prop(b.get(attribute.name, [b.return(expression)]));
 
				const assignment = b.assignment('=', attribute.expression, b.id('$$value'));
				push_prop(
					b.set(attribute.name, [b.stmt(/** @type {Expression} */ (context.visit(assignment)))])
				);
			}
		}
	}
 
	if (slot_scope_applies_to_itself) {
		context.state.init.push(...lets);
	}
 
	if (Object.keys(events).length > 0) {
		const events_expression = b.object(
			Object.keys(events).map((name) =>
				b.init(name, events[name].length > 1 ? b.array(events[name]) : events[name][0])
			)
		);
		push_prop(b.init('$$events', events_expression));
	}
 
	/** @type {Statement[]} */
	const snippet_declarations = [];
 
	// Group children by slot
	for (const child of node.fragment.nodes) {
		if (child.type === 'SnippetBlock') {
			// the SnippetBlock visitor adds a declaration to `init`, but if it's directly
			// inside a component then we want to hoist them into a block so that they
			// can be used as props without creating conflicts
			context.visit(child, {
				...context.state,
				init: snippet_declarations
			});
 
			push_prop(b.prop('init', child.expression, child.expression));
 
			continue;
		}
 
		let slot_name = determine_slot(child) ?? 'default';
 
		(children[slot_name] ||= []).push(child);
	}
 
	// Serialize each slot
	/** @type {Property[]} */
	const serialized_slots = [];
	for (const slot_name of Object.keys(children)) {
		const block = /** @type {BlockStatement} */ (
			context.visit(
				{
					...node.fragment,
					// @ts-expect-error
					nodes: children[slot_name]
				},
				slot_name === 'default'
					? slot_scope_applies_to_itself
						? context.state
						: states.default
					: {
							...context.state,
							scope: node.metadata.scopes[slot_name],
							transform: { ...context.state.transform }
						}
			)
		);
 
		if (block.body.length === 0) continue;
 
		const slot_fn = b.arrow(
			[b.id('$$anchor'), b.id('$$slotProps')],
			b.block([
				...(slot_name === 'default' && !slot_scope_applies_to_itself ? lets : []),
				...block.body
			])
		);
 
		if (slot_name === 'default' && !has_children_prop) {
			if (lets.length === 0 && children.default.every((node) => node.type !== 'SvelteFragment')) {
				// create `children` prop...
				push_prop(
					b.init(
						'children',
						dev ? b.call('$.wrap_snippet', b.id(context.state.analysis.name), slot_fn) : slot_fn
					)
				);
 
				// and `$$slots.default: true` so that `<slot>` on the child works
				serialized_slots.push(b.init(slot_name, b.true));
			} else {
				// create `$$slots.default`...
				serialized_slots.push(b.init(slot_name, slot_fn));
 
				// and a `children` prop that errors
				push_prop(b.init('children', b.id('$.invalid_default_snippet')));
			}
		} else {
			serialized_slots.push(b.init(slot_name, slot_fn));
		}
	}
 
	if (serialized_slots.length > 0) {
		push_prop(b.init('$$slots', b.object(serialized_slots)));
	}
 
	if (
		!context.state.analysis.runes &&
		node.attributes.some((attribute) => attribute.type === 'BindDirective')
	) {
		push_prop(b.init('$$legacy', b.true));
	}
 
	const props_expression =
		props_and_spreads.length === 0 ||
		(props_and_spreads.length === 1 && Array.isArray(props_and_spreads[0]))
			? b.object(/** @type {Property[]} */ (props_and_spreads[0]) || [])
			: b.call(
					'$.spread_props',
					...props_and_spreads.map((p) => (Array.isArray(p) ? b.object(p) : p))
				);
 
	/** @param {Expression} node_id */
	let fn = (node_id) => {
		return b.call(
			// TODO We can remove this ternary once we remove legacy mode, since in runes mode dynamic components
			// will be handled separately through the `$.component` function, and then the component name will
			// always be referenced through just the identifier here.
			node.type === 'SvelteComponent'
				? component_name
				: /** @type {Expression} */ (context.visit(b.member_id(component_name))),
			node_id,
			props_expression
		);
	};
 
	if (bind_this !== null) {
		const prev = fn;
 
		fn = (node_id) => {
			return build_bind_this(bind_this, prev(node_id), context);
		};
	}
 
	const statements = [...snippet_declarations];
 
	if (node.type === 'SvelteComponent') {
		const prev = fn;
 
		fn = (node_id) => {
			return b.call(
				'$.component',
				node_id,
				b.thunk(/** @type {Expression} */ (context.visit(node.expression))),
				b.arrow(
					[b.id('$$anchor'), b.id(component_name)],
					b.block([...binding_initializers, b.stmt(prev(b.id('$$anchor')))])
				)
			);
		};
	} else {
		statements.push(...binding_initializers);
	}
 
	if (Object.keys(custom_css_props).length > 0) {
		context.state.template.push(
			context.state.metadata.namespace === 'svg'
				? '<g><!></g>'
				: '<div style="display: contents"><!></div>'
		);
 
		statements.push(
			b.stmt(b.call('$.css_props', anchor, b.thunk(b.object(custom_css_props)))),
			b.stmt(fn(b.member(anchor, 'lastChild'))),
			b.stmt(b.call('$.reset', anchor))
		);
	} else {
		context.state.template.push('<!>');
		statements.push(b.stmt(fn(anchor)));
	}
 
	return statements.length > 1 ? b.block(statements) : statements[0];
}