All files / src/compiler/phases/3-transform/server/visitors/shared element.js

97.11% Statements 437/450
95.31% Branches 122/128
100% Functions 5/5
97.05% Lines 429/442

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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 4432x 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 2x 2x 2x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 3137x 2070x 1208x 133x 6x 6x 6x 6x 2x 6x           6x 133x 120x 120x 120x 120x 133x 133x 1208x 6x 6x   6x     1075x 1069x 507x 1069x 31x 31x 1069x 1069x 2070x 279x 248x 279x 87x 87x 20x 20x 20x 17x 87x 279x 1x 1x 278x 190x 190x 279x 171x 272x 6x 272x 4x 4x 4x 4x 165x 61x 61x 61x 61x 61x 61x 61x 116x 116x 116x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 40x 40x 40x 61x 21x 21x 21x 61x 61x 61x 61x 61x 61x 61x 61x 157x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 862x 69x 69x 69x 1x 1x 1x 583x 29x       514x 23x 485x 39x 462x 10x 423x 413x 413x 2070x 3137x 3137x 15x 15x 15x 15x 15x 8x 8x 15x 3137x 3137x 25x 25x 25x 25x 25x 25x 5x 5x 25x 3137x 3137x 3137x 3137x 3137x 68x 68x 68x 68x 68x 68x 68x 3137x 3069x 1295x 906x 906x 906x 906x 906x 906x 906x 906x 906x 903x 903x 903x 903x 903x 903x 903x 903x 903x 903x 906x 906x 389x 389x 389x 389x 389x 389x 389x 389x 389x 389x 1295x 1295x 1295x 3069x 3137x 3137x 1x 2x 2x 1x 3137x 3137x 3137x 2x 2x 2x 2x 2x 2x 1353x 1353x 1353x 1247x 1247x 1247x 1247x 1353x 1353x 2x 2x 2x 2x 2x 2x 2x 2x 2x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 8x 3x 3x 3x 3x 3x 3x 8x 8x 8x 6x 6x 8x 8x 8x 68x 68x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 68x 68x 2x 68x     68x 68x 68x 127x 58x 58x 58x 58x 58x 58x 58x 58x 69x 69x 68x 68x 68x 68x 68x 68x 2x 2x 2x 2x 2x 2x 2x 15x 15x 20x 15x 15x 15x 8x 8x 15x 15x 15x 15x 15x 5x 5x 15x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x 2x 2x 25x 25x 34x 34x 34x 34x 34x 1x 1x 34x 25x 25x 25x 25x 25x 25x 5x 5x 5x 25x 25x 25x 25x  
/** @import { Expression, ExpressionStatement, Literal } from 'estree' */
/** @import { Attribute, ClassDirective, Namespace, RegularElement, SpreadAttribute, StyleDirective, SvelteElement, SvelteNode } from '#compiler' */
/** @import { ComponentContext, ComponentServerTransformState } from '../../types.js' */
import {
	get_attribute_chunks,
	is_event_attribute,
	is_text_attribute
} from '../../../../../utils/ast.js';
import { binding_properties } from '../../../../bindings.js';
import {
	ContentEditableBindings,
	LoadErrorElements,
	WhitespaceInsensitiveAttributes
} from '../../../../constants.js';
import { create_attribute, is_custom_element_node } from '../../../../nodes.js';
import { regex_starts_with_newline } from '../../../../patterns.js';
import * as b from '../../../../../utils/builders.js';
import {
	DOMBooleanAttributes,
	ELEMENT_IS_NAMESPACED,
	ELEMENT_PRESERVE_ATTRIBUTE_CASE
} from '../../../../../../constants.js';
import { serialize_attribute_value } from './utils.js';
 
/**
 * Writes the output to the template output. Some elements may have attributes on them that require the
 * their output to be the child content instead. In this case, an object is returned.
 * @param {RegularElement | SvelteElement} node
 * @param {import('zimmerframe').Context<SvelteNode, ComponentServerTransformState>} context
 */
