fix: resolve the fallback of an each block in the enclosing scope (#18803)

In `phases/scope.js`, `EachBlock` visits `node.fallback` with the
block's own scope, so `{:else}` resolves the loop's name to the each
context. With `let item = $state('outer')` outside and `{#each items as
item}…{:else}<button onclick={() => (item = 'changed')}>` the compiler
reports "Cannot reassign or bind to each block argument" for a variable
that is not the block's argument.

The fallback renders when there is nothing to iterate, so it is visited
in the enclosing scope, as an await block's `pending` is.
pull/18800/merge
Nic Polumeyv 1 week ago committed by GitHub
parent 34b13ac3e4
commit 6be176df2f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: resolve the fallback of an each block in the enclosing scope

@ -1233,6 +1233,7 @@ export function create_scopes(ast, root, allow_reactive_declarations, parent) {
EachBlock(node, { state, visit }) {
visit(node.expression);
if (node.fallback) visit(node.fallback);
// context and children are a new scope
const scope = state.scope.child();
@ -1278,7 +1279,6 @@ export function create_scopes(ast, root, allow_reactive_declarations, parent) {
for (const child of node.body.nodes) {
visit(child, { scope });
}
if (node.fallback) visit(node.fallback, { scope });
node.metadata = {
expression: new ExpressionMetadata(),

@ -0,0 +1,14 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: '<button>outer</button>',
test({ assert, target }) {
const button = target.querySelector('button');
flushSync(() => {
button?.click();
});
assert.htmlEqual(target.innerHTML, '<button>changed</button>');
}
});

@ -0,0 +1,10 @@
<script>
let items = $state([]);
let item = $state('outer');
</script>
{#each items as item}
<p>{item}</p>
{:else}
<button onclick={() => (item = 'changed')}>{item}</button>
{/each}
Loading…
Cancel
Save