fix: ensure proxied arrays correctly update their length upon deletions (#13549)

* fix: ensure proxied arrays correctly update their length upon deletions

* add test
pull/13545/head
Dominic Gannaway 2 months ago committed by GitHub
parent 4dcac41c10
commit a2ece29b6e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: ensure proxied arrays correctly update their length upon deletions

@ -104,6 +104,16 @@ export function proxy(value, parent = null, prev) {
sources.set(prop, source(UNINITIALIZED));
}
} else {
// When working with arrays, we need to also ensure we update the length when removing
// an indexed property
if (is_proxied_array && typeof prop === 'string') {
var ls = /** @type {Source<number>} */ (sources.get('length'));
var n = Number(prop);
if (Number.isInteger(n) && n < ls.v) {
set(ls, n);
}
}
set(s, UNINITIALIZED);
update_version(version);
}

@ -0,0 +1,29 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
compileOptions: {
dev: true
},
async test({ target, assert, logs }) {
const button = target.querySelector('button');
flushSync(() => {
button?.click();
});
assert.deepEqual(logs, [
'init',
[1, 2, 3, 7],
'update',
[2, 2, 3, 7],
'update',
[2, 3, 3, 7],
'update',
[2, 3, 7, 7],
'update',
[2, 3, 7]
]);
}
});

@ -0,0 +1,33 @@
<script>
function createState(init) {
let values = $state(init);
return {
get value() {
return $state.snapshot(values);
},
get workedValues() {
let newValue = [];
for (const value of values) {
if (value === undefined) {
throw new Error('undefined found');
}
newValue.push(value);
}
return newValue;
},
doSplice() {
values.splice(0, 1);
}
};
}
const myState = createState([1, 2, 3, 7]);
$inspect(myState.workedValues);
</script>
<button onclick={() => myState.doSplice()}>Delete</button>
Loading…
Cancel
Save