Skip to content

Commit

Permalink
fix: ensure $state.snapshot clones holey arrays correctly (#14657)
Browse files Browse the repository at this point in the history
* fix: ensure $state.snapshot clones holey arrays correctly

* fix: ensure $state.snapshot clones holey arrays correctly

* fix: ensure $state.snapshot clones holey arrays correctly

* fix: ensure $state.snapshot clones holey arrays correctly
  • Loading branch information
trueadm authored Dec 10, 2024
1 parent ab1f7f4 commit fb879dd
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/clean-bobcats-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: ensure $state.snapshot clones holey arrays correctly
13 changes: 8 additions & 5 deletions packages/svelte/src/internal/shared/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,30 +54,33 @@ export function snapshot(value, skip_warning = false) {
*/
function clone(value, cloned, path, paths, original = null) {
if (typeof value === 'object' && value !== null) {
const unwrapped = cloned.get(value);
var unwrapped = cloned.get(value);
if (unwrapped !== undefined) return unwrapped;

if (value instanceof Map) return /** @type {Snapshot<T>} */ (new Map(value));
if (value instanceof Set) return /** @type {Snapshot<T>} */ (new Set(value));

if (is_array(value)) {
const copy = /** @type {Snapshot<any>} */ ([]);
var copy = /** @type {Snapshot<any>} */ (Array(value.length));
cloned.set(value, copy);

if (original !== null) {
cloned.set(original, copy);
}

for (let i = 0; i < value.length; i += 1) {
copy.push(clone(value[i], cloned, DEV ? `${path}[${i}]` : path, paths));
for (var i = 0; i < value.length; i += 1) {
var element = value[i];
if (i in value) {
copy[i] = clone(element, cloned, DEV ? `${path}[${i}]` : path, paths);
}
}

return copy;
}

if (get_prototype_of(value) === object_prototype) {
/** @type {Snapshot<any>} */
const copy = {};
copy = {};
cloned.set(value, copy);

if (original !== null) {
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>false</div><div>true</div>`
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<script>
let arr = []
arr[5] = true
let state = $state([])
state[5] = true
</script>

<div>{2 in $state.snapshot(state)}</div>
<div>{5 in $state.snapshot(state)}</div>

0 comments on commit fb879dd

Please sign in to comment.