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

100% Statements 317/317
100% Branches 74/74
100% Functions 10/10
100% Lines 311/311

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 3122x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 383x 383x 475x 475x 37x 37x 475x 475x 475x 475x 102x 102x 102x 16x 16x 102x 102x 102x 102x 102x 102x 102x 102x 90x 90x 475x 373x 373x 475x 475x 475x 475x 475x 475x 105x 328x 80x 105x 475x 8x 8x 475x 475x 92x 92x 475x 475x 84x 84x 475x 475x 475x 475x 475x 414x 414x 414x 414x 9x 9x 414x 414x 475x 475x 475x 62x 62x 62x 62x 62x 62x 475x 475x 475x 37x 475x 438x 438x 438x 438x 438x 438x 438x 438x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 649x 649x 475x 475x 475x 56x 56x 82x 82x 82x 82x 82x 56x 56x 56x 56x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 434x 434x 434x 16x 16x 16x 16x 16x 16x 16x 434x 434x 434x 434x 434x 475x 41x 41x 41x 41x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 5x 5x 92x 92x 1x 1x 92x 92x 92x 92x 92x 3x 3x 92x 92x 92x 41x 475x 475x 475x 475x 475x 475x 475x 102x 102x 102x 102x 102x 102x 475x 475x 1x 1x 1x 1x 475x 475x 2x 2x 2x 2x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 475x 26x 26x 26x 26x 475x 475x 475x 2x 2x 2x 2x 475x 475x 475x 2x 2x 2x 2x 2x 500x 500x 500x 500x 500x 446x 446x 5x 5x 446x 500x 500x 500x 2x 2x 2x 2x 2x 2x 451x 451x 4x 314x 7x 5x 5x 7x 7x 5x 7x 4x 4x 4x  
/** @import { BlockStatement, Expression, Identifier, Pattern, Statement } from 'estree' */
/** @import { Binding, EachBlock } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/** @import { Scope } from '../../../scope' */
import {
	EACH_INDEX_REACTIVE,
	EACH_IS_ANIMATED,
	EACH_IS_CONTROLLED,
	EACH_IS_STRICT_EQUALS,
	EACH_ITEM_REACTIVE,
	EACH_KEYED
} from '../../../../../constants.js';
import { dev } from '../../../../state.js';
import { extract_paths, object } from '../../../../utils/ast.js';
import * as b from '../../../../utils/builders.js';
import { build_getter, with_loc } from '../utils.js';
import { get_value } from './shared/declarations.js';
 
/**
 * @param {EachBlock} node
 * @param {ComponentContext} context
 */
