Skip to content
Open
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
117 changes: 109 additions & 8 deletions __tests__/patch.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use strict"
import {vi} from "vitest"
import {
Immer,
produce,
applyPatches,
produceWithPatches,
Expand All @@ -25,10 +26,11 @@ function createPatchTestData(
producer,
expectedPatches,
expectedInversePatches,
expectedResult
expectedResult,
produceRecipe = produce
) {
let recordedPatches, recordedInversePatches
const res = produce(base, producer, (p, i) => {
const res = produceRecipe(base, producer, (p, i) => {
recordedPatches = p
recordedInversePatches = i
})
Expand All @@ -53,7 +55,8 @@ function runPatchTests(
expectedResult,
options = {}
) {
const {only = false, skip = false} = options
const {only = false, skip = false, immer} = options
const replay = immer ? immer.applyPatches.bind(immer) : applyPatches

// Choose the appropriate describe function
let describeFn = describe
Expand All @@ -66,7 +69,8 @@ function runPatchTests(
producer,
expectedPatches,
expectedInversePatches,
expectedResult
expectedResult,
immer ? immer.produce : produce
)

describeFn(testName, () => {
Expand All @@ -84,14 +88,12 @@ function runPatchTests(
})

test("patches are replayable", () => {
expect(applyPatches(base, testData.patches)).toEqual(testData.result)
expect(replay(base, testData.patches)).toEqual(testData.result)
})

test("patches can be reversed", () => {
if (expectedInversePatches) {
expect(applyPatches(testData.result, testData.inversePatches)).toEqual(
base
)
expect(replay(testData.result, testData.inversePatches)).toEqual(base)
}
})
})
Expand Down Expand Up @@ -1694,3 +1696,102 @@ describe("assigning a base value back over a modified draft", () => {
{map: new Map([["child", {id: 1}]])}
)
})

describe.each([false, true, "class_only"])(
"patch value shallow copy: %s",
strict => {
const immer = new Immer({autoFreeze: false})
immer.setUseStrictShallowCopy(strict)
const key = Symbol("key")
const nestedKey = Symbol("nested")
for (const op of ["add", "replace"]) {
const value = {[key]: {[nestedKey]: {value: 1}}}
const base = op === "add" ? {} : {item: null}
const data = runPatchTests(
`preserves symbols in ${op} values`,
base,
draft => {
draft.item = value
},
[{op, path: ["item"], value}],
op === "add"
? [{op: "remove", path: ["item"]}]
: [{op: "replace", path: ["item"], value: null}],
{item: value},
{immer}
)
it(`deep clones ${op} values`, () => {
const result = immer.applyPatches(base, data.patches)
expect(result.item[key]).not.toBe(value[key])
expect(result.item[key][nestedKey]).not.toBe(value[key][nestedKey])
})
}
runPatchTests(
"restores symbols in inverse values",
{item: {[key]: {value: 1}}},
draft => {
draft.item = null
},
[{op: "replace", path: ["item"], value: null}],
[{op: "replace", path: ["item"], value: {[key]: {value: 1}}}],
{item: null},
{immer}
)
for (const isClass of [false, true]) {
class Value {
[immerable] = true
changed = false
}
const value = isClass ? new Value() : {changed: false}
const hidden = Symbol("hidden")
Object.defineProperty(value, "hidden", {
value: {nested: 1},
enumerable: false
})
Object.defineProperty(value, hidden, {
value: {nested: 2},
enumerable: false
})
// Copy through a recipe so patch generation and replay must agree on the flag.
const expected = immer.produce(value, draft => {
draft.changed = true
})
const data = runPatchTests(
`copies ${isClass ? "class" : "plain"} draft values`,
{source: value},
draft => {
draft.source.changed = true
draft.item = draft.source
delete draft.source
},
[
{op: "add", path: ["item"], value: expected},
{op: "remove", path: ["source"]}
],
undefined,
{item: expected},
{immer}
)
it(`respects non-enumerables for ${isClass ? "classes" : "plain objects"}`, () => {
const result = immer.applyPatches({}, [
{op: "add", path: ["item"], value}
]).item
const keepsHidden =
strict === true || (strict === "class_only" && isClass)
for (const property of ["hidden", hidden]) {
expect(Object.hasOwn(result, property)).toBe(keepsHidden)
expect(Object.hasOwn(data.patches[0].value, property)).toBe(
keepsHidden
)
if (keepsHidden) {
expect(result[property]).toEqual(value[property])
expect(result[property]).not.toBe(value[property])
expect(
Object.getOwnPropertyDescriptor(result, property).enumerable
).toBe(false)
}
}
})
}
}
)
36 changes: 26 additions & 10 deletions src/plugins/patches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {
each,
has,
getArchtype,
getPrototypeOf,
shallowCopy,
StrictMode,
isSet,
isMap,
loadPlugin,
Expand Down Expand Up @@ -359,7 +360,10 @@ export function enablePatches() {
}

const type = getArchtype(base)
const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411
const value = deepClonePatchValue(
patch.value,
(draft as any)[DRAFT_STATE].scope_.immer_.useStrictShallowCopy_
) // used to clone patch to ensure original patch is not modified, see #411
const key = path[path.length - 1]
switch (op) {
case REPLACE:
Expand Down Expand Up @@ -411,24 +415,36 @@ export function enablePatches() {
// optimize: this is quite a performance hit, can we detect intelligently when it is needed?
// E.g. auto-draft when new objects from outside are assigned and modified?
// (See failing test when deepClone just returns obj)
function deepClonePatchValue<T>(obj: T): T
function deepClonePatchValue(obj: any) {
function deepClonePatchValue<T>(obj: T, strict: StrictMode): T
function deepClonePatchValue(obj: any, strict: StrictMode) {
if (!isDraftable(obj)) return obj
if (isArray(obj)) return obj.map(deepClonePatchValue)
if (isArray(obj))
return obj.map(value => deepClonePatchValue(value, strict))
if (isMap(obj))
return new Map(
Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
Array.from(obj.entries()).map(([k, v]) => [
k,
deepClonePatchValue(v, strict)
])
)
if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))
const cloned = Object.create(getPrototypeOf(obj))
for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])
if (isSet(obj))
return new Set(
Array.from(obj).map(value => deepClonePatchValue(value, strict))
)
const cloned = shallowCopy(obj, strict)
for (const key of Reflect.ownKeys(cloned)) {
cloned[key] = deepClonePatchValue(cloned[key], strict)
}
if (has(obj, immerable)) cloned[immerable] = obj[immerable]
return cloned
}

function clonePatchValueIfNeeded<T>(obj: T): T {
if (isDraft(obj)) {
return deepClonePatchValue(obj)
return deepClonePatchValue(
obj,
(obj as any)[DRAFT_STATE].scope_.immer_.useStrictShallowCopy_
)
} else return obj
}

Expand Down