Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wise-dancers-hang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: improve each block index handling
Original file line number Diff line number Diff line change
Expand Up @@ -2236,6 +2236,12 @@ export const template_visitors = {
const item = b.id(each_node_meta.item_name);
const binding = /** @type {import('#compiler').Binding} */ (context.state.scope.get(item.name));
binding.expression = each_item_is_reactive ? b.call('$.unwrap', item) : item;
if (node.index) {
const index_binding = /** @type {import('#compiler').Binding} */ (
context.state.scope.get(node.index)
);
index_binding.expression = each_item_is_reactive ? b.call('$.unwrap', index) : index;
}

/** @type {import('estree').Statement[]} */
const declarations = [];
Expand Down Expand Up @@ -2291,7 +2297,7 @@ export const template_visitors = {
const key_function =
node.key && ((each_type & EACH_ITEM_REACTIVE) !== 0 || context.state.options.dev)
? b.arrow(
[node.context.type === 'Identifier' ? node.context : b.id('$$item')],
[node.context.type === 'Identifier' ? node.context : b.id('$$item'), index],
b.block(
declarations.concat(
b.return(/** @type {import('estree').Expression} */ (context.visit(node.key)))
Expand Down
7 changes: 4 additions & 3 deletions packages/svelte/src/internal/client/validate.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { untrack } from './runtime.js';
import { EACH_INDEX_REACTIVE } from '../../constants.js';
import { source, untrack } from './runtime.js';
import { is_array } from './utils.js';

/** regex of all html void element names */
Expand Down Expand Up @@ -65,7 +66,7 @@ export function validate_dynamic_element_tag(tag_fn) {

/**
* @param {() => any} collection
* @param {(item: any) => string} key_fn
* @param {(item: any, index: number) => string} key_fn
* @returns {void}
*/
export function validate_each_keys(collection, key_fn) {
Expand All @@ -78,7 +79,7 @@ export function validate_each_keys(collection, key_fn) {
: Array.from(maybe_array);
const length = array.length;
for (let i = 0; i < length; i++) {
const key = key_fn(array[i]);
const key = key_fn(array[i], i);
if (keys.has(key)) {
throw new Error(
`Cannot have duplicate keys in a keyed each: Keys at index ${keys.get(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { test } from '../../test';

export default test({
html: `<div>0</div><div>1</div>`
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{#each {length: 2} as item, i (`${i}`)}
<div>{i}</div>
{/each}