export function serialize_element_attributes(node, context) {
	/** @type {Array<Attribute | SpreadAttribute>} */
	const attributes = [];
 
	/** @type {ClassDirective[]} */
	const class_directives = [];
 
	/** @type {StyleDirective[]} */
	const style_directives = [];
 
	/** @type {ExpressionStatement[]} */
	const lets = [];
 
	/** @type {Expression | null} */
	let content = null;
 
	let has_spread = false;
	// Use the index to keep the attributes order which is important for spreading
	let class_index = -1;
	let style_index = -1;
	let events_to_capture = new Set();
 
	for (const attribute of node.attributes) {
		if (attribute.type === 'Attribute') {
			if (attribute.name === 'value') {
				if (node.name === 'textarea') {
					if (
						attribute.value !== true &&
						Array.isArray(attribute.value) &&
						attribute.value[0].type === 'Text' &&
						regex_starts_with_newline.test(attribute.value[0].data)
					) {
						// Two or more leading newlines are required to restore the leading newline immediately after `<textarea>`.
						// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
						// also see related code in analysis phase
						attribute.value[0].data = '\n' + attribute.value[0].data;
					}
					content = b.call('$.escape', serialize_attribute_value(attribute.value, context));
				} else if (node.name !== 'select') {
					// omit value attribute for select elements, it's irrelevant for the initially selected value and has no
					// effect on the selected value after the user interacts with the select element (the value _property_ does, but not the attribute)
					attributes.push(attribute);
				}
 
				// omit event handlers except for special cases
			} else if (is_event_attribute(attribute)) {
				if (
					(attribute.name === 'onload' || attribute.name === 'onerror') &&
					LoadErrorElements.includes(node.name)
				) {
					events_to_capture.add(attribute.name);
				}
			} else {
				if (attribute.name === 'class') {
					class_index = attributes.length;
				} else if (attribute.name === 'style') {
					style_index = attributes.length;
				}
				attributes.push(attribute);
			}
		} else if (attribute.type === 'BindDirective') {
			if (attribute.name === 'value' && node.name === 'select') continue;
			if (
				attribute.name === 'value' &&
				attributes.some(
					(attr) =>
						attr.type === 'Attribute' &&
						attr.name === 'type' &&
						is_text_attribute(attr) &&
						attr.value[0].data === 'file'
				)
			) {
				continue;
			}
			if (attribute.name === 'this') continue;
 
			const binding = binding_properties[attribute.name];
			if (binding?.omit_in_ssr) continue;
 
			if (ContentEditableBindings.includes(attribute.name)) {
				content = /** @type {Expression} */ (context.visit(attribute.expression));
			} else if (attribute.name === 'value' && node.name === 'textarea') {
				content = b.call(
					'$.escape',
					/** @type {Expression} */ (context.visit(attribute.expression))
				);
			} else if (attribute.name === 'group') {
				const value_attribute = /** @type {Attribute | undefined} */ (
					node.attributes.find((attr) => attr.type === 'Attribute' && attr.name === 'value')
				);
				if (!value_attribute) continue;
 
				const is_checkbox = node.attributes.some(
					(attr) =>
						attr.type === 'Attribute' &&
						attr.name === 'type' &&
						is_text_attribute(attr) &&
						attr.value[0].data === 'checkbox'
				);
				attributes.push(
					create_attribute('checked', -1, -1, [
						{
							type: 'ExpressionTag',
							start: -1,
							end: -1,
							parent: attribute,
							expression: is_checkbox
								? b.call(
										b.member(attribute.expression, b.id('includes')),
										serialize_attribute_value(value_attribute.value, context)
									)
								: b.binary(
										'===',
										attribute.expression,
										serialize_attribute_value(value_attribute.value, context)
									),
							metadata: {
								contains_call_expression: false,
								dynamic: false
							}
						}
					])
				);
			} else {
				attributes.push(
					create_attribute(attribute.name, -1, -1, [
						{
							type: 'ExpressionTag',
							start: -1,
							end: -1,
							parent: attribute,
							expression: attribute.expression,
							metadata: {
								contains_call_expression: false,
								dynamic: false
							}
						}
					])
				);
			}
		} else if (attribute.type === 'SpreadAttribute') {
			attributes.push(attribute);
			has_spread = true;
			if (LoadErrorElements.includes(node.name)) {
				events_to_capture.add('onload');
				events_to_capture.add('onerror');
			}
		} else if (attribute.type === 'UseDirective') {
			if (LoadErrorElements.includes(node.name)) {
				events_to_capture.add('onload');
				events_to_capture.add('onerror');
			}
		} else if (attribute.type === 'ClassDirective') {
			class_directives.push(attribute);
		} else if (attribute.type === 'StyleDirective') {
			style_directives.push(attribute);
		} else if (attribute.type === 'LetDirective') {
			lets.push(/** @type {ExpressionStatement} */ (context.visit(attribute)));
		} else {
			context.visit(attribute);
		}
	}
 
	if (class_directives.length > 0 && !has_spread) {
		const class_attribute = serialize_class_directives(
			class_directives,
			/** @type {Attribute | null} */ (attributes[class_index] ?? null)
		);
		if (class_index === -1) {
			attributes.push(class_attribute);
		}
	}
 
	if (style_directives.length > 0 && !has_spread) {
		serialize_style_directives(
			style_directives,
			/** @type {Attribute | null} */ (attributes[style_index] ?? null),
			context
		);
		if (style_index > -1) {
			attributes.splice(style_index, 1);
		}
	}
 
	// Let bindings first, they can be used on attributes
	context.state.init.push(...lets);
 
	if (has_spread) {
		serialize_element_spread_attributes(
			node,
			attributes,
			style_directives,
			class_directives,
			context
		);
	} else {
		for (const attribute of /** @type {Attribute[]} */ (attributes)) {
			if (attribute.value === true || is_text_attribute(attribute)) {
				const name = get_attribute_name(node, attribute, context);
				const literal_value = /** @type {Literal} */ (
					serialize_attribute_value(
						attribute.value,
						context,
						WhitespaceInsensitiveAttributes.includes(name)
					)
				).value;
				if (name !== 'class' || literal_value) {
					context.state.template.push(
						b.literal(
							` ${attribute.name}${
								DOMBooleanAttributes.includes(name) && literal_value === true
									? ''
									: `="${literal_value === true ? '' : String(literal_value)}"`
							}`
						)
					);
				}
				continue;
			}
 
			const name = get_attribute_name(node, attribute, context);
			const is_boolean = DOMBooleanAttributes.includes(name);
			const value = serialize_attribute_value(
				attribute.value,
				context,
				WhitespaceInsensitiveAttributes.includes(name)
			);
 
			context.state.template.push(
				b.call('$.attr', b.literal(name), value, is_boolean && b.literal(is_boolean))
			);
		}
	}
 
	if (events_to_capture.size !== 0) {
		for (const event of events_to_capture) {
			context.state.template.push(b.literal(` ${event}="this.__e=event"`));
		}
	}
 
	return content;
}
 
