Skip to content

Commit

Permalink
fix(sanity): add fix proposed in #6646
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoerge committed May 16, 2024
1 parent ec179d0 commit cf1ff00
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions packages/sanity/src/core/form/store/utils/immutableReconcile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @param next - the next/current value
*/
export function immutableReconcile<T>(previous: unknown, next: T): T {
return _immutableReconcile(previous, next, new WeakSet())
return _immutableReconcile(previous, next, new WeakMap())
}

function _immutableReconcile<T>(
Expand All @@ -14,12 +14,12 @@ function _immutableReconcile<T>(
/**
* Keep track of visited nodes to prevent infinite recursion in case of circular structures
*/
parents: WeakSet<any>,
parents: WeakMap<any, any>,
): T {
if (previous === next) return previous as T

if (parents.has(next)) {
return next
return parents.get(next)
}

// eslint-disable-next-line no-eq-null
Expand All @@ -32,13 +32,12 @@ function _immutableReconcile<T>(
if (prevType !== nextType) return next

if (Array.isArray(next)) {
parents.add(next)

assertType<unknown[]>(previous)
assertType<unknown[]>(next)

let allEqual = previous.length === next.length
const result = []
const result: unknown[] = []
parents.set(next, result)
for (let index = 0; index < next.length; index++) {
const nextItem = _immutableReconcile(previous[index], next[index], parents)

Expand All @@ -47,26 +46,26 @@ function _immutableReconcile<T>(
}
result[index] = nextItem
}
parents.delete(next)
parents.set(next, allEqual ? previous : result)
return (allEqual ? previous : result) as any
}

if (typeof next === 'object') {
parents.add(next)
assertType<Record<string, unknown>>(previous)
assertType<Record<string, unknown>>(next)

const nextKeys = Object.keys(next)
let allEqual = Object.keys(previous).length === nextKeys.length
const result: Record<string, unknown> = {}
parents.set(next, result)
for (const key of nextKeys) {
const nextValue = _immutableReconcile(previous[key], next[key]!, parents)
if (nextValue !== previous[key]) {
allEqual = false
}
result[key] = nextValue
}
parents.delete(next)
parents.set(next, allEqual ? previous : result)
return (allEqual ? previous : result) as T
}
return next
Expand Down

0 comments on commit cf1ff00

Please sign in to comment.