From 1b70ad509d192de20c50dd8f132d0a5a121413a9 Mon Sep 17 00:00:00 2001 From: Michel Weststrate Date: Tue, 20 Oct 2020 20:45:20 +0100 Subject: [PATCH] fix: undraftable values should not be cloned for patches, fixes #676 --- __tests__/patch.js | 28 ++++++++++++++++++++++++++++ src/plugins/patches.ts | 5 +++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/__tests__/patch.js b/__tests__/patch.js index 8345ab06..7baba6e5 100644 --- a/__tests__/patch.js +++ b/__tests__/patch.js @@ -1119,3 +1119,31 @@ describe("#588", () => { [{op: "add", path: ["num"], value: 42}] ) }) + +test("#676 patching Date objects", () => { + class Test { + constructor() { + this.test = true + } + perform() { + return "tested!" + } + } + + const [nextState, patches] = produceWithPatches({}, function(draft) { + draft.date = new Date(2020, 10, 10, 8, 8, 8, 3) + draft.test = new Test() + }) + + expect(nextState.date.toJSON()).toMatchInlineSnapshot( + `"2020-11-10T08:08:08.003Z"` + ) + expect(nextState.test.perform()).toBe("tested!") + + const rebuilt = applyPatches({}, patches) + expect(rebuilt.date).toBeInstanceOf(Date) + expect(rebuilt.date.toJSON()).toMatchInlineSnapshot( + `"2020-11-10T08:08:08.003Z"` + ) + expect(rebuilt.date).toEqual(new Date(2020, 10, 10, 8, 8, 8, 3)) +}) diff --git a/src/plugins/patches.ts b/src/plugins/patches.ts index 6470c9d5..998627f2 100644 --- a/src/plugins/patches.ts +++ b/src/plugins/patches.ts @@ -25,7 +25,8 @@ import { ArchtypeSet, ArchtypeArray, die, - isDraft + isDraft, + isDraftable } from "../internal" export function enablePatches() { @@ -267,7 +268,7 @@ export function enablePatches() { // (See failing test when deepClone just returns obj) function deepClonePatchValue(obj: T): T function deepClonePatchValue(obj: any) { - if (!obj || typeof obj !== "object") return obj + if (!isDraftable(obj)) return obj if (Array.isArray(obj)) return obj.map(deepClonePatchValue) if (isMap(obj)) return new Map(