/**
 * @param {RegularElement | SvelteElement} element
 * @param {Attribute} attribute
 * @param {{ state: { namespace: Namespace }}} context
 */
function get_attribute_name(element, attribute, context) {
	let name = attribute.name;
	if (!element.metadata.svg && !element.metadata.mathml && context.state.namespace !== 'foreign') {
		name = name.toLowerCase();
		// don't lookup boolean aliases here, the server runtime function does only
		// check for the lowercase variants of boolean attributes
	}
	return name;
}
 
/**
 *
 * @param {RegularElement | SvelteElement} element
 * @param {Array<Attribute | SpreadAttribute>} attributes
 * @param {StyleDirective[]} style_directives
 * @param {ClassDirective[]} class_directives
 * @param {ComponentContext} context
 */
function serialize_element_spread_attributes(
	element,
	attributes,
	style_directives,
	class_directives,
	context
) {
	let classes;
	let styles;
	let flags = 0;
 
	if (class_directives.length > 0 || context.state.analysis.css.hash) {
		const properties = class_directives.map((directive) =>
			b.init(
				directive.name,
				directive.expression.type === 'Identifier' && directive.expression.name === directive.name
					? b.id(directive.name)
					: /** @type {Expression} */ (context.visit(directive.expression))
			)
		);
 
		if (context.state.analysis.css.hash) {
			properties.unshift(b.init(context.state.analysis.css.hash, b.literal(true)));
		}
 
		classes = b.object(properties);
	}
 
	if (style_directives.length > 0) {
		const properties = style_directives.map((directive) =>
			b.init(
				directive.name,
				directive.value === true
					? b.id(directive.name)
					: serialize_attribute_value(directive.value, context, true)
			)
		);
 
		styles = b.object(properties);
	}
 
	if (element.metadata.svg || element.metadata.mathml) {
		flags |= ELEMENT_IS_NAMESPACED | ELEMENT_PRESERVE_ATTRIBUTE_CASE;
	} else if (is_custom_element_node(element)) {
		flags |= ELEMENT_PRESERVE_ATTRIBUTE_CASE;
	}
 
	const object = b.object(
		attributes.map((attribute) => {
			if (attribute.type === 'Attribute') {
				const name = get_attribute_name(element, attribute, context);
				const value = serialize_attribute_value(
					attribute.value,
					context,
					WhitespaceInsensitiveAttributes.includes(name)
				);
				return b.prop('init', b.key(name), value);
			}
 
			return b.spread(/** @type {Expression} */ (context.visit(attribute)));
		})
	);
 
	const args = [object, classes, styles, flags ? b.literal(flags) : undefined];
	context.state.template.push(b.call('$.spread_attributes', ...args));
}
 