export function EachBlock(node, context) {
	const each_node_meta = node.metadata;
 
	// expression should be evaluated in the parent scope, not the scope
	// created by the each block itself
	const collection = /** @type {Expression} */ (
		context.visit(node.expression, {
			...context.state,
			scope: /** @type {Scope} */ (context.state.scope.parent)
		})
	);
 
	if (!each_node_meta.is_controlled) {
		context.state.template.push('<!>');
	}
 
	if (each_node_meta.array_name !== null) {
		context.state.init.push(b.const(each_node_meta.array_name, b.thunk(collection)));
	}
 
	let flags = 0;
 
	if (node.metadata.keyed) {
		flags |= EACH_KEYED;
 
		if (node.index) {
			flags |= EACH_INDEX_REACTIVE;
		}
 
		// In runes mode, if key === item, we don't need to wrap the item in a source
		const key_is_item =
			/** @type {Expression} */ (node.key).type === 'Identifier' &&
			node.context.type === 'Identifier' &&
			node.context.name === node.key.name;
 
		if (!context.state.analysis.runes || !key_is_item) {
			flags |= EACH_ITEM_REACTIVE;
		}
	} else {
		flags |= EACH_ITEM_REACTIVE;
	}
 
	// Since `animate:` can only appear on elements that are the sole child of a keyed each block,
	// we can determine at compile time whether the each block is animated or not (in which
	// case it should measure animated elements before and after reconciliation).
	if (
		node.key &&
		node.body.nodes.some((child) => {
			if (child.type !== 'RegularElement' && child.type !== 'SvelteElement') return false;
			return child.attributes.some((attr) => attr.type === 'AnimateDirective');
		})
	) {
		flags |= EACH_IS_ANIMATED;
	}
 
	if (each_node_meta.is_controlled) {
		flags |= EACH_IS_CONTROLLED;
	}
 
	if (context.state.analysis.runes) {
		flags |= EACH_IS_STRICT_EQUALS;
	}
 
	// If the array is a store expression, we need to invalidate it when the array is changed.
	// This doesn't catch all cases, but all the ones that Svelte 4 catches, too.
	let store_to_invalidate = '';
	if (node.expression.type === 'Identifier' || node.expression.type === 'MemberExpression') {
		const id = object(node.expression);
		if (id) {
			const binding = context.state.scope.get(id.name);
			if (binding?.kind === 'store_sub') {
				store_to_invalidate = id.name;
			}
		}
	}
 
	// Legacy mode: find the parent each blocks which contain the arrays to invalidate
	const indirect_dependencies = collect_parent_each_blocks(context).flatMap((block) => {
		const array = /** @type {Expression} */ (context.visit(block.expression));
		const transitive_dependencies = build_transitive_dependencies(
			block.metadata.references,
			context
		);
		return [array, ...transitive_dependencies];
	});
 
	if (each_node_meta.array_name) {
		indirect_dependencies.push(b.call(each_node_meta.array_name));
	} else {
		indirect_dependencies.push(collection);
 
		const transitive_dependencies = build_transitive_dependencies(
			each_node_meta.references,
			context
		);
		indirect_dependencies.push(...transitive_dependencies);
	}
 
	const child_state = {
		...context.state,
		transform: { ...context.state.transform }
	};
 
	/** The state used when generating the key function, if necessary */
	const key_state = {
		...context.state,
		transform: { ...context.state.transform }
	};
 
	// We need to generate a unique identifier in case there's a bind:group below
	// which needs a reference to the index
	const index =
		each_node_meta.contains_group_binding || !node.index ? each_node_meta.index : b.id(node.index);
	const item = each_node_meta.item;
	const binding = /** @type {Binding} */ (context.state.scope.get(item.name));
	const getter = (/** @type {Identifier} */ id) => {
		const item_with_loc = with_loc(item, id);
		return b.call('$.unwrap', item_with_loc);
	};
 
	if (node.index) {
		child_state.transform[node.index] = {
			read: (id) => {
				const index_with_loc = with_loc(index, id);
				return (flags & EACH_INDEX_REACTIVE) === 0
					? index_with_loc
					: b.call('$.get', index_with_loc);
			}
		};
 
		delete key_state.transform[node.index];
	}
 
	/** @type {Statement[]} */
	const declarations = [];
 
	const invalidate = b.call(
		'$.invalidate_inner_signals',
		b.thunk(b.sequence(indirect_dependencies))
	);
 
	const invalidate_store = store_to_invalidate
		? b.call('$.invalidate_store', b.id('$$stores'), b.literal(store_to_invalidate))
		: undefined;
 
	/** @type {Expression[]} */
	const sequence = [];
	if (!context.state.analysis.runes) sequence.push(invalidate);
	if (invalidate_store) sequence.push(invalidate_store);
 
	if (node.context.type === 'Identifier') {
		child_state.transform[node.context.name] = {
			read: getter,
			assign: (_, value) => {
				const left = b.member(
					each_node_meta.array_name ? b.call(each_node_meta.array_name) : collection,
					index,
					true
				);
 
				return b.sequence([b.assignment('=', left, value), ...sequence]);
			},
			mutate: (_, mutation) => b.sequence([mutation, ...sequence])
		};
 
		delete key_state.transform[node.context.name];
	} else {
		const unwrapped = getter(binding.node);
		const paths = extract_paths(node.context);
 
		for (const path of paths) {
			const name = /** @type {Identifier} */ (path.node).name;
			const needs_derived = path.has_default_value; // to ensure that default value is only called once
			const fn = b.thunk(
				/** @type {Expression} */ (context.visit(path.expression?.(unwrapped), child_state))
			);
 
			declarations.push(b.let(path.node, needs_derived ? b.call('$.derived_safe_equal', fn) : fn));
 
			const read = needs_derived ? get_value : b.call;
 
			child_state.transform[name] = {
				read,
				assign: (node, value) => {
					const left = /** @type {Pattern} */ (path.update_expression(unwrapped));
					return b.sequence([b.assignment('=', left, value), ...sequence]);
				},
				mutate: (node, mutation) => {
					return b.sequence([mutation, ...sequence]);
				}
			};
 
			// we need to eagerly evaluate the expression in order to hit any
			// 'Cannot access x before initialization' errors
			if (dev) {
				declarations.push(b.stmt(read(b.id(name))));
			}
 
			delete key_state.transform[name];
		}
	}
 
	const block = /** @type {BlockStatement} */ (context.visit(node.body, child_state));
 
	/** @type {Expression} */
	let key_function = b.id('$.index');
 
	if (node.metadata.keyed) {
		const expression = /** @type {Expression} */ (
			context.visit(/** @type {Expression} */ (node.key), key_state)
		);
 
		key_function = b.arrow([node.context, index], expression);
	}
 
	if (node.index && each_node_meta.contains_group_binding) {
		// We needed to create a unique identifier for the index above, but we want to use the
		// original index name in the template, therefore create another binding
		declarations.push(b.let(node.index, index));
	}
 
	if (dev && (flags & EACH_KEYED) !== 0) {
		context.state.init.push(
			b.stmt(b.call('$.validate_each_keys', b.thunk(collection), key_function))
		);
	}
 
	/** @type {Expression[]} */
	const args = [
		context.state.node,
		b.literal(flags),
		each_node_meta.array_name ? each_node_meta.array_name : b.thunk(collection),
		key_function,
		b.arrow([b.id('$$anchor'), item, index], b.block(declarations.concat(block.body)))
	];
 
	if (node.fallback) {
		args.push(
			b.arrow([b.id('$$anchor')], /** @type {BlockStatement} */ (context.visit(node.fallback)))
		);
	}
 
	context.state.init.push(b.stmt(b.call('$.each', ...args)));
}
 
/**
 * @param {ComponentContext} context
 */
function collect_parent_each_blocks(context) {
	return /** @type {EachBlock[]} */ (context.path.filter((node) => node.type === 'EachBlock'));
}
 
/**
 * @param {Binding[]} references
 * @param {ComponentContext} context
 */
function build_transitive_dependencies(references, context) {
	/** @type {Set<Binding>} */
	const dependencies = new Set();
 
	for (const ref of references) {
		const deps = collect_transitive_dependencies(ref);
		for (const dep of deps) {
			dependencies.add(dep);
		}
	}
 
	return [...dependencies].map((dep) => build_getter({ ...dep.node }, context.state));
}
 
/**
 * @param {Binding} binding
 * @param {Set<Binding>} seen
 * @returns {Binding[]}
 */
function collect_transitive_dependencies(binding, seen = new Set()) {
	if (binding.kind !== 'legacy_reactive') return [];
 
	for (const dep of binding.legacy_dependencies) {
		if (!seen.has(dep)) {
			seen.add(dep);
			for (const transitive_dep of collect_transitive_dependencies(dep, seen)) {
				seen.add(transitive_dep);
			}
		}
	}
 
	return [...seen];
}