Skip to content

Commit

Permalink
fix: ensure each key validation occurs for updates (#12836)
Browse files Browse the repository at this point in the history
* fix: ensure each key validation occurs for updates

* fix: ensure each key validation occurs for updates
  • Loading branch information
trueadm authored Aug 14, 2024
1 parent 555e90f commit 873a184
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 21 deletions.
5 changes: 5 additions & 0 deletions .changeset/tame-dodos-float.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: ensure each key validation occurs for updates
44 changes: 23 additions & 21 deletions packages/svelte/src/internal/client/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,28 +45,30 @@ export function validate_dynamic_component(component_fn) {
* @returns {void}
*/
export function validate_each_keys(collection, key_fn) {
const keys = new Map();
const maybe_array = untrack(() => collection());
const array = is_array(maybe_array)
? maybe_array
: maybe_array == null
? []
: Array.from(maybe_array);
const length = array.length;
for (let i = 0; i < length; i++) {
const key = key_fn(array[i], i);
if (keys.has(key)) {
const a = String(keys.get(key));
const b = String(i);

/** @type {string | null} */
let k = String(array[i]);
if (k.startsWith('[object ')) k = null;

e.each_key_duplicate(a, b, k);
render_effect(() => {
const keys = new Map();
const maybe_array = collection();
const array = is_array(maybe_array)
? maybe_array
: maybe_array == null
? []
: Array.from(maybe_array);
const length = array.length;
for (let i = 0; i < length; i++) {
const key = key_fn(array[i], i);
if (keys.has(key)) {
const a = String(keys.get(key));
const b = String(i);

/** @type {string | null} */
let k = String(array[i]);
if (k.startsWith('[object ')) k = null;

e.each_key_duplicate(a, b, k);
}
keys.set(key, i);
}
keys.set(key, i);
}
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
compileOptions: {
dev: true
},

test({ assert, target }) {
let button = target.querySelector('button');

button?.click();

assert.throws(flushSync, /each_key_duplicate/);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<script>
let data = [
[0, 0],
[0, 4],
[1, 4],
];
function add() {
const n = [0, 0]
data.push(n);
data = data;
}
</script>

<button onclick={add}>add</button>

<ul>
{#each data as d (d.join(""))}
<li> {d}</li>
{/each}
</ul>

0 comments on commit 873a184

Please sign in to comment.