/**
 *
 * @param {ClassDirective[]} class_directives
 * @param {Attribute | null} class_attribute
 * @returns
 */
function serialize_class_directives(class_directives, class_attribute) {
	const expressions = class_directives.map((directive) =>
		b.conditional(directive.expression, b.literal(directive.name), b.literal(''))
	);
 
	if (class_attribute === null) {
		class_attribute = create_attribute('class', -1, -1, []);
	}
 
	const chunks = get_attribute_chunks(class_attribute.value);
	const last = chunks.at(-1);
 
	if (last?.type === 'Text') {
		last.data += ' ';
		last.raw += ' ';
	} else if (last) {
		chunks.push({
			type: 'Text',
			start: -1,
			end: -1,
			parent: class_attribute,
			data: ' ',
			raw: ' '
		});
	}
 
	chunks.push({
		type: 'ExpressionTag',
		start: -1,
		end: -1,
		parent: class_attribute,
		expression: b.call(
			b.member(
				b.call(b.member(b.array(expressions), b.id('filter')), b.id('Boolean')),
				b.id('join')
			),
			b.literal(' ')
		),
		metadata: { contains_call_expression: false, dynamic: false }
	});
 
	class_attribute.value = chunks;
	return class_attribute;
}
 
/**
 * @param {StyleDirective[]} style_directives
 * @param {Attribute | null} style_attribute
 * @param {ComponentContext} context
 */
function serialize_style_directives(style_directives, style_attribute, context) {
	const styles = style_directives.map((directive) => {
		let value =
			directive.value === true
				? b.id(directive.name)
				: serialize_attribute_value(directive.value, context, true);
		if (directive.modifiers.includes('important')) {
			value = b.binary('+', value, b.literal(' !important'));
		}
		return b.init(directive.name, value);
	});
 
	const arg =
		style_attribute === null
			? b.object(styles)
			: b.call(
					'$.merge_styles',
					serialize_attribute_value(style_attribute.value, context, true),
					b.object(styles)
				);
 
	context.state.template.push(b.call('$.add_styles', arg));
}