Skip to content
Myr

run prettier with master config before merging

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent 85656cb · Browse files · 19 files+4120 added−4169 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

19 files+4120 added−4169 removed

  • tests:+2870 added−2909 removed
  • other:+1250 added−1260 removed

19 files+4120 added−4169 removed

modified:__tests__/base.js+1510 added-1529 removed
6 unmodified lines
78jest.setTimeout(1000)910test("immer should have no dependencies", () => {11 expect(require("../package.json").dependencies).toBeUndefined()11 expect(require("../package.json").dependencies).toBeUndefined()12})1314runBaseTest("proxy (no freeze)", true, false)15runBaseTest("proxy (autofreeze)", true, true)
2 unmodified lines
18runBaseTest("es5 (autofreeze)", false, true)19runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)2021function runBaseTest(name, useProxies, autoFreeze, useListener) {22 const listener = useListener ? function() {} : undefined23 const {produce} = createPatchedImmer({24 useProxies,25 autoFreeze26 })22 const listener = useListener ? function() {} : undefined23 const {produce} = createPatchedImmer({24 useProxies,25 autoFreeze26 })2728 // When `useListener` is true, append a function to the arguments of every29 // uncurried `produce` call in every test. This makes tests easier to read.30 function createPatchedImmer(options) {31 const immer = new Immer(options)28 // When `useListener` is true, append a function to the arguments of every29 // uncurried `produce` call in every test. This makes tests easier to read.30 function createPatchedImmer(options) {31 const immer = new Immer(options)3233 const {produce} = immer34 immer.produce = (...args) =>35 typeof args[1] === "function" && args.length < 336 ? produce(...args, listener)37 : produce(...args)33 const {produce} = immer34 immer.produce = (...args) =>35 typeof args[1] === "function" && args.length < 336 ? produce(...args, listener)37 : produce(...args)3839 return immer40 }39 return immer40 }4142 describe(`base functionality - ${name}`, () => {43 let baseState44 let origBaseState42 describe(`base functionality - ${name}`, () => {43 let baseState44 let origBaseState4546 beforeEach(() => {47 origBaseState = baseState = createBaseState()48 })46 beforeEach(() => {47 origBaseState = baseState = createBaseState()48 })4950 it("returns the original state when no changes are made", () => {51 const nextState = produce(baseState, s => {52 expect(s.aProp).toBe("hi")53 expect(s.anObject.nested).toMatchObject({yummie: true})54 })55 expect(nextState).toBe(baseState)56 })50 it("returns the original state when no changes are made", () => {51 const nextState = produce(baseState, s => {52 expect(s.aProp).toBe("hi")53 expect(s.anObject.nested).toMatchObject({yummie: true})54 })55 expect(nextState).toBe(baseState)56 })5758 it("does structural sharing", () => {59 const random = Math.random()60 const nextState = produce(baseState, s => {61 s.aProp = random62 })63 expect(nextState).not.toBe(baseState)64 expect(nextState.aProp).toBe(random)65 expect(nextState.nested).toBe(baseState.nested)66 })58 it("does structural sharing", () => {59 const random = Math.random()60 const nextState = produce(baseState, s => {61 s.aProp = random62 })63 expect(nextState).not.toBe(baseState)64 expect(nextState.aProp).toBe(random)65 expect(nextState.nested).toBe(baseState.nested)66 })6768 it("deep change bubbles up", () => {69 const nextState = produce(baseState, s => {70 s.anObject.nested.yummie = false71 })72 expect(nextState).not.toBe(baseState)73 expect(nextState.anObject).not.toBe(baseState.anObject)74 expect(baseState.anObject.nested.yummie).toBe(true)75 expect(nextState.anObject.nested.yummie).toBe(false)76 expect(nextState.anArray).toBe(baseState.anArray)77 })68 it("deep change bubbles up", () => {69 const nextState = produce(baseState, s => {70 s.anObject.nested.yummie = false71 })72 expect(nextState).not.toBe(baseState)73 expect(nextState.anObject).not.toBe(baseState.anObject)74 expect(baseState.anObject.nested.yummie).toBe(true)75 expect(nextState.anObject.nested.yummie).toBe(false)76 expect(nextState.anArray).toBe(baseState.anArray)77 })7879 it("can add props", () => {80 const nextState = produce(baseState, s => {81 s.anObject.cookie = {tasty: true}82 })83 expect(nextState).not.toBe(baseState)84 expect(nextState.anObject).not.toBe(baseState.anObject)85 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)86 expect(nextState.anObject.cookie).toEqual({tasty: true})87 })79 it("can add props", () => {80 const nextState = produce(baseState, s => {81 s.anObject.cookie = {tasty: true}82 })83 expect(nextState).not.toBe(baseState)84 expect(nextState.anObject).not.toBe(baseState.anObject)85 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)86 expect(nextState.anObject.cookie).toEqual({tasty: true})87 })8889 it("can delete props", () => {90 const nextState = produce(baseState, s => {91 delete s.anObject.nested92 })93 expect(nextState).not.toBe(baseState)94 expect(nextState.anObject).not.toBe(baseState.anObject)95 expect(nextState.anObject.nested).toBe(undefined)96 })89 it("can delete props", () => {90 const nextState = produce(baseState, s => {91 delete s.anObject.nested92 })93 expect(nextState).not.toBe(baseState)94 expect(nextState.anObject).not.toBe(baseState.anObject)95 expect(nextState.anObject.nested).toBe(undefined)96 })9798 // Found by: https://github.com/mweststrate/immer/pull/26799 it("can delete props added in the producer", () => {100 const nextState = produce(baseState, s => {101 s.anObject.test = true102 delete s.anObject.test103 })104 if (useProxies) {105 expect(nextState).not.toBe(baseState)106 expect(nextState).toEqual(baseState)107 } else {108 // The copy is avoided in ES5.109 expect(nextState).toBe(baseState)110 }111 })98 // Found by: https://github.com/mweststrate/immer/pull/26799 it("can delete props added in the producer", () => {100 const nextState = produce(baseState, s => {101 s.anObject.test = true102 delete s.anObject.test103 })104 if (useProxies) {105 expect(nextState).not.toBe(baseState)106 expect(nextState).toEqual(baseState)107 } else {108 // The copy is avoided in ES5.109 expect(nextState).toBe(baseState)110 }111 })112113 // Found by: https://github.com/mweststrate/immer/issues/328114 it("can set a property that was just deleted", () => {115 const baseState = {a: 1}116 const nextState = produce(baseState, s => {117 delete s.a118 s.a = 2119 })120 expect(nextState.a).toBe(2)121 })113 // Found by: https://github.com/mweststrate/immer/issues/328114 it("can set a property that was just deleted", () => {115 const baseState = {a: 1}116 const nextState = produce(baseState, s => {117 delete s.a118 s.a = 2119 })120 expect(nextState.a).toBe(2)121 })122123 it("can set a property to its original value after deleting it", () => {124 const baseState = {a: {b: 1}}125 const nextState = produce(baseState, s => {126 const a = s.a127 delete s.a128 s.a = a129 })130 if (useProxies) {131 expect(nextState).not.toBe(baseState)132 expect(nextState).toEqual(baseState)133 } else {134 // The copy is avoided in ES5.135 expect(nextState).toBe(baseState)136 }137 })123 it("can set a property to its original value after deleting it", () => {124 const baseState = {a: {b: 1}}125 const nextState = produce(baseState, s => {126 const a = s.a127 delete s.a128 s.a = a129 })130 if (useProxies) {131 expect(nextState).not.toBe(baseState)132 expect(nextState).toEqual(baseState)133 } else {134 // The copy is avoided in ES5.135 expect(nextState).toBe(baseState)136 }137 })138139 it("can get property descriptors", () => {140 const getDescriptor = Object.getOwnPropertyDescriptor141 const baseState = deepFreeze([{a: 1}])142 produce(baseState, arr => {143 const obj = arr[0]144 const desc = {145 configurable: true,146 enumerable: true,147 ...(useProxies && {writable: true})148 }139 it("can get property descriptors", () => {140 const getDescriptor = Object.getOwnPropertyDescriptor141 const baseState = deepFreeze([{a: 1}])142 produce(baseState, arr => {143 const obj = arr[0]144 const desc = {145 configurable: true,146 enumerable: true,147 ...(useProxies && {writable: true})148 }149150 // Known property151 expect(getDescriptor(obj, "a")).toMatchObject(desc)152 expect(getDescriptor(arr, 0)).toMatchObject(desc)150 // Known property151 expect(getDescriptor(obj, "a")).toMatchObject(desc)152 expect(getDescriptor(arr, 0)).toMatchObject(desc)153154 // Deleted property155 delete obj.a156 arr.pop()157 expect(getDescriptor(obj, "a")).toBeUndefined()158 expect(getDescriptor(arr, 0)).toBeUndefined()154 // Deleted property155 delete obj.a156 arr.pop()157 expect(getDescriptor(obj, "a")).toBeUndefined()158 expect(getDescriptor(arr, 0)).toBeUndefined()159160 // Unknown property161 expect(getDescriptor(obj, "b")).toBeUndefined()162 expect(getDescriptor(arr, 100)).toBeUndefined()160 // Unknown property161 expect(getDescriptor(obj, "b")).toBeUndefined()162 expect(getDescriptor(arr, 100)).toBeUndefined()163164 // Added property165 obj.b = 2166 arr[100] = 1167 expect(getDescriptor(obj, "b")).toBeDefined()168 expect(getDescriptor(arr, 100)).toBeDefined()169 })170 })164 // Added property165 obj.b = 2166 arr[100] = 1167 expect(getDescriptor(obj, "b")).toBeDefined()168 expect(getDescriptor(arr, 100)).toBeDefined()169 })170 })171172 describe("array drafts", () => {173 it("supports Array.isArray()", () => {174 const nextState = produce(baseState, s => {175 expect(Array.isArray(s.anArray)).toBeTruthy()176 s.anArray.push(1)177 })178 expect(Array.isArray(nextState.anArray)).toBeTruthy()179 })172 describe("array drafts", () => {173 it("supports Array.isArray()", () => {174 const nextState = produce(baseState, s => {175 expect(Array.isArray(s.anArray)).toBeTruthy()176 s.anArray.push(1)177 })178 expect(Array.isArray(nextState.anArray)).toBeTruthy()179 })180181 it("supports index access", () => {182 const value = baseState.anArray[0]183 const nextState = produce(baseState, s => {184 expect(s.anArray[0]).toBe(value)185 })186 expect(nextState).toBe(baseState)187 })181 it("supports index access", () => {182 const value = baseState.anArray[0]183 const nextState = produce(baseState, s => {184 expect(s.anArray[0]).toBe(value)185 })186 expect(nextState).toBe(baseState)187 })188189 it("supports iteration", () => {190 const base = [{id: 1, a: 1}, {id: 2, a: 1}]191 const findById = (collection, id) => {192 for (const item of collection) {193 if (item.id === id) return item194 }195 return null196 }197 const result = produce(base, draft => {198 const obj1 = findById(draft, 1)199 const obj2 = findById(draft, 2)200 obj1.a = 2201 obj2.a = 2202 })203 expect(result[0].a).toEqual(2)204 expect(result[1].a).toEqual(2)205 })189 it("supports iteration", () => {190 const base = [{id: 1, a: 1}, {id: 2, a: 1}]191 const findById = (collection, id) => {192 for (const item of collection) {193 if (item.id === id) return item194 }195 return null196 }197 const result = produce(base, draft => {198 const obj1 = findById(draft, 1)199 const obj2 = findById(draft, 2)200 obj1.a = 2201 obj2.a = 2202 })203 expect(result[0].a).toEqual(2)204 expect(result[1].a).toEqual(2)205 })206207 it("can assign an index via bracket notation", () => {208 const nextState = produce(baseState, s => {209 s.anArray[3] = true210 })211 expect(nextState).not.toBe(baseState)212 expect(nextState.anArray).not.toBe(baseState.anArray)213 expect(nextState.anArray[3]).toEqual(true)214 })207 it("can assign an index via bracket notation", () => {208 const nextState = produce(baseState, s => {209 s.anArray[3] = true210 })211 expect(nextState).not.toBe(baseState)212 expect(nextState.anArray).not.toBe(baseState.anArray)213 expect(nextState.anArray[3]).toEqual(true)214 })215216 it("can use splice() to both add and remove items", () => {217 const nextState = produce(baseState, s => {218 s.anArray.splice(1, 1, "a", "b")219 })220 expect(nextState.anArray).not.toBe(baseState.anArray)221 expect(nextState.anArray[1]).toBe("a")222 expect(nextState.anArray[2]).toBe("b")223 })216 it("can use splice() to both add and remove items", () => {217 const nextState = produce(baseState, s => {218 s.anArray.splice(1, 1, "a", "b")219 })220 expect(nextState.anArray).not.toBe(baseState.anArray)221 expect(nextState.anArray[1]).toBe("a")222 expect(nextState.anArray[2]).toBe("b")223 })224225 it("can truncate via the length property", () => {226 const baseLength = baseState.anArray.length227 const nextState = produce(baseState, s => {228 s.anArray.length = baseLength - 1229 })230 expect(nextState.anArray).not.toBe(baseState.anArray)231 expect(nextState.anArray.length).toBe(baseLength - 1)232 })225 it("can truncate via the length property", () => {226 const baseLength = baseState.anArray.length227 const nextState = produce(baseState, s => {228 s.anArray.length = baseLength - 1229 })230 expect(nextState.anArray).not.toBe(baseState.anArray)231 expect(nextState.anArray.length).toBe(baseLength - 1)232 })233234 it("can extend via the length property", () => {235 const baseLength = baseState.anArray.length236 const nextState = produce(baseState, s => {237 s.anArray.length = baseLength + 1238 })239 expect(nextState.anArray).not.toBe(baseState.anArray)240 expect(nextState.anArray.length).toBe(baseLength + 1)241 })234 it("can extend via the length property", () => {235 const baseLength = baseState.anArray.length236 const nextState = produce(baseState, s => {237 s.anArray.length = baseLength + 1238 })239 expect(nextState.anArray).not.toBe(baseState.anArray)240 expect(nextState.anArray.length).toBe(baseLength + 1)241 })242243 // Reported here: https://github.com/mweststrate/immer/issues/116244 it("can pop then push", () => {245 const nextState = produce([1, 2, 3], s => {246 s.pop()247 s.push(100)248 })249 expect(nextState).toEqual([1, 2, 100])250 })243 // Reported here: https://github.com/mweststrate/immer/issues/116244 it("can pop then push", () => {245 const nextState = produce([1, 2, 3], s => {246 s.pop()247 s.push(100)248 })249 expect(nextState).toEqual([1, 2, 100])250 })251252 it("can be sorted", () => {253 const baseState = [3, 1, 2]254 const nextState = produce(baseState, s => {255 s.sort()256 })257 expect(nextState).not.toBe(baseState)258 expect(nextState).toEqual([1, 2, 3])259 })252 it("can be sorted", () => {253 const baseState = [3, 1, 2]254 const nextState = produce(baseState, s => {255 s.sort()256 })257 expect(nextState).not.toBe(baseState)258 expect(nextState).toEqual([1, 2, 3])259 })260261 it("supports modifying nested objects", () => {262 const baseState = [{a: 1}, {}]263 const nextState = produce(baseState, s => {264 s[0].a++265 s[1].a = 0266 })267 expect(nextState).not.toBe(baseState)268 expect(nextState[0].a).toBe(2)269 expect(nextState[1].a).toBe(0)270 })261 it("supports modifying nested objects", () => {262 const baseState = [{a: 1}, {}]263 const nextState = produce(baseState, s => {264 s[0].a++265 s[1].a = 0266 })267 expect(nextState).not.toBe(baseState)268 expect(nextState[0].a).toBe(2)269 expect(nextState[1].a).toBe(0)270 })271272 it("never preserves non-numeric properties", () => {273 const baseState = []274 baseState.x = 7275 const nextState = produce(baseState, s => {276 s.push(3)277 })278 expect("x" in nextState).toBeFalsy()279 })272 it("never preserves non-numeric properties", () => {273 const baseState = []274 baseState.x = 7275 const nextState = produce(baseState, s => {276 s.push(3)277 })278 expect("x" in nextState).toBeFalsy()279 })280281 if (useProxies) {282 it("throws when a non-numeric property is added", () => {283 expect(() => {284 produce([], d => {285 d.x = 3286 })287 }).toThrowErrorMatchingSnapshot()288 })281 if (useProxies) {282 it("throws when a non-numeric property is added", () => {283 expect(() => {284 produce([], d => {285 d.x = 3286 })287 }).toThrowErrorMatchingSnapshot()288 })289290 it("throws when a non-numeric property is deleted", () => {291 expect(() => {292 const baseState = []293 baseState.x = 7294 produce(baseState, d => {295 delete d.x296 })297 }).toThrowErrorMatchingSnapshot()298 })299 }300 })290 it("throws when a non-numeric property is deleted", () => {291 expect(() => {292 const baseState = []293 baseState.x = 7294 produce(baseState, d => {295 delete d.x296 })297 }).toThrowErrorMatchingSnapshot()298 })299 }300 })301302 describe("map drafts", () => {303 it("supports key access", () => {304 const value = baseState.aMap.get("jedi")305 const nextState = produce(baseState, s => {306 expect(s.aMap.get("jedi")).toEqual(value)307 })308 expect(nextState).toBe(baseState)309 })302 describe("map drafts", () => {303 it("supports key access", () => {304 const value = baseState.aMap.get("jedi")305 const nextState = produce(baseState, s => {306 expect(s.aMap.get("jedi")).toEqual(value)307 })308 expect(nextState).toBe(baseState)309 })310311 it("supports key access for non-primitive keys", () => {312 const key = {prop: "val"}313 const base = new Map([[key, {id: 1, a: 1}]])314 const value = base.get(key)315 const nextState = produce(base, s => {316 expect(s.get(key)).toEqual(value)317 })318 expect(nextState).toBe(base)319 })311 it("supports key access for non-primitive keys", () => {312 const key = {prop: "val"}313 const base = new Map([[key, {id: 1, a: 1}]])314 const value = base.get(key)315 const nextState = produce(base, s => {316 expect(s.get(key)).toEqual(value)317 })318 expect(nextState).toBe(base)319 })320321 it("supports iteration", () => {322 const base = new Map([323 ["first", {id: 1, a: 1}],324 ["second", {id: 2, a: 1}]325 ])326 const findById = (map, id) => {327 for (const [, item] of map) {328 if (item.id === id) return item329 }330 return null331 }332 const result = produce(base, draft => {333 const obj1 = findById(draft, 1)334 const obj2 = findById(draft, 2)335 obj1.a = 2336 obj2.a = 2337 })338 expect(result).not.toBe(base)339 expect(result.get("first").a).toEqual(2)340 expect(result.get("second").a).toEqual(2)341 })321 it("supports iteration", () => {322 const base = new Map([323 ["first", {id: 1, a: 1}],324 ["second", {id: 2, a: 1}]325 ])326 const findById = (map, id) => {327 for (const [, item] of map) {328 if (item.id === id) return item329 }330 return null331 }332 const result = produce(base, draft => {333 const obj1 = findById(draft, 1)334 const obj2 = findById(draft, 2)335 obj1.a = 2336 obj2.a = 2337 })338 expect(result).not.toBe(base)339 expect(result.get("first").a).toEqual(2)340 expect(result.get("second").a).toEqual(2)341 })342343 it("supports 'entries'", () => {344 const base = new Map([345 ["first", {id: 1, a: 1}],346 ["second", {id: 2, a: 1}]347 ])348 const findById = (map, id) => {349 for (const [, item] of map.entries()) {350 if (item.id === id) return item351 }352 return null353 }354 const result = produce(base, draft => {355 const obj1 = findById(draft, 1)356 const obj2 = findById(draft, 2)357 obj1.a = 2358 obj2.a = 2359 })360 expect(result).not.toBe(base)361 expect(result.get("first").a).toEqual(2)362 expect(result.get("second").a).toEqual(2)363 })343 it("supports 'entries'", () => {344 const base = new Map([345 ["first", {id: 1, a: 1}],346 ["second", {id: 2, a: 1}]347 ])348 const findById = (map, id) => {349 for (const [, item] of map.entries()) {350 if (item.id === id) return item351 }352 return null353 }354 const result = produce(base, draft => {355 const obj1 = findById(draft, 1)356 const obj2 = findById(draft, 2)357 obj1.a = 2358 obj2.a = 2359 })360 expect(result).not.toBe(base)361 expect(result.get("first").a).toEqual(2)362 expect(result.get("second").a).toEqual(2)363 })364365 it("supports 'values'", () => {366 const base = new Map([367 ["first", {id: 1, a: 1}],368 ["second", {id: 2, a: 1}]369 ])370 const findById = (map, id) => {371 for (const item of map.values()) {372 if (item.id === id) return item373 }374 return null375 }376 const result = produce(base, draft => {377 const obj1 = findById(draft, 1)378 const obj2 = findById(draft, 2)379 obj1.a = 2380 obj2.a = 2381 })382 expect(result).not.toBe(base)383 expect(result.get("first").a).toEqual(2)384 expect(result.get("second").a).toEqual(2)385 })365 it("supports 'values'", () => {366 const base = new Map([367 ["first", {id: 1, a: 1}],368 ["second", {id: 2, a: 1}]369 ])370 const findById = (map, id) => {371 for (const item of map.values()) {372 if (item.id === id) return item373 }374 return null375 }376 const result = produce(base, draft => {377 const obj1 = findById(draft, 1)378 const obj2 = findById(draft, 2)379 obj1.a = 2380 obj2.a = 2381 })382 expect(result).not.toBe(base)383 expect(result.get("first").a).toEqual(2)384 expect(result.get("second").a).toEqual(2)385 })386387 it("supports 'keys", () => {388 const base = new Map([389 ["first", Symbol()],390 ["second", Symbol()]391 ])392 const result = produce(base, draft => {393 expect([...draft.keys()]).toEqual(["first", "second"])394 draft.set("third", Symbol())395 expect([...draft.keys()]).toEqual([396 "first",397 "second",398 "third"399 ])400 })401 })387 it("supports 'keys", () => {388 const base = new Map([["first", Symbol()], ["second", Symbol()]])389 const result = produce(base, draft => {390 expect([...draft.keys()]).toEqual(["first", "second"])391 draft.set("third", Symbol())392 expect([...draft.keys()]).toEqual(["first", "second", "third"])393 })394 })395403 it("supports forEach", () => {404 const key1 = {prop: "val1"}405 const key2 = {prop: "val2"}406 const base = new Map([407 ["first", {id: 1, a: 1}],408 ["second", {id: 2, a: 1}],409 [key1, {id: 3, a: 1}],410 [key2, {id: 4, a: 1}]411 ])412 const result = produce(base, draft => {413 let sum1 = 0414 draft.forEach(({a}) => {415 sum1 += a416 })417 expect(sum1).toBe(4)418 let sum2 = 0419 draft.get("first").a = 10420 draft.get("second").a = 20421 draft.get(key1).a = 30422 draft.get(key2).a = 40423 draft.forEach(({a}) => {424 sum2 += a425 })426 expect(sum2).toBe(100)427 })428 expect(result).not.toBe(base)429 expect(base.get("first").a).toEqual(1)430 expect(base.get("second").a).toEqual(1)431 expect(base.get(key1).a).toEqual(1)432 expect(base.get(key2).a).toEqual(1)433 expect(result.get("first").a).toEqual(10)434 expect(result.get("second").a).toEqual(20)435 expect(result.get(key1).a).toEqual(30)436 expect(result.get(key2).a).toEqual(40)437 })396 it("supports forEach", () => {397 const key1 = {prop: "val1"}398 const key2 = {prop: "val2"}399 const base = new Map([400 ["first", {id: 1, a: 1}],401 ["second", {id: 2, a: 1}],402 [key1, {id: 3, a: 1}],403 [key2, {id: 4, a: 1}]404 ])405 const result = produce(base, draft => {406 let sum1 = 0407 draft.forEach(({a}) => {408 sum1 += a409 })410 expect(sum1).toBe(4)411 let sum2 = 0412 draft.get("first").a = 10413 draft.get("second").a = 20414 draft.get(key1).a = 30415 draft.get(key2).a = 40416 draft.forEach(({a}) => {417 sum2 += a418 })419 expect(sum2).toBe(100)420 })421 expect(result).not.toBe(base)422 expect(base.get("first").a).toEqual(1)423 expect(base.get("second").a).toEqual(1)424 expect(base.get(key1).a).toEqual(1)425 expect(base.get(key2).a).toEqual(1)426 expect(result.get("first").a).toEqual(10)427 expect(result.get("second").a).toEqual(20)428 expect(result.get(key1).a).toEqual(30)429 expect(result.get(key2).a).toEqual(40)430 })431439 it("supports forEach mutation", () => {440 const base = new Map([441 ["first", {id: 1, a: 1}],442 ["second", {id: 2, a: 1}]443 ])444 const result = produce(base, draft => {445 draft.forEach(item => {446 item.a = 100447 })448 })449 expect(result).not.toBe(base)450 expect(result.get("first").a).toEqual(100)451 expect(result.get("second").a).toEqual(100)452 })432 it("supports forEach mutation", () => {433 const base = new Map([434 ["first", {id: 1, a: 1}],435 ["second", {id: 2, a: 1}]436 ])437 const result = produce(base, draft => {438 draft.forEach(item => {439 item.a = 100440 })441 })442 expect(result).not.toBe(base)443 expect(result.get("first").a).toEqual(100)444 expect(result.get("second").a).toEqual(100)445 })446454 it("can assign by key", () => {455 const nextState = produce(baseState, s => {456 // Map.prototype.set should return the Map itself457 const res = s.aMap.set("force", true)458 expect(res).toBe(s.aMap[DRAFT_STATE].draft)459 })460 expect(nextState).not.toBe(baseState)461 expect(nextState.aMap).not.toBe(baseState.aMap)462 expect(nextState.aMap.get("force")).toEqual(true)463 })447 it("can assign by key", () => {448 const nextState = produce(baseState, s => {449 // Map.prototype.set should return the Map itself450 const res = s.aMap.set("force", true)451 expect(res).toBe(s.aMap[DRAFT_STATE].draft)452 })453 expect(nextState).not.toBe(baseState)454 expect(nextState.aMap).not.toBe(baseState.aMap)455 expect(nextState.aMap.get("force")).toEqual(true)456 })457465 it("can assign by a non-primitive key", () => {466 const key = {prop: "val"}467 const value = {id: 1, a: 1}468 const base = new Map([[key, value]])469 const nextState = produce(base, s => {470 s.set(key, true)471 })472 expect(nextState).not.toBe(base)473 expect(base.get(key)).toEqual(value)474 expect(nextState.get(key)).toEqual(true)475 })458 it("can assign by a non-primitive key", () => {459 const key = {prop: "val"}460 const value = {id: 1, a: 1}461 const base = new Map([[key, value]])462 const nextState = produce(base, s => {463 s.set(key, true)464 })465 expect(nextState).not.toBe(base)466 expect(base.get(key)).toEqual(value)467 expect(nextState.get(key)).toEqual(true)468 })469477 it("state stays the same if the the same item is assigned by key", () => {478 const nextState = produce(baseState, s => {479 s.aMap.set("jediTotal", 42)480 })481 expect(nextState).toBe(baseState)482 expect(nextState.aMap).toBe(baseState.aMap)483 })470 it("state stays the same if the the same item is assigned by key", () => {471 const nextState = produce(baseState, s => {472 s.aMap.set("jediTotal", 42)473 })474 expect(nextState).toBe(baseState)475 expect(nextState.aMap).toBe(baseState.aMap)476 })477485 it("returns 'size'", () => {486 const nextState = produce(baseState, s => {487 s.aMap.set("newKey", true)488 expect(s.aMap.size).toBe(baseState.aMap.size + 1)489 })490 expect(nextState).not.toBe(baseState)491 expect(nextState.aMap).not.toBe(baseState.aMap)492 expect(nextState.aMap.get("newKey")).toEqual(true)493 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)494 })478 it("returns 'size'", () => {479 const nextState = produce(baseState, s => {480 s.aMap.set("newKey", true)481 expect(s.aMap.size).toBe(baseState.aMap.size + 1)482 })483 expect(nextState).not.toBe(baseState)484 expect(nextState.aMap).not.toBe(baseState.aMap)485 expect(nextState.aMap.get("newKey")).toEqual(true)486 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)487 })488496 it("can use 'delete' to remove items", () => {497 const nextState = produce(baseState, s => {498 expect(s.aMap.has("jedi")).toBe(true)499 s.aMap.delete("jedi")500 expect(s.aMap.has("jedi")).toBe(false)501 })502 expect(nextState.aMap).not.toBe(baseState.aMap)503 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)504 expect(baseState.aMap.has("jedi")).toBe(true)505 expect(nextState.aMap.has("jedi")).toBe(false)506 })489 it("can use 'delete' to remove items", () => {490 const nextState = produce(baseState, s => {491 expect(s.aMap.has("jedi")).toBe(true)492 s.aMap.delete("jedi")493 expect(s.aMap.has("jedi")).toBe(false)494 })495 expect(nextState.aMap).not.toBe(baseState.aMap)496 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)497 expect(baseState.aMap.has("jedi")).toBe(true)498 expect(nextState.aMap.has("jedi")).toBe(false)499 })500508 it("can use 'clear' to remove items", () => {509 const nextState = produce(baseState, s => {510 expect(s.aMap.size).not.toBe(0)511 s.aMap.clear()512 expect(s.aMap.size).toBe(0)513 })514 expect(nextState.aMap).not.toBe(baseState.aMap)515 expect(baseState.aMap.size).not.toBe(0)516 expect(nextState.aMap.size).toBe(0)517 })501 it("can use 'clear' to remove items", () => {502 const nextState = produce(baseState, s => {503 expect(s.aMap.size).not.toBe(0)504 s.aMap.clear()505 expect(s.aMap.size).toBe(0)506 })507 expect(nextState.aMap).not.toBe(baseState.aMap)508 expect(baseState.aMap.size).not.toBe(0)509 expect(nextState.aMap.size).toBe(0)510 })511519 it("support 'has'", () => {520 const nextState = produce(baseState, s => {521 expect(s.aMap.has("newKey")).toBe(false)522 s.aMap.set("newKey", true)523 expect(s.aMap.has("newKey")).toBe(true)524 })525 expect(nextState).not.toBe(baseState)526 expect(nextState.aMap).not.toBe(baseState.aMap)527 expect(baseState.aMap.has("newKey")).toBe(false)528 expect(nextState.aMap.has("newKey")).toBe(true)529 })512 it("support 'has'", () => {513 const nextState = produce(baseState, s => {514 expect(s.aMap.has("newKey")).toBe(false)515 s.aMap.set("newKey", true)516 expect(s.aMap.has("newKey")).toBe(true)517 })518 expect(nextState).not.toBe(baseState)519 expect(nextState.aMap).not.toBe(baseState.aMap)520 expect(baseState.aMap.has("newKey")).toBe(false)521 expect(nextState.aMap.has("newKey")).toBe(true)522 })523531 it("supports nested maps", () => {532 const base = new Map([533 ["first", new Map([["second", {prop: "test"}]])]534 ])535 const result = produce(base, draft => {536 draft.get("first").get("second").prop = "test1"537 })538 expect(result).not.toBe(base)539 expect(result.get("first")).not.toBe(base.get("first"))540 expect(result.get("first").get("second")).not.toBe(541 base.get("first").get("second")542 )543 expect(base.get("first").get("second").prop).toBe("test")544 expect(result.get("first").get("second").prop).toBe("test1")545 })546 })524 it("supports nested maps", () => {525 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])526 const result = produce(base, draft => {527 draft.get("first").get("second").prop = "test1"528 })529 expect(result).not.toBe(base)530 expect(result.get("first")).not.toBe(base.get("first"))531 expect(result.get("first").get("second")).not.toBe(532 base.get("first").get("second")533 )534 expect(base.get("first").get("second").prop).toBe("test")535 expect(result.get("first").get("second").prop).toBe("test1")536 })537 })538548 describe("set drafts", () => {549 it("supports iteration", () => {550 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])551 const findById = (set, id) => {552 for (const item of set) {553 if (item.id === id) return item554 }555 return null556 }557 const result = produce(base, draft => {558 const obj1 = findById(draft, 1)559 const obj2 = findById(draft, 2)560 obj1.a = 2561 obj2.a = 2562 })563 expect(result).not.toBe(base)564 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))565 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))566 })539 describe("set drafts", () => {540 it("supports iteration", () => {541 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])542 const findById = (set, id) => {543 for (const item of set) {544 if (item.id === id) return item545 }546 return null547 }548 const result = produce(base, draft => {549 const obj1 = findById(draft, 1)550 const obj2 = findById(draft, 2)551 obj1.a = 2552 obj2.a = 2553 })554 expect(result).not.toBe(base)555 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))556 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))557 })558568 it("supports 'entries'", () => {569 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])570 const findById = (set, id) => {571 for (const [item1, item2] of set.entries()) {572 expect(item1).toBe(item2)573 if (item1.id === id) return item1574 }575 return null576 }577 const result = produce(base, draft => {578 const obj1 = findById(draft, 1)579 const obj2 = findById(draft, 2)580 obj1.a = 2581 obj2.a = 2582 })583 expect(result).not.toBe(base)584 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))585 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))586 })559 it("supports 'entries'", () => {560 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])561 const findById = (set, id) => {562 for (const [item1, item2] of set.entries()) {563 expect(item1).toBe(item2)564 if (item1.id === id) return item1565 }566 return null567 }568 const result = produce(base, draft => {569 const obj1 = findById(draft, 1)570 const obj2 = findById(draft, 2)571 obj1.a = 2572 obj2.a = 2573 })574 expect(result).not.toBe(base)575 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))576 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))577 })578588 it("supports 'values'", () => {589 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])590 const findById = (set, id) => {591 for (const item of set.values()) {592 if (item.id === id) return item593 }594 return null595 }596 const result = produce(base, draft => {597 const obj1 = findById(draft, 1)598 const obj2 = findById(draft, 2)599 obj1.a = 2600 obj2.a = 2601 })602 expect(result).not.toBe(base)603 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))604 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))605 })579 it("supports 'values'", () => {580 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])581 const findById = (set, id) => {582 for (const item of set.values()) {583 if (item.id === id) return item584 }585 return null586 }587 const result = produce(base, draft => {588 const obj1 = findById(draft, 1)589 const obj2 = findById(draft, 2)590 obj1.a = 2591 obj2.a = 2592 })593 expect(result).not.toBe(base)594 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))595 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))596 })597607 it("supports 'keys'", () => {608 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])609 const findById = (set, id) => {610 for (const item of set.keys()) {611 if (item.id === id) return item612 }613 return null614 }615 const result = produce(base, draft => {616 const obj1 = findById(draft, 1)617 const obj2 = findById(draft, 2)618 obj1.a = 2619 obj2.a = 2620 })621 expect(result).not.toBe(base)622 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))623 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))624 })598 it("supports 'keys'", () => {599 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])600 const findById = (set, id) => {601 for (const item of set.keys()) {602 if (item.id === id) return item603 }604 return null605 }606 const result = produce(base, draft => {607 const obj1 = findById(draft, 1)608 const obj2 = findById(draft, 2)609 obj1.a = 2610 obj2.a = 2611 })612 expect(result).not.toBe(base)613 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))614 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))615 })616626 it("supports forEach with mutation after reads", () => {627 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])628 const result = produce(base, draft => {629 let sum1 = 0630 draft.forEach(({a}) => {631 sum1 += a632 })633 expect(sum1).toBe(3)634 let sum2 = 0635 draft.forEach(item => {636 item.a += 10637 sum2 += item.a638 })639 expect(sum2).toBe(23)640 })641 expect(result).not.toBe(base)642 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))643 expect(result).toEqual(644 new Set([{id: 1, a: 11}, {id: 2, a: 12}])645 )646 })617 it("supports forEach with mutation after reads", () => {618 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])619 const result = produce(base, draft => {620 let sum1 = 0621 draft.forEach(({a}) => {622 sum1 += a623 })624 expect(sum1).toBe(3)625 let sum2 = 0626 draft.forEach(item => {627 item.a += 10628 sum2 += item.a629 })630 expect(sum2).toBe(23)631 })632 expect(result).not.toBe(base)633 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))634 expect(result).toEqual(new Set([{id: 1, a: 11}, {id: 2, a: 12}]))635 })636648 it("state stays the same if the same item is added", () => {649 const nextState = produce(baseState, s => {650 s.aSet.add("Luke")651 })652 expect(nextState).toBe(baseState)653 expect(nextState.aSet).toBe(baseState.aSet)654 })637 it("state stays the same if the same item is added", () => {638 const nextState = produce(baseState, s => {639 s.aSet.add("Luke")640 })641 expect(nextState).toBe(baseState)642 expect(nextState.aSet).toBe(baseState.aSet)643 })644656 it("can add new items", () => {657 const nextState = produce(baseState, s => {658 // Set.prototype.set should return the Set itself659 const res = s.aSet.add("force")660 expect(res).toBe(s.aSet[DRAFT_STATE].draft)661 })662 expect(nextState).not.toBe(baseState)663 expect(nextState.aSet).not.toBe(baseState.aSet)664 expect(baseState.aSet.has("force")).toBe(false)665 expect(nextState.aSet.has("force")).toBe(true)666 })645 it("can add new items", () => {646 const nextState = produce(baseState, s => {647 // Set.prototype.set should return the Set itself648 const res = s.aSet.add("force")649 expect(res).toBe(s.aSet[DRAFT_STATE].draft)650 })651 expect(nextState).not.toBe(baseState)652 expect(nextState.aSet).not.toBe(baseState.aSet)653 expect(baseState.aSet.has("force")).toBe(false)654 expect(nextState.aSet.has("force")).toBe(true)655 })656668 it("returns 'size'", () => {669 const nextState = produce(baseState, s => {670 s.aSet.add("newKey")671 expect(s.aSet.size).toBe(baseState.aSet.size + 1)672 })673 expect(nextState).not.toBe(baseState)674 expect(nextState.aSet).not.toBe(baseState.aSet)675 expect(nextState.aSet.has("newKey")).toBe(true)676 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)677 })657 it("returns 'size'", () => {658 const nextState = produce(baseState, s => {659 s.aSet.add("newKey")660 expect(s.aSet.size).toBe(baseState.aSet.size + 1)661 })662 expect(nextState).not.toBe(baseState)663 expect(nextState.aSet).not.toBe(baseState.aSet)664 expect(nextState.aSet.has("newKey")).toBe(true)665 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)666 })667679 it("can use 'delete' to remove items", () => {680 const nextState = produce(baseState, s => {681 expect(s.aSet.has("Luke")).toBe(true)682 s.aSet.delete("Luke")683 expect(s.aSet.has("Luke")).toBe(false)684 })685 expect(nextState.aSet).not.toBe(baseState.aSet)686 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)687 expect(baseState.aSet.has("Luke")).toBe(true)688 expect(nextState.aSet.has("Luke")).toBe(false)689 })668 it("can use 'delete' to remove items", () => {669 const nextState = produce(baseState, s => {670 expect(s.aSet.has("Luke")).toBe(true)671 s.aSet.delete("Luke")672 expect(s.aSet.has("Luke")).toBe(false)673 })674 expect(nextState.aSet).not.toBe(baseState.aSet)675 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)676 expect(baseState.aSet.has("Luke")).toBe(true)677 expect(nextState.aSet.has("Luke")).toBe(false)678 })679691 it("can use 'clear' to remove items", () => {692 const nextState = produce(baseState, s => {693 expect(s.aSet.size).not.toBe(0)694 s.aSet.clear()695 expect(s.aSet.size).toBe(0)696 })697 expect(nextState.aSet).not.toBe(baseState.aSet)698 expect(baseState.aSet.size).not.toBe(0)699 expect(nextState.aSet.size).toBe(0)700 })680 it("can use 'clear' to remove items", () => {681 const nextState = produce(baseState, s => {682 expect(s.aSet.size).not.toBe(0)683 s.aSet.clear()684 expect(s.aSet.size).toBe(0)685 })686 expect(nextState.aSet).not.toBe(baseState.aSet)687 expect(baseState.aSet.size).not.toBe(0)688 expect(nextState.aSet.size).toBe(0)689 })690702 it("supports 'has'", () => {703 const nextState = produce(baseState, s => {704 expect(s.aSet.has("newKey")).toBe(false)705 s.aSet.add("newKey")706 expect(s.aSet.has("newKey")).toBe(true)707 })708 expect(nextState).not.toBe(baseState)709 expect(nextState.aSet).not.toBe(baseState.aSet)710 expect(baseState.aSet.has("newKey")).toBe(false)711 expect(nextState.aSet.has("newKey")).toBe(true)712 })691 it("supports 'has'", () => {692 const nextState = produce(baseState, s => {693 expect(s.aSet.has("newKey")).toBe(false)694 s.aSet.add("newKey")695 expect(s.aSet.has("newKey")).toBe(true)696 })697 expect(nextState).not.toBe(baseState)698 expect(nextState.aSet).not.toBe(baseState.aSet)699 expect(baseState.aSet.has("newKey")).toBe(false)700 expect(nextState.aSet.has("newKey")).toBe(true)701 })702714 it("supports nested sets", () => {715 const base = new Set([new Set(["Serenity"])])716 const result = produce(base, draft => {717 draft.forEach(nestedItem => nestedItem.add("Firefly"))718 })719 expect(result).not.toBe(base)720 expect(base).toEqual(new Set([new Set(["Serenity"])]))721 expect(result).toEqual(722 new Set([new Set(["Serenity", "Firefly"])])723 )724 })725 })703 it("supports nested sets", () => {704 const base = new Set([new Set(["Serenity"])])705 const result = produce(base, draft => {706 draft.forEach(nestedItem => nestedItem.add("Firefly"))707 })708 expect(result).not.toBe(base)709 expect(base).toEqual(new Set([new Set(["Serenity"])]))710 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))711 })712 })713727 it("supports `immerable` symbol on constructor", () => {728 class One {}729 One[immerable] = true730 const baseState = new One()731 const nextState = produce(baseState, draft => {732 expect(draft).not.toBe(baseState)733 draft.foo = true734 })735 expect(nextState).not.toBe(baseState)736 expect(nextState.foo).toBeTruthy()737 })714 it("supports `immerable` symbol on constructor", () => {715 class One {}716 One[immerable] = true717 const baseState = new One()718 const nextState = produce(baseState, draft => {719 expect(draft).not.toBe(baseState)720 draft.foo = true721 })722 expect(nextState).not.toBe(baseState)723 expect(nextState.foo).toBeTruthy()724 })725739 it("preserves symbol properties", () => {740 const test = Symbol("test")741 const baseState = {[test]: true}742 const nextState = produce(baseState, s => {743 expect(s[test]).toBeTruthy()744 s.foo = true745 })746 expect(nextState).toEqual({747 [test]: true,748 foo: true749 })750 })726 it("preserves symbol properties", () => {727 const test = Symbol("test")728 const baseState = {[test]: true}729 const nextState = produce(baseState, s => {730 expect(s[test]).toBeTruthy()731 s.foo = true732 })733 expect(nextState).toEqual({734 [test]: true,735 foo: true736 })737 })738752 it("preserves non-enumerable properties", () => {753 const baseState = {}754 // Non-enumerable object property755 Object.defineProperty(baseState, "foo", {756 value: {a: 1},757 enumerable: false758 })759 // Non-enumerable primitive property760 Object.defineProperty(baseState, "bar", {761 value: 1,762 enumerable: false763 })764 const nextState = produce(baseState, s => {765 expect(s.foo).toBeTruthy()766 expect(isEnumerable(s, "foo")).toBeFalsy()767 s.bar++768 expect(isEnumerable(s, "foo")).toBeFalsy()769 s.foo.a++770 expect(isEnumerable(s, "foo")).toBeFalsy()771 })772 expect(nextState.foo).toBeTruthy()773 expect(isEnumerable(nextState, "foo")).toBeFalsy()774 })739 it("preserves non-enumerable properties", () => {740 const baseState = {}741 // Non-enumerable object property742 Object.defineProperty(baseState, "foo", {743 value: {a: 1},744 enumerable: false745 })746 // Non-enumerable primitive property747 Object.defineProperty(baseState, "bar", {748 value: 1,749 enumerable: false750 })751 const nextState = produce(baseState, s => {752 expect(s.foo).toBeTruthy()753 expect(isEnumerable(s, "foo")).toBeFalsy()754 s.bar++755 expect(isEnumerable(s, "foo")).toBeFalsy()756 s.foo.a++757 expect(isEnumerable(s, "foo")).toBeFalsy()758 })759 expect(nextState.foo).toBeTruthy()760 expect(isEnumerable(nextState, "foo")).toBeFalsy()761 })762776 it("throws on computed properties", () => {777 const baseState = {}778 Object.defineProperty(baseState, "foo", {779 get: () => {},780 enumerable: true781 })782 expect(() => {783 produce(baseState, s => {784 // Proxies only throw once a change is made.785 if (useProxies) {786 s.modified = true787 }788 })789 }).toThrowErrorMatchingSnapshot()790 })763 it("throws on computed properties", () => {764 const baseState = {}765 Object.defineProperty(baseState, "foo", {766 get: () => {},767 enumerable: true768 })769 expect(() => {770 produce(baseState, s => {771 // Proxies only throw once a change is made.772 if (useProxies) {773 s.modified = true774 }775 })776 }).toThrowErrorMatchingSnapshot()777 })778792 it("allows inherited computed properties", () => {793 const proto = {}794 Object.defineProperty(proto, "foo", {795 get() {796 return this.bar797 },798 set(val) {799 this.bar = val800 }801 })802 const baseState = Object.create(proto)803 produce(baseState, s => {804 expect(s.bar).toBeUndefined()805 s.foo = {}806 expect(s.bar).toBeDefined()807 expect(s.foo).toBe(s.bar)808 })809 })779 it("allows inherited computed properties", () => {780 const proto = {}781 Object.defineProperty(proto, "foo", {782 get() {783 return this.bar784 },785 set(val) {786 this.bar = val787 }788 })789 const baseState = Object.create(proto)790 produce(baseState, s => {791 expect(s.bar).toBeUndefined()792 s.foo = {}793 expect(s.bar).toBeDefined()794 expect(s.foo).toBe(s.bar)795 })796 })797811 it("supports a base state with multiple references to an object", () => {812 const obj = {}813 const res = produce({a: obj, b: obj}, d => {814 // Two drafts are created for each occurrence of an object in the base state.815 expect(d.a).not.toBe(d.b)816 d.a.z = true817 expect(d.b.z).toBeUndefined()818 })819 expect(res.b).toBe(obj)820 expect(res.a).not.toBe(res.b)821 expect(res.a.z).toBeTruthy()822 })798 it("supports a base state with multiple references to an object", () => {799 const obj = {}800 const res = produce({a: obj, b: obj}, d => {801 // Two drafts are created for each occurrence of an object in the base state.802 expect(d.a).not.toBe(d.b)803 d.a.z = true804 expect(d.b.z).toBeUndefined()805 })806 expect(res.b).toBe(obj)807 expect(res.a).not.toBe(res.b)808 expect(res.a.z).toBeTruthy()809 })810824 // NOTE: Except the root draft.825 it("supports multiple references to any modified draft", () => {826 const next = produce({a: {b: 1}}, d => {827 d.a.b++828 d.b = d.a829 })830 expect(next.a).toBe(next.b)831 })811 // NOTE: Except the root draft.812 it("supports multiple references to any modified draft", () => {813 const next = produce({a: {b: 1}}, d => {814 d.a.b++815 d.b = d.a816 })817 expect(next.a).toBe(next.b)818 })819833 it("can rename nested objects (no changes)", () => {834 const nextState = produce({obj: {}}, s => {835 s.foo = s.obj836 delete s.obj837 })838 expect(nextState).toEqual({foo: {}})839 })820 it("can rename nested objects (no changes)", () => {821 const nextState = produce({obj: {}}, s => {822 s.foo = s.obj823 delete s.obj824 })825 expect(nextState).toEqual({foo: {}})826 })827841 // Very similar to the test before, but the reused object has one842 // property changed, one added, and one removed.843 it("can rename nested objects (with changes)", () => {844 const nextState = produce({obj: {a: 1, b: 1}}, s => {845 s.obj.a = true // change846 delete s.obj.b // delete847 s.obj.c = true // add828 // Very similar to the test before, but the reused object has one829 // property changed, one added, and one removed.830 it("can rename nested objects (with changes)", () => {831 const nextState = produce({obj: {a: 1, b: 1}}, s => {832 s.obj.a = true // change833 delete s.obj.b // delete834 s.obj.c = true // add835849 s.foo = s.obj850 delete s.obj851 })852 expect(nextState).toEqual({foo: {a: true, c: true}})853 })836 s.foo = s.obj837 delete s.obj838 })839 expect(nextState).toEqual({foo: {a: true, c: true}})840 })841855 it("can nest a draft in a new object (no changes)", () => {856 const baseState = {obj: {}}857 const nextState = produce(baseState, s => {858 s.foo = {bar: s.obj}859 delete s.obj860 })861 expect(nextState.foo.bar).toBe(baseState.obj)862 })842 it("can nest a draft in a new object (no changes)", () => {843 const baseState = {obj: {}}844 const nextState = produce(baseState, s => {845 s.foo = {bar: s.obj}846 delete s.obj847 })848 expect(nextState.foo.bar).toBe(baseState.obj)849 })850864 it("can nest a modified draft in a new object", () => {865 const nextState = produce({obj: {a: 1, b: 1}}, s => {866 s.obj.a = true // change867 delete s.obj.b // delete868 s.obj.c = true // add851 it("can nest a modified draft in a new object", () => {852 const nextState = produce({obj: {a: 1, b: 1}}, s => {853 s.obj.a = true // change854 delete s.obj.b // delete855 s.obj.c = true // add856870 s.foo = {bar: s.obj}871 delete s.obj872 })873 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})874 })857 s.foo = {bar: s.obj}858 delete s.obj859 })860 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})861 })862876 it("supports assigning undefined to an existing property", () => {877 const nextState = produce(baseState, s => {878 s.aProp = undefined879 })880 expect(nextState).not.toBe(baseState)881 expect(nextState.aProp).toBe(undefined)882 })863 it("supports assigning undefined to an existing property", () => {864 const nextState = produce(baseState, s => {865 s.aProp = undefined866 })867 expect(nextState).not.toBe(baseState)868 expect(nextState.aProp).toBe(undefined)869 })870884 it("supports assigning undefined to a new property", () => {885 const baseState = {}886 const nextState = produce(baseState, s => {887 s.aProp = undefined888 })889 expect(nextState).not.toBe(baseState)890 expect(nextState.aProp).toBe(undefined)891 })871 it("supports assigning undefined to a new property", () => {872 const baseState = {}873 const nextState = produce(baseState, s => {874 s.aProp = undefined875 })876 expect(nextState).not.toBe(baseState)877 expect(nextState.aProp).toBe(undefined)878 })879893 // NOTE: ES5 drafts only protect existing properties when revoked.894 it("revokes the draft once produce returns", () => {895 const expectRevoked = (fn, shouldThrow = true) => {896 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()897 else expect(fn).not.toThrow()898 }880 // NOTE: ES5 drafts only protect existing properties when revoked.881 it("revokes the draft once produce returns", () => {882 const expectRevoked = (fn, shouldThrow = true) => {883 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()884 else expect(fn).not.toThrow()885 }886900 // Test object drafts:901 let draft902 produce({a: 1, b: 1}, s => {903 draft = s904 delete s.b905 })887 // Test object drafts:888 let draft889 produce({a: 1, b: 1}, s => {890 draft = s891 delete s.b892 })893907 // Access known property on object draft.908 expectRevoked(() => {909 draft.a910 })894 // Access known property on object draft.895 expectRevoked(() => {896 draft.a897 })898912 // Assign known property on object draft.913 expectRevoked(() => {914 draft.a = true915 })899 // Assign known property on object draft.900 expectRevoked(() => {901 draft.a = true902 })903917 // Access unknown property on object draft.918 expectRevoked(() => {919 draft.z920 }, useProxies)904 // Access unknown property on object draft.905 expectRevoked(() => {906 draft.z907 }, useProxies)908922 // Assign unknown property on object draft.923 expectRevoked(() => {924 draft.z = true925 }, useProxies)909 // Assign unknown property on object draft.910 expectRevoked(() => {911 draft.z = true912 }, useProxies)913927 // Test array drafts:928 produce([1, 2], s => {929 draft = s930 s.pop()931 })914 // Test array drafts:915 produce([1, 2], s => {916 draft = s917 s.pop()918 })919933 // Access known index of an array draft.934 expectRevoked(() => {935 draft[0]936 })920 // Access known index of an array draft.921 expectRevoked(() => {922 draft[0]923 })924938 // Assign known index of an array draft.939 expectRevoked(() => {940 draft[0] = true941 })925 // Assign known index of an array draft.926 expectRevoked(() => {927 draft[0] = true928 })929943 // Access unknown index of an array draft.944 expectRevoked(() => {945 draft[1]946 }, useProxies)930 // Access unknown index of an array draft.931 expectRevoked(() => {932 draft[1]933 }, useProxies)934948 // Assign unknown index of an array draft.949 expectRevoked(() => {950 draft[1] = true951 }, useProxies)952 })935 // Assign unknown index of an array draft.936 expectRevoked(() => {937 draft[1] = true938 }, useProxies)939 })940954 it("can access a child draft that was created before the draft was modified", () => {955 produce({a: {}}, s => {956 const before = s.a957 s.b = 1958 expect(s.a).toBe(before)959 })960 })941 it("can access a child draft that was created before the draft was modified", () => {942 produce({a: {}}, s => {943 const before = s.a944 s.b = 1945 expect(s.a).toBe(before)946 })947 })948962 it("should reflect all changes made in the draft immediately", () => {963 produce(baseState, draft => {964 draft.anArray[0] = 5965 draft.anArray.unshift("test")966 expect(enumerableOnly(draft.anArray)).toEqual([967 "test",968 5,969 2,970 {c: 3},971 1972 ])973 draft.stuffz = "coffee"974 expect(draft.stuffz).toBe("coffee")975 })976 })949 it("should reflect all changes made in the draft immediately", () => {950 produce(baseState, draft => {951 draft.anArray[0] = 5952 draft.anArray.unshift("test")953 expect(enumerableOnly(draft.anArray)).toEqual(["test", 5, 2, {c: 3}, 1])954 draft.stuffz = "coffee"955 expect(draft.stuffz).toBe("coffee")956 })957 })958978 if (useProxies)979 it("throws when Object.defineProperty() is used on drafts", () => {980 expect(() => {981 produce({}, draft => {982 Object.defineProperty(draft, "xx", {983 enumerable: true,984 writeable: true,985 value: 2986 })987 })988 }).toThrowErrorMatchingSnapshot()989 })959 if (useProxies)960 it("throws when Object.defineProperty() is used on drafts", () => {961 expect(() => {962 produce({}, draft => {963 Object.defineProperty(draft, "xx", {964 enumerable: true,965 writeable: true,966 value: 2967 })968 })969 }).toThrowErrorMatchingSnapshot()970 })971991 it("should handle constructor correctly", () => {992 const baseState = {993 arr: new Array(),994 obj: new Object()995 }996 const result = produce(baseState, draft => {997 draft.arrConstructed = draft.arr.constructor(1)998 draft.objConstructed = draft.obj.constructor(1)999 })1000 expect(result.arrConstructed).toEqual(new Array().constructor(1))1001 expect(result.objConstructed).toEqual(new Object().constructor(1))1002 })972 it("should handle constructor correctly", () => {973 const baseState = {974 arr: new Array(),975 obj: new Object()976 }977 const result = produce(baseState, draft => {978 draft.arrConstructed = draft.arr.constructor(1)979 draft.objConstructed = draft.obj.constructor(1)980 })981 expect(result.arrConstructed).toEqual(new Array().constructor(1))982 expect(result.objConstructed).toEqual(new Object().constructor(1))983 })9841004 it("should handle equality correctly - 1", () => {1005 const baseState = {1006 y: 3 / 0,1007 z: NaN1008 }1009 const nextState = produce(baseState, draft => {1010 draft.y = 4 / 01011 draft.z = NaN1012 })1013 expect(nextState).toBe(baseState)1014 })985 it("should handle equality correctly - 1", () => {986 const baseState = {987 y: 3 / 0,988 z: NaN989 }990 const nextState = produce(baseState, draft => {991 draft.y = 4 / 0992 draft.z = NaN993 })994 expect(nextState).toBe(baseState)995 })9961016 it("should handle equality correctly - 2", () => {1017 const baseState = {1018 x: -01019 }1020 const nextState = produce(baseState, draft => {1021 draft.x = +01022 })1023 expect(nextState).not.toBe(baseState)1024 expect(nextState).not.toEqual(baseState)1025 })997 it("should handle equality correctly - 2", () => {998 const baseState = {999 x: -01000 }1001 const nextState = produce(baseState, draft => {1002 draft.x = +01003 })1004 expect(nextState).not.toBe(baseState)1005 expect(nextState).not.toEqual(baseState)1006 })10071027 // AKA: recursive produce calls1028 describe("nested producers", () => {1029 describe("when base state is not a draft", () => {1030 // This test ensures the global state used to manage proxies is1031 // never left in a corrupted state by a nested `produce` call.1032 it("never affects its parent producer implicitly", () => {1033 const base = {obj: {a: 1}}1034 const next = produce(base, draft => {1035 // Notice how `base.obj` is passed, not `draft.obj`1036 const obj2 = produce(base.obj, draft2 => {1037 draft2.a = 01038 })1039 expect(obj2.a).toBe(0)1040 expect(draft.obj.a).toBe(1) // effects should not be visible outside1041 })1042 expect(next).toBe(base)1043 })1044 })1008 // AKA: recursive produce calls1009 describe("nested producers", () => {1010 describe("when base state is not a draft", () => {1011 // This test ensures the global state used to manage proxies is1012 // never left in a corrupted state by a nested `produce` call.1013 it("never affects its parent producer implicitly", () => {1014 const base = {obj: {a: 1}}1015 const next = produce(base, draft => {1016 // Notice how `base.obj` is passed, not `draft.obj`1017 const obj2 = produce(base.obj, draft2 => {1018 draft2.a = 01019 })1020 expect(obj2.a).toBe(0)1021 expect(draft.obj.a).toBe(1) // effects should not be visible outside1022 })1023 expect(next).toBe(base)1024 })1025 })10261046 describe("when base state is a draft", () => {1047 it("always wraps the draft in a new draft", () => {1048 produce({}, parent => {1049 produce(parent, child => {1050 expect(child).not.toBe(parent)1051 expect(isDraft(child)).toBeTruthy()1052 expect(original(child)).toBe(parent)1053 })1054 })1055 })1027 describe("when base state is a draft", () => {1028 it("always wraps the draft in a new draft", () => {1029 produce({}, parent => {1030 produce(parent, child => {1031 expect(child).not.toBe(parent)1032 expect(isDraft(child)).toBeTruthy()1033 expect(original(child)).toBe(parent)1034 })1035 })1036 })10371057 // Reported by: https://github.com/mweststrate/immer/issues/3431058 it("ensures each property is drafted", () => {1059 produce({a: {}, b: {}}, parent => {1060 parent.a // Access "a" but not "b"1061 produce(parent, child => {1062 child.c = 11063 expect(isDraft(child.a)).toBeTruthy()1064 expect(isDraft(child.b)).toBeTruthy()1065 })1066 })1067 })1038 // Reported by: https://github.com/mweststrate/immer/issues/3431039 it("ensures each property is drafted", () => {1040 produce({a: {}, b: {}}, parent => {1041 parent.a // Access "a" but not "b"1042 produce(parent, child => {1043 child.c = 11044 expect(isDraft(child.a)).toBeTruthy()1045 expect(isDraft(child.b)).toBeTruthy()1046 })1047 })1048 })10491069 it("preserves any pending changes", () => {1070 produce({a: 1, b: 1, d: 1}, parent => {1071 parent.b = 21072 parent.c = 21073 delete parent.d1074 produce(parent, child => {1075 expect(child.a).toBe(1) // unchanged1076 expect(child.b).toBe(2) // changed1077 expect(child.c).toBe(2) // added1078 expect(child.d).toBeUndefined() // deleted1079 })1080 })1081 })1082 })1050 it("preserves any pending changes", () => {1051 produce({a: 1, b: 1, d: 1}, parent => {1052 parent.b = 21053 parent.c = 21054 delete parent.d1055 produce(parent, child => {1056 expect(child.a).toBe(1) // unchanged1057 expect(child.b).toBe(2) // changed1058 expect(child.c).toBe(2) // added1059 expect(child.d).toBeUndefined() // deleted1060 })1061 })1062 })1063 })10641084 describe("when base state contains a draft", () => {1085 it("wraps unowned draft with its own draft", () => {1086 produce({a: {}}, parent => {1087 produce({a: parent.a}, child => {1088 expect(child.a).not.toBe(parent.a)1089 expect(isDraft(child.a)).toBeTruthy()1090 expect(original(child.a)).toBe(parent.a)1091 })1092 })1093 })1065 describe("when base state contains a draft", () => {1066 it("wraps unowned draft with its own draft", () => {1067 produce({a: {}}, parent => {1068 produce({a: parent.a}, child => {1069 expect(child.a).not.toBe(parent.a)1070 expect(isDraft(child.a)).toBeTruthy()1071 expect(original(child.a)).toBe(parent.a)1072 })1073 })1074 })10751095 it("returns unowned draft if no changes were made", () => {1096 produce({a: {}}, parent => {1097 const result = produce({a: parent.a}, () => {})1098 expect(result.a).toBe(parent.a)1099 })1100 })1076 it("returns unowned draft if no changes were made", () => {1077 produce({a: {}}, parent => {1078 const result = produce({a: parent.a}, () => {})1079 expect(result.a).toBe(parent.a)1080 })1081 })10821102 it("clones the unowned draft when changes are made", () => {1103 produce({a: {}}, parent => {1104 const result = produce({a: parent.a}, child => {1105 child.a.b = 11106 })1107 expect(result.a).not.toBe(parent.a)1108 expect(result.a.b).toBe(1)1109 expect("b" in parent.a).toBeFalsy()1110 })1111 })1083 it("clones the unowned draft when changes are made", () => {1084 produce({a: {}}, parent => {1085 const result = produce({a: parent.a}, child => {1086 child.a.b = 11087 })1088 expect(result.a).not.toBe(parent.a)1089 expect(result.a.b).toBe(1)1090 expect("b" in parent.a).toBeFalsy()1091 })1092 })10931113 // We cannot auto-freeze the result of a nested producer,1114 // because it may contain a draft from a parent producer.1115 it("never auto-freezes the result", () => {1116 produce({a: {}}, parent => {1117 const r = produce({a: parent.a}, child => {1118 child.b = 1 // Ensure a copy is returned.1119 })1120 expect(Object.isFrozen(r)).toBeFalsy()1121 })1122 })1123 })1094 // We cannot auto-freeze the result of a nested producer,1095 // because it may contain a draft from a parent producer.1096 it("never auto-freezes the result", () => {1097 produce({a: {}}, parent => {1098 const r = produce({a: parent.a}, child => {1099 child.b = 1 // Ensure a copy is returned.1100 })1101 expect(Object.isFrozen(r)).toBeFalsy()1102 })1103 })1104 })11051125 // "Upvalues" are variables from a parent scope.1126 it("does not finalize upvalue drafts", () => {1127 produce({a: {}, b: {}}, parent => {1128 expect(produce({}, () => parent)).toBe(parent)1129 parent.x // Ensure proxy not revoked.1106 // "Upvalues" are variables from a parent scope.1107 it("does not finalize upvalue drafts", () => {1108 produce({a: {}, b: {}}, parent => {1109 expect(produce({}, () => parent)).toBe(parent)1110 parent.x // Ensure proxy not revoked.11111131 expect(produce({}, () => [parent])[0]).toBe(parent)1132 parent.x // Ensure proxy not revoked.1112 expect(produce({}, () => [parent])[0]).toBe(parent)1113 parent.x // Ensure proxy not revoked.11141134 expect(produce({}, () => parent.a)).toBe(parent.a)1135 parent.a.x // Ensure proxy not revoked.1115 expect(produce({}, () => parent.a)).toBe(parent.a)1116 parent.a.x // Ensure proxy not revoked.11171137 // Modified parent test1138 parent.c = 11139 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1140 parent.b.x // Ensure proxy not revoked.1141 })1142 })1118 // Modified parent test1119 parent.c = 11120 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1121 parent.b.x // Ensure proxy not revoked.1122 })1123 })11241144 it("works with interweaved Immer instances", () => {1145 const options = {useProxies, autoFreeze}1146 const one = createPatchedImmer(options)1147 const two = createPatchedImmer(options)1125 it("works with interweaved Immer instances", () => {1126 const options = {useProxies, autoFreeze}1127 const one = createPatchedImmer(options)1128 const two = createPatchedImmer(options)11291149 const base = {}1150 const result = one.produce(base, s1 =>1151 two.produce({s1}, s2 => {1152 expect(original(s2.s1)).toBe(s1)1153 s2.n = 11154 s2.s1 = one.produce({s2}, s3 => {1155 expect(original(s3.s2)).toBe(s2)1156 expect(original(s3.s2.s1)).toBe(s2.s1)1157 return s3.s2.s11158 })1159 })1160 )1161 expect(result.n).toBe(1)1162 expect(result.s1).toBe(base)1163 })1164 })1130 const base = {}1131 const result = one.produce(base, s1 =>1132 two.produce({s1}, s2 => {1133 expect(original(s2.s1)).toBe(s1)1134 s2.n = 11135 s2.s1 = one.produce({s2}, s3 => {1136 expect(original(s3.s2)).toBe(s2)1137 expect(original(s3.s2.s1)).toBe(s2.s1)1138 return s3.s2.s11139 })1140 })1141 )1142 expect(result.n).toBe(1)1143 expect(result.s1).toBe(base)1144 })1145 })11461166 if (useProxies)1167 it("throws when Object.setPrototypeOf() is used on a draft", () => {1168 produce({}, draft => {1169 expect(() =>1170 Object.setPrototypeOf(draft, Array)1171 ).toThrowErrorMatchingSnapshot()1172 })1173 })1147 if (useProxies)1148 it("throws when Object.setPrototypeOf() is used on a draft", () => {1149 produce({}, draft => {1150 expect(() =>1151 Object.setPrototypeOf(draft, Array)1152 ).toThrowErrorMatchingSnapshot()1153 })1154 })11551175 it("supports the 'in' operator", () => {1176 produce(baseState, draft => {1177 // Known property1178 expect("anArray" in draft).toBe(true)1179 expect(Reflect.has(draft, "anArray")).toBe(true)1156 it("supports the 'in' operator", () => {1157 produce(baseState, draft => {1158 // Known property1159 expect("anArray" in draft).toBe(true)1160 expect(Reflect.has(draft, "anArray")).toBe(true)11611181 // Unknown property1182 expect("bla" in draft).toBe(false)1183 expect(Reflect.has(draft, "bla")).toBe(false)1162 // Unknown property1163 expect("bla" in draft).toBe(false)1164 expect(Reflect.has(draft, "bla")).toBe(false)11651185 // Known index1186 expect(0 in draft.anArray).toBe(true)1187 expect("0" in draft.anArray).toBe(true)1188 expect(Reflect.has(draft.anArray, 0)).toBe(true)1189 expect(Reflect.has(draft.anArray, "0")).toBe(true)1166 // Known index1167 expect(0 in draft.anArray).toBe(true)1168 expect("0" in draft.anArray).toBe(true)1169 expect(Reflect.has(draft.anArray, 0)).toBe(true)1170 expect(Reflect.has(draft.anArray, "0")).toBe(true)11711191 // Unknown index1192 expect(17 in draft.anArray).toBe(false)1193 expect("17" in draft.anArray).toBe(false)1194 expect(Reflect.has(draft.anArray, 17)).toBe(false)1195 expect(Reflect.has(draft.anArray, "17")).toBe(false)1196 })1197 })1172 // Unknown index1173 expect(17 in draft.anArray).toBe(false)1174 expect("17" in draft.anArray).toBe(false)1175 expect(Reflect.has(draft.anArray, 17)).toBe(false)1176 expect(Reflect.has(draft.anArray, "17")).toBe(false)1177 })1178 })11791199 it("'this' should not be bound anymore - 1", () => {1200 const base = {x: 3}1201 const next1 = produce(base, function() {1202 expect(this).toBe(undefined)1203 })1204 })1180 it("'this' should not be bound anymore - 1", () => {1181 const base = {x: 3}1182 const next1 = produce(base, function() {1183 expect(this).toBe(undefined)1184 })1185 })11861206 it("'this' should not be bound anymore - 2", () => {1207 const incrementor = produce(function() {1208 expect(this).toBe(undefined)1209 })1210 incrementor()1211 })1187 it("'this' should not be bound anymore - 2", () => {1188 const incrementor = produce(function() {1189 expect(this).toBe(undefined)1190 })1191 incrementor()1192 })11931213 it("should be possible to use dynamic bound this", () => {1214 const world = {1215 counter: {count: 1},1216 inc: produce(function(draft) {1217 expect(this).toBe(world)1218 draft.counter.count = this.counter.count + 11219 })1220 }1194 it("should be possible to use dynamic bound this", () => {1195 const world = {1196 counter: {count: 1},1197 inc: produce(function(draft) {1198 expect(this).toBe(world)1199 draft.counter.count = this.counter.count + 11200 })1201 }12021222 expect(world.inc(world).counter.count).toBe(2)1223 })1203 expect(world.inc(world).counter.count).toBe(2)1204 })12051225 // See here: https://github.com/mweststrate/immer/issues/891226 it("supports the spread operator", () => {1227 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1228 const result = produce(base, draft => {1229 draft.foo = {x: 1, ...draft.foo, y: 1}1230 draft.bar = [1, ...draft.bar, 1]1231 })1232 expect(result).toEqual({1233 foo: {x: 0, y: 1},1234 bar: [1, 0, 0, 1]1235 })1236 })1206 // See here: https://github.com/mweststrate/immer/issues/891207 it("supports the spread operator", () => {1208 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1209 const result = produce(base, draft => {1210 draft.foo = {x: 1, ...draft.foo, y: 1}1211 draft.bar = [1, ...draft.bar, 1]1212 })1213 expect(result).toEqual({1214 foo: {x: 0, y: 1},1215 bar: [1, 0, 0, 1]1216 })1217 })12181238 it("processes with lodash.set", () => {1239 const base = [{id: 1, a: 1}]1240 const result = produce(base, draft => {1241 lodash.set(draft, "[0].a", 2)1242 })1243 expect(base[0].a).toEqual(1)1244 expect(result[0].a).toEqual(2)1245 })1219 it("processes with lodash.set", () => {1220 const base = [{id: 1, a: 1}]1221 const result = produce(base, draft => {1222 lodash.set(draft, "[0].a", 2)1223 })1224 expect(base[0].a).toEqual(1)1225 expect(result[0].a).toEqual(2)1226 })12271247 it("processes with lodash.find", () => {1248 const base = [{id: 1, a: 1}]1249 const result = produce(base, draft => {1250 const obj1 = lodash.find(draft, {id: 1})1251 lodash.set(obj1, "a", 2)1252 })1253 expect(base[0].a).toEqual(1)1254 expect(result[0].a).toEqual(2)1255 })1228 it("processes with lodash.find", () => {1229 const base = [{id: 1, a: 1}]1230 const result = produce(base, draft => {1231 const obj1 = lodash.find(draft, {id: 1})1232 lodash.set(obj1, "a", 2)1233 })1234 expect(base[0].a).toEqual(1)1235 expect(result[0].a).toEqual(2)1236 })12371257 describe("recipe functions", () => {1258 it("can return a new object", () => {1259 const base = {x: 3}1260 const res = produce(base, d => {1261 return {x: d.x + 1}1262 })1263 expect(res).not.toBe(base)1264 expect(res).toEqual({x: 4})1265 })1238 describe("recipe functions", () => {1239 it("can return a new object", () => {1240 const base = {x: 3}1241 const res = produce(base, d => {1242 return {x: d.x + 1}1243 })1244 expect(res).not.toBe(base)1245 expect(res).toEqual({x: 4})1246 })12471267 it("can return the draft", () => {1268 const base = {x: 3}1269 const res = produce(base, d => {1270 d.x = 41271 return d1272 })1273 expect(res).not.toBe(base)1274 expect(res).toEqual({x: 4})1275 })1248 it("can return the draft", () => {1249 const base = {x: 3}1250 const res = produce(base, d => {1251 d.x = 41252 return d1253 })1254 expect(res).not.toBe(base)1255 expect(res).toEqual({x: 4})1256 })12571277 it("can return an unmodified child draft", () => {1278 const base = {a: {}}1279 const res = produce(base, d => {1280 return d.a1281 })1282 expect(res).toBe(base.a)1283 })1258 it("can return an unmodified child draft", () => {1259 const base = {a: {}}1260 const res = produce(base, d => {1261 return d.a1262 })1263 expect(res).toBe(base.a)1264 })12651285 // TODO: Avoid throwing if only the child draft was modified.1286 it("cannot return a modified child draft", () => {1287 const base = {a: {}}1288 expect(() => {1289 produce(base, d => {1290 d.a.b = 11291 return d.a1292 })1293 }).toThrowErrorMatchingSnapshot()1294 })1266 // TODO: Avoid throwing if only the child draft was modified.1267 it("cannot return a modified child draft", () => {1268 const base = {a: {}}1269 expect(() => {1270 produce(base, d => {1271 d.a.b = 11272 return d.a1273 })1274 }).toThrowErrorMatchingSnapshot()1275 })12761296 it("can return a frozen object", () => {1297 const res = deepFreeze([{x: 3}])1298 expect(produce({}, () => res)).toBe(res)1299 })1277 it("can return a frozen object", () => {1278 const res = deepFreeze([{x: 3}])1279 expect(produce({}, () => res)).toBe(res)1280 })12811301 it("can return an object with two references to another object", () => {1302 const next = produce({}, d => {1303 const obj = {}1304 return {obj, arr: [obj]}1305 })1306 expect(next.obj).toBe(next.arr[0])1307 })1282 it("can return an object with two references to another object", () => {1283 const next = produce({}, d => {1284 const obj = {}1285 return {obj, arr: [obj]}1286 })1287 expect(next.obj).toBe(next.arr[0])1288 })12891309 it("can return an object with two references to an unmodified draft", () => {1310 const base = {a: {}}1311 const next = produce(base, d => {1312 return [d.a, d.a]1313 })1314 expect(next[0]).toBe(base.a)1315 expect(next[0]).toBe(next[1])1316 })1290 it("can return an object with two references to an unmodified draft", () => {1291 const base = {a: {}}1292 const next = produce(base, d => {1293 return [d.a, d.a]1294 })1295 expect(next[0]).toBe(base.a)1296 expect(next[0]).toBe(next[1])1297 })12981318 it("cannot return an object that references itself", () => {1319 const res = {}1320 res.self = res1321 expect(() => {1322 produce(res, () => res.self)1323 }).toThrowErrorMatchingSnapshot()1324 })1325 })1299 it("cannot return an object that references itself", () => {1300 const res = {}1301 res.self = res1302 expect(() => {1303 produce(res, () => res.self)1304 }).toThrowErrorMatchingSnapshot()1305 })1306 })13071327 describe("async recipe function", () => {1328 it("can modify the draft", () => {1329 const base = {a: 0, b: 0}1330 return produce(base, async d => {1331 d.a = 11332 await Promise.resolve()1333 d.b = 11334 }).then(res => {1335 expect(res).not.toBe(base)1336 expect(res).toEqual({a: 1, b: 1})1337 })1338 })1308 describe("async recipe function", () => {1309 it("can modify the draft", () => {1310 const base = {a: 0, b: 0}1311 return produce(base, async d => {1312 d.a = 11313 await Promise.resolve()1314 d.b = 11315 }).then(res => {1316 expect(res).not.toBe(base)1317 expect(res).toEqual({a: 1, b: 1})1318 })1319 })13201340 it("works with rejected promises", () => {1341 let draft1342 const base = {a: 0, b: 0}1343 const err = new Error("passed")1344 return produce(base, d => {1345 draft = d1346 draft.b = 11347 return Promise.reject(err)1348 }).then(1349 () => {1350 throw "failed"1351 },1352 e => {1353 expect(e).toBe(err)1354 expect(() => draft.a).toThrowErrorMatchingSnapshot()1355 }1356 )1357 })1321 it("works with rejected promises", () => {1322 let draft1323 const base = {a: 0, b: 0}1324 const err = new Error("passed")1325 return produce(base, d => {1326 draft = d1327 draft.b = 11328 return Promise.reject(err)1329 }).then(1330 () => {1331 throw "failed"1332 },1333 e => {1334 expect(e).toBe(err)1335 expect(() => draft.a).toThrowErrorMatchingSnapshot()1336 }1337 )1338 })13391359 it("supports recursive produce calls after await", () => {1360 const base = {obj: {k: 1}}1361 return produce(base, d => {1362 const obj = d.obj1363 delete d.obj1364 return Promise.resolve().then(() => {1365 d.a = produce({}, d => {1366 d.b = obj // Assign a draft owned by the parent scope.1367 })1340 it("supports recursive produce calls after await", () => {1341 const base = {obj: {k: 1}}1342 return produce(base, d => {1343 const obj = d.obj1344 delete d.obj1345 return Promise.resolve().then(() => {1346 d.a = produce({}, d => {1347 d.b = obj // Assign a draft owned by the parent scope.1348 })13491369 // Auto-freezing is prevented when an unowned draft exists.1370 expect(Object.isFrozen(d.a)).toBeFalsy()1350 // Auto-freezing is prevented when an unowned draft exists.1351 expect(Object.isFrozen(d.a)).toBeFalsy()13521372 // Ensure `obj` is not revoked.1373 obj.c = 11374 })1375 }).then(res => {1376 expect(res).not.toBe(base)1377 expect(res).toEqual({1378 a: {b: {k: 1, c: 1}}1379 })1380 })1381 })1382 })1353 // Ensure `obj` is not revoked.1354 obj.c = 11355 })1356 }).then(res => {1357 expect(res).not.toBe(base)1358 expect(res).toEqual({1359 a: {b: {k: 1, c: 1}}1360 })1361 })1362 })1363 })13641384 it("throws when the draft is modified and another object is returned", () => {1385 const base = {x: 3}1386 expect(() => {1387 produce(base, draft => {1388 draft.x = 41389 return {x: 5}1390 })1391 }).toThrowErrorMatchingSnapshot()1392 })1365 it("throws when the draft is modified and another object is returned", () => {1366 const base = {x: 3}1367 expect(() => {1368 produce(base, draft => {1369 draft.x = 41370 return {x: 5}1371 })1372 }).toThrowErrorMatchingSnapshot()1373 })13741394 it("should fix #117 - 1", () => {1395 const reducer = (state, action) =>1396 produce(state, draft => {1397 switch (action.type) {1398 case "SET_STARTING_DOTS":1399 return draft.availableStartingDots.map(a => a)1400 default:1401 break1402 }1403 })1404 const base = {1405 availableStartingDots: [1406 {dots: 4, count: 1},1407 {dots: 3, count: 2},1408 {dots: 2, count: 3},1409 {dots: 1, count: 4}1410 ]1411 }1412 const next = reducer(base, {type: "SET_STARTING_DOTS"})1413 expect(next).toEqual(base.availableStartingDots)1414 expect(next).not.toBe(base.availableStartingDots)1415 })1375 it("should fix #117 - 1", () => {1376 const reducer = (state, action) =>1377 produce(state, draft => {1378 switch (action.type) {1379 case "SET_STARTING_DOTS":1380 return draft.availableStartingDots.map(a => a)1381 default:1382 break1383 }1384 })1385 const base = {1386 availableStartingDots: [1387 {dots: 4, count: 1},1388 {dots: 3, count: 2},1389 {dots: 2, count: 3},1390 {dots: 1, count: 4}1391 ]1392 }1393 const next = reducer(base, {type: "SET_STARTING_DOTS"})1394 expect(next).toEqual(base.availableStartingDots)1395 expect(next).not.toBe(base.availableStartingDots)1396 })13971417 it("should fix #117 - 2", () => {1418 const reducer = (state, action) =>1419 produce(state, draft => {1420 switch (action.type) {1421 case "SET_STARTING_DOTS":1422 return {1423 dots: draft.availableStartingDots.map(a => a)1424 }1425 default:1426 break1427 }1428 })1429 const base = {1430 availableStartingDots: [1431 {dots: 4, count: 1},1432 {dots: 3, count: 2},1433 {dots: 2, count: 3},1434 {dots: 1, count: 4}1435 ]1436 }1437 const next = reducer(base, {type: "SET_STARTING_DOTS"})1438 expect(next).toEqual({dots: base.availableStartingDots})1439 })1398 it("should fix #117 - 2", () => {1399 const reducer = (state, action) =>1400 produce(state, draft => {1401 switch (action.type) {1402 case "SET_STARTING_DOTS":1403 return {1404 dots: draft.availableStartingDots.map(a => a)1405 }1406 default:1407 break1408 }1409 })1410 const base = {1411 availableStartingDots: [1412 {dots: 4, count: 1},1413 {dots: 3, count: 2},1414 {dots: 2, count: 3},1415 {dots: 1, count: 4}1416 ]1417 }1418 const next = reducer(base, {type: "SET_STARTING_DOTS"})1419 expect(next).toEqual({dots: base.availableStartingDots})1420 })14211441 it("cannot always detect noop assignments - 0", () => {1442 const baseState = {x: {y: 3}}1443 const nextState = produce(baseState, d => {1444 const a = d.x1445 d.x = a1446 })1447 expect(nextState).toBe(baseState)1448 })1422 it("cannot always detect noop assignments - 0", () => {1423 const baseState = {x: {y: 3}}1424 const nextState = produce(baseState, d => {1425 const a = d.x1426 d.x = a1427 })1428 expect(nextState).toBe(baseState)1429 })14301450 it("cannot always detect noop assignments - 1", () => {1451 const baseState = {x: {y: 3}}1452 const nextState = produce(baseState, d => {1453 const a = d.x1454 d.x = 41455 d.x = a1456 })1457 // Ideally, this should actually be the same instances1458 // but this would be pretty expensive to detect,1459 // so we don't atm1460 expect(nextState).not.toBe(baseState)1461 })1431 it("cannot always detect noop assignments - 1", () => {1432 const baseState = {x: {y: 3}}1433 const nextState = produce(baseState, d => {1434 const a = d.x1435 d.x = 41436 d.x = a1437 })1438 // Ideally, this should actually be the same instances1439 // but this would be pretty expensive to detect,1440 // so we don't atm1441 expect(nextState).not.toBe(baseState)1442 })14431463 it("cannot always detect noop assignments - 2", () => {1464 const baseState = {x: {y: 3}}1465 const nextState = produce(baseState, d => {1466 const a = d.x1467 const stuff = a.y + 31468 d.x = 41469 d.x = a1470 })1471 // Ideally, this should actually be the same instances1472 // but this would be pretty expensive to detect,1473 // so we don't atm1474 expect(nextState).not.toBe(baseState)1475 })1444 it("cannot always detect noop assignments - 2", () => {1445 const baseState = {x: {y: 3}}1446 const nextState = produce(baseState, d => {1447 const a = d.x1448 const stuff = a.y + 31449 d.x = 41450 d.x = a1451 })1452 // Ideally, this should actually be the same instances1453 // but this would be pretty expensive to detect,1454 // so we don't atm1455 expect(nextState).not.toBe(baseState)1456 })14571477 it("cannot always detect noop assignments - 3", () => {1478 const baseState = {x: 3}1479 const nextState = produce(baseState, d => {1480 d.x = 31481 })1482 expect(nextState).toBe(baseState)1483 })1458 it("cannot always detect noop assignments - 3", () => {1459 const baseState = {x: 3}1460 const nextState = produce(baseState, d => {1461 d.x = 31462 })1463 expect(nextState).toBe(baseState)1464 })14651485 it("cannot always detect noop assignments - 4", () => {1486 const baseState = {x: 3}1487 const nextState = produce(baseState, d => {1488 d.x = 41489 d.x = 31490 })1491 // Ideally, this should actually be the same instances1492 // but this would be pretty expensive to detect,1493 // so we don't atm1494 expect(nextState).not.toBe(baseState)1495 })1466 it("cannot always detect noop assignments - 4", () => {1467 const baseState = {x: 3}1468 const nextState = produce(baseState, d => {1469 d.x = 41470 d.x = 31471 })1472 // Ideally, this should actually be the same instances1473 // but this would be pretty expensive to detect,1474 // so we don't atm1475 expect(nextState).not.toBe(baseState)1476 })14771497 it("cannot produce undefined by returning undefined", () => {1498 const base = 31499 expect(produce(base, () => 4)).toBe(4)1500 expect(produce(base, () => null)).toBe(null)1501 expect(produce(base, () => undefined)).toBe(3)1502 expect(produce(base, () => {})).toBe(3)1503 expect(produce(base, () => nothing)).toBe(undefined)1478 it("cannot produce undefined by returning undefined", () => {1479 const base = 31480 expect(produce(base, () => 4)).toBe(4)1481 expect(produce(base, () => null)).toBe(null)1482 expect(produce(base, () => undefined)).toBe(3)1483 expect(produce(base, () => {})).toBe(3)1484 expect(produce(base, () => nothing)).toBe(undefined)14851505 expect(produce({}, () => undefined)).toEqual({})1506 expect(produce({}, () => nothing)).toBe(undefined)1507 expect(produce(3, () => nothing)).toBe(undefined)1486 expect(produce({}, () => undefined)).toEqual({})1487 expect(produce({}, () => nothing)).toBe(undefined)1488 expect(produce(3, () => nothing)).toBe(undefined)14891509 expect(produce(() => undefined)({})).toEqual({})1510 expect(produce(() => nothing)({})).toBe(undefined)1511 expect(produce(() => nothing)(3)).toBe(undefined)1512 })1490 expect(produce(() => undefined)({})).toEqual({})1491 expect(produce(() => nothing)({})).toBe(undefined)1492 expect(produce(() => nothing)(3)).toBe(undefined)1493 })14941514 describe("base state type", () => {1515 testObjectTypes(produce)1516 testLiteralTypes(produce)1517 })1495 describe("base state type", () => {1496 testObjectTypes(produce)1497 testLiteralTypes(produce)1498 })14991519 afterEach(() => {1520 expect(baseState).toBe(origBaseState)1521 expect(baseState).toEqual(createBaseState())1522 })1500 afterEach(() => {1501 expect(baseState).toBe(origBaseState)1502 expect(baseState).toEqual(createBaseState())1503 })15041524 class Foo {}1525 function createBaseState() {1526 const data = {1527 anInstance: new Foo(),1528 anArray: [3, 2, {c: 3}, 1],1529 aMap: new Map([1530 ["jedi", {name: "Luke", skill: 10}],1531 ["jediTotal", 42],1532 ["force", "these aren't the droids you're looking for"]1533 ]),1534 aSet: new Set([1535 "Luke",1536 42,1537 {1538 jedi: "Yoda"1539 }1540 ]),1541 aProp: "hi",1542 anObject: {1543 nested: {1544 yummie: true1545 },1546 coffee: false1547 }1548 }1549 return autoFreeze ? deepFreeze(data) : data1550 }1551 })1505 class Foo {}1506 function createBaseState() {1507 const data = {1508 anInstance: new Foo(),1509 anArray: [3, 2, {c: 3}, 1],1510 aMap: new Map([1511 ["jedi", {name: "Luke", skill: 10}],1512 ["jediTotal", 42],1513 ["force", "these aren't the droids you're looking for"]1514 ]),1515 aSet: new Set([1516 "Luke",1517 42,1518 {1519 jedi: "Yoda"1520 }1521 ]),1522 aProp: "hi",1523 anObject: {1524 nested: {1525 yummie: true1526 },1527 coffee: false1528 }1529 }1530 return autoFreeze ? deepFreeze(data) : data1531 }1532 })15331553 describe(`isDraft - ${name}`, () => {1554 it("returns true for object drafts", () => {1555 produce({}, state => {1556 expect(isDraft(state)).toBeTruthy()1557 })1558 })1559 it("returns true for array drafts", () => {1560 produce([], state => {1561 expect(isDraft(state)).toBeTruthy()1562 })1563 })1564 it("returns true for objects nested in object drafts", () => {1565 produce({a: {b: {}}}, state => {1566 expect(isDraft(state.a)).toBeTruthy()1567 expect(isDraft(state.a.b)).toBeTruthy()1568 })1569 })1570 it("returns false for new objects added to a draft", () => {1571 produce({}, state => {1572 state.a = {}1573 expect(isDraft(state.a)).toBeFalsy()1574 })1575 })1576 it("returns false for objects returned by the producer", () => {1577 const object = produce(null, Object.create)1578 expect(isDraft(object)).toBeFalsy()1579 })1580 it("returns false for arrays returned by the producer", () => {1581 const array = produce(null, _ => [])1582 expect(isDraft(array)).toBeFalsy()1583 })1584 it("returns false for object drafts returned by the producer", () => {1585 const object = produce({}, state => state)1586 expect(isDraft(object)).toBeFalsy()1587 })1588 it("returns false for array drafts returned by the producer", () => {1589 const array = produce([], state => state)1590 expect(isDraft(array)).toBeFalsy()1591 })1592 })1534 describe(`isDraft - ${name}`, () => {1535 it("returns true for object drafts", () => {1536 produce({}, state => {1537 expect(isDraft(state)).toBeTruthy()1538 })1539 })1540 it("returns true for array drafts", () => {1541 produce([], state => {1542 expect(isDraft(state)).toBeTruthy()1543 })1544 })1545 it("returns true for objects nested in object drafts", () => {1546 produce({a: {b: {}}}, state => {1547 expect(isDraft(state.a)).toBeTruthy()1548 expect(isDraft(state.a.b)).toBeTruthy()1549 })1550 })1551 it("returns false for new objects added to a draft", () => {1552 produce({}, state => {1553 state.a = {}1554 expect(isDraft(state.a)).toBeFalsy()1555 })1556 })1557 it("returns false for objects returned by the producer", () => {1558 const object = produce(null, Object.create)1559 expect(isDraft(object)).toBeFalsy()1560 })1561 it("returns false for arrays returned by the producer", () => {1562 const array = produce(null, _ => [])1563 expect(isDraft(array)).toBeFalsy()1564 })1565 it("returns false for object drafts returned by the producer", () => {1566 const object = produce({}, state => state)1567 expect(isDraft(object)).toBeFalsy()1568 })1569 it("returns false for array drafts returned by the producer", () => {1570 const array = produce([], state => state)1571 expect(isDraft(array)).toBeFalsy()1572 })1573 })1574}15751576function testObjectTypes(produce) {1596 class Foo {1597 constructor(foo) {1598 this.foo = foo1599 this[immerable] = true1600 }1601 }1602 const values = {1603 "empty object": {},1604 "plain object": {a: 1, b: 2},1605 "object (no prototype)": Object.create(null),1606 "empty array": [],1607 "plain array": [1, 2],1608 "class instance (draftable)": new Foo(1)1609 }1610 for (const name in values) {1611 const value = values[name]1612 const copy = shallowCopy(value)1613 testObjectType(name, value)1614 testObjectType(name + " (frozen)", Object.freeze(copy))1615 }1616 function testObjectType(name, base) {1617 describe(name, () => {1618 it("creates a draft", () => {1619 produce(base, draft => {1620 expect(draft).not.toBe(base)1621 expect(shallowCopy(draft, true)).toEqual(base)1622 })1623 })1577 class Foo {1578 constructor(foo) {1579 this.foo = foo1580 this[immerable] = true1581 }1582 }1583 const values = {1584 "empty object": {},1585 "plain object": {a: 1, b: 2},1586 "object (no prototype)": Object.create(null),1587 "empty array": [],1588 "plain array": [1, 2],1589 "class instance (draftable)": new Foo(1)1590 }1591 for (const name in values) {1592 const value = values[name]1593 const copy = shallowCopy(value)1594 testObjectType(name, value)1595 testObjectType(name + " (frozen)", Object.freeze(copy))1596 }1597 function testObjectType(name, base) {1598 describe(name, () => {1599 it("creates a draft", () => {1600 produce(base, draft => {1601 expect(draft).not.toBe(base)1602 expect(shallowCopy(draft, true)).toEqual(base)1603 })1604 })16051625 it("preserves the prototype", () => {1626 const proto = Object.getPrototypeOf(base)1627 produce(base, draft => {1628 expect(Object.getPrototypeOf(draft)).toBe(proto)1629 })1630 })1606 it("preserves the prototype", () => {1607 const proto = Object.getPrototypeOf(base)1608 produce(base, draft => {1609 expect(Object.getPrototypeOf(draft)).toBe(proto)1610 })1611 })16121632 it("returns the base state when no changes are made", () => {1633 expect(produce(base, () => {})).toBe(base)1634 })1613 it("returns the base state when no changes are made", () => {1614 expect(produce(base, () => {})).toBe(base)1615 })16161636 it("returns a copy when changes are made", () => {1637 const random = Math.random()1638 const result = produce(base, draft => {1639 draft[0] = random1640 })1641 expect(result).not.toBe(base)1642 expect(result.constructor).toBe(base.constructor)1643 expect(result[0]).toBe(random)1644 })1645 })1646 }1617 it("returns a copy when changes are made", () => {1618 const random = Math.random()1619 const result = produce(base, draft => {1620 draft[0] = random1621 })1622 expect(result).not.toBe(base)1623 expect(result.constructor).toBe(base.constructor)1624 expect(result[0]).toBe(random)1625 })1626 })1627 }1628}16291630function testLiteralTypes(produce) {1650 class Foo {}1651 const values = {1652 "falsy number": 0,1653 "truthy number": 1,1654 "negative number": -1,1655 NaN: NaN,1656 infinity: 1 / 0,1657 true: true,1658 false: false,1659 "empty string": "",1660 "truthy string": "1",1661 null: null,1662 undefined: undefined,1631 class Foo {}1632 const values = {1633 "falsy number": 0,1634 "truthy number": 1,1635 "negative number": -1,1636 NaN: NaN,1637 infinity: 1 / 0,1638 true: true,1639 false: false,1640 "empty string": "",1641 "truthy string": "1",1642 null: null,1643 undefined: undefined,16441664 /**1665 * These objects are treated as literals because Immer1666 * does not know how to draft them.1667 */1668 function: () => {},1669 "regexp object": /.+/g,1670 "boxed number": new Number(0),1671 "boxed string": new String(""),1672 "boxed boolean": new Boolean(),1673 "date object": new Date(),1674 "class instance (not draftable)": new Foo()1675 }1676 for (const name in values) {1677 describe(name, () => {1678 const value = values[name]1645 /**1646 * These objects are treated as literals because Immer1647 * does not know how to draft them.1648 */1649 function: () => {},1650 "regexp object": /.+/g,1651 "boxed number": new Number(0),1652 "boxed string": new String(""),1653 "boxed boolean": new Boolean(),1654 "date object": new Date(),1655 "class instance (not draftable)": new Foo()1656 }1657 for (const name in values) {1658 describe(name, () => {1659 const value = values[name]16601680 it("does not create a draft", () => {1681 produce(value, draft => {1682 expect(draft).toBe(value)1683 })1684 })1661 it("does not create a draft", () => {1662 produce(value, draft => {1663 expect(draft).toBe(value)1664 })1665 })16661686 it("returns the base state when no changes are made", () => {1687 expect(produce(value, () => {})).toBe(value)1688 })1667 it("returns the base state when no changes are made", () => {1668 expect(produce(value, () => {})).toBe(value)1669 })16701690 if (value && typeof value == "object") {1691 it("does not return a copy when changes are made", () => {1692 expect(1693 produce(value, draft => {1694 draft.foo = true1695 })1696 ).toBe(value)1697 })1698 }1699 })1700 }1671 if (value && typeof value == "object") {1672 it("does not return a copy when changes are made", () => {1673 expect(1674 produce(value, draft => {1675 draft.foo = true1676 })1677 ).toBe(value)1678 })1679 }1680 })1681 }1682}16831684function enumerableOnly(x) {1704 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1705 each(copy, (prop, value) => {1706 if (value && typeof value === "object") {1707 copy[prop] = enumerableOnly(value)1708 }1709 })1710 return copy1685 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1686 each(copy, (prop, value) => {1687 if (value && typeof value === "object") {1688 copy[prop] = enumerableOnly(value)1689 }1690 })1691 return copy1692}
modified:__tests__/curry.js+54 added-60 removed
modified:__tests__/frozen.js+111 added-111 removed
5 unmodified lines
6runTests("proxy", true)7runTests("es5", false)89function runTests(name, useProxies) {10 describe("auto freeze - " + name, () => {11 setUseProxies(useProxies)12 setAutoFreeze(true)10 describe("auto freeze - " + name, () => {11 setUseProxies(useProxies)12 setAutoFreeze(true)1314 it("never freezes the base state", () => {15 const base = {arr: [1], obj: {a: 1}}16 const next = produce(base, draft => {17 draft.arr.push(1)18 })19 expect(isFrozen(base)).toBeFalsy()20 expect(isFrozen(base.arr)).toBeFalsy()21 expect(isFrozen(next)).toBeTruthy()22 expect(isFrozen(next.arr)).toBeTruthy()23 })14 it("never freezes the base state", () => {15 const base = {arr: [1], obj: {a: 1}}16 const next = produce(base, draft => {17 draft.arr.push(1)18 })19 expect(isFrozen(base)).toBeFalsy()20 expect(isFrozen(base.arr)).toBeFalsy()21 expect(isFrozen(next)).toBeTruthy()22 expect(isFrozen(next.arr)).toBeTruthy()23 })2425 it("never freezes reused state", () => {26 const base = {arr: [1], obj: {a: 1}}27 const next = produce(base, draft => {28 draft.arr.push(1)29 })30 expect(next.obj).toBe(base.obj)31 expect(isFrozen(next.obj)).toBeFalsy()32 })25 it("never freezes reused state", () => {26 const base = {arr: [1], obj: {a: 1}}27 const next = produce(base, draft => {28 draft.arr.push(1)29 })30 expect(next.obj).toBe(base.obj)31 expect(isFrozen(next.obj)).toBeFalsy()32 })3334 describe("the result is always auto-frozen when", () => {35 it("the root draft is mutated (and no error is thrown)", () => {36 const base = {}37 const next = produce(base, draft => {38 draft.a = 139 })40 expect(next).not.toBe(base)41 expect(isFrozen(next)).toBeTruthy()42 })34 describe("the result is always auto-frozen when", () => {35 it("the root draft is mutated (and no error is thrown)", () => {36 const base = {}37 const next = produce(base, draft => {38 draft.a = 139 })40 expect(next).not.toBe(base)41 expect(isFrozen(next)).toBeTruthy()42 })4344 it("a nested draft is mutated (and no error is thrown)", () => {45 const base = {a: {}}46 const next = produce(base, draft => {47 draft.a.b = 148 })49 expect(next).not.toBe(base)50 expect(isFrozen(next)).toBeTruthy()51 expect(isFrozen(next.a)).toBeTruthy()52 })53 })44 it("a nested draft is mutated (and no error is thrown)", () => {45 const base = {a: {}}46 const next = produce(base, draft => {47 draft.a.b = 148 })49 expect(next).not.toBe(base)50 expect(isFrozen(next)).toBeTruthy()51 expect(isFrozen(next.a)).toBeTruthy()52 })53 })5455 describe("the result is never auto-frozen when", () => {56 it("the producer is a no-op", () => {57 const base = {}58 const next = produce(base, () => {})59 expect(next).toBe(base)60 expect(isFrozen(next)).toBeFalsy()61 })55 describe("the result is never auto-frozen when", () => {56 it("the producer is a no-op", () => {57 const base = {}58 const next = produce(base, () => {})59 expect(next).toBe(base)60 expect(isFrozen(next)).toBeFalsy()61 })6263 it("the root draft is returned", () => {64 const base = {}65 const next = produce(base, draft => draft)66 expect(next).toBe(base)67 expect(isFrozen(next)).toBeFalsy()68 })63 it("the root draft is returned", () => {64 const base = {}65 const next = produce(base, draft => draft)66 expect(next).toBe(base)67 expect(isFrozen(next)).toBeFalsy()68 })6970 it("a nested draft is returned", () => {71 const base = {a: {}}72 const next = produce(base, draft => draft.a)73 expect(next).toBe(base.a)74 expect(isFrozen(next)).toBeFalsy()75 })70 it("a nested draft is returned", () => {71 const base = {a: {}}72 const next = produce(base, draft => draft.a)73 expect(next).toBe(base.a)74 expect(isFrozen(next)).toBeFalsy()75 })7677 it("the base state is returned", () => {78 const base = {}79 const next = produce(base, () => base)80 expect(next).toBe(base)81 expect(isFrozen(next)).toBeFalsy()82 })77 it("the base state is returned", () => {78 const base = {}79 const next = produce(base, () => base)80 expect(next).toBe(base)81 expect(isFrozen(next)).toBeFalsy()82 })8384 it("a new object replaces a primitive base", () => {85 const obj = {}86 const next = produce(null, () => obj)87 expect(next).toBe(obj)88 expect(isFrozen(next)).toBeFalsy()89 })84 it("a new object replaces a primitive base", () => {85 const obj = {}86 const next = produce(null, () => obj)87 expect(next).toBe(obj)88 expect(isFrozen(next)).toBeFalsy()89 })9091 it("a new object replaces the entire draft", () => {92 const obj = {a: {b: {}}}93 const next = produce({}, () => obj)94 expect(next).toBe(obj)95 expect(isFrozen(next)).toBeFalsy()96 expect(isFrozen(next.a)).toBeFalsy()97 expect(isFrozen(next.a.b)).toBeFalsy()98 })91 it("a new object replaces the entire draft", () => {92 const obj = {a: {b: {}}}93 const next = produce({}, () => obj)94 expect(next).toBe(obj)95 expect(isFrozen(next)).toBeFalsy()96 expect(isFrozen(next.a)).toBeFalsy()97 expect(isFrozen(next.a.b)).toBeFalsy()98 })99100 it("a new object is added to the root draft", () => {101 const base = {}102 const next = produce(base, draft => {103 draft.a = {}104 })105 expect(next).not.toBe(base)106 expect(isFrozen(next)).toBeTruthy()107 expect(isFrozen(next.a)).toBeFalsy()108 })100 it("a new object is added to the root draft", () => {101 const base = {}102 const next = produce(base, draft => {103 draft.a = {}104 })105 expect(next).not.toBe(base)106 expect(isFrozen(next)).toBeTruthy()107 expect(isFrozen(next.a)).toBeFalsy()108 })109110 it("a new object is added to a nested draft", () => {111 const base = {a: {}}112 const next = produce(base, draft => {113 draft.a.b = {}114 })115 expect(next).not.toBe(base)116 expect(isFrozen(next)).toBeTruthy()117 expect(isFrozen(next.a)).toBeTruthy()118 expect(isFrozen(next.a.b)).toBeFalsy()119 })120 })110 it("a new object is added to a nested draft", () => {111 const base = {a: {}}112 const next = produce(base, draft => {113 draft.a.b = {}114 })115 expect(next).not.toBe(base)116 expect(isFrozen(next)).toBeTruthy()117 expect(isFrozen(next.a)).toBeTruthy()118 expect(isFrozen(next.a.b)).toBeFalsy()119 })120 })121122 it("can handle already frozen trees", () => {123 const a = []124 const b = {a: a}125 Object.freeze(a)126 Object.freeze(b)127 const n = produce(b, draft => {128 draft.c = true129 draft.a.push(3)130 })131 expect(n).toEqual({c: true, a: [3]})132 })133 })122 it("can handle already frozen trees", () => {123 const a = []124 const b = {a: a}125 Object.freeze(a)126 Object.freeze(b)127 const n = produce(b, draft => {128 draft.c = true129 draft.a.push(3)130 })131 expect(n).toEqual({c: true, a: [3]})132 })133 })134}
modified:__tests__/hooks.js+323 added-331 removed
5 unmodified lines
6describe("hooks (proxy) -", () => createHookTests(true))7describe("hooks (es5) -", () => createHookTests(false))89function createHookTests(useProxies) {10 let produce, onAssign, onDelete, onCopy10 let produce, onAssign, onDelete, onCopy1112 beforeEach(() => {13 ;({produce, onAssign, onDelete, onCopy} = new Immer({14 autoFreeze: true,15 useProxies,16 onAssign: jest.fn().mockName("onAssign"),17 onDelete: jest.fn().mockName("onDelete"),18 onCopy: jest.fn().mockName("onCopy")19 }))20 })12 beforeEach(() => {13 ;({produce, onAssign, onDelete, onCopy} = new Immer({14 autoFreeze: true,15 useProxies,16 onAssign: jest.fn().mockName("onAssign"),17 onDelete: jest.fn().mockName("onDelete"),18 onCopy: jest.fn().mockName("onCopy")19 }))20 })2122 describe("onAssign()", () => {23 useSharedTests(() => onAssign)24 describe("when draft is an object", () => {25 test("assign", () => {26 produce({a: 0, b: 0, c: 0}, s => {27 s.a++28 s.c++29 })30 expectCalls(onAssign)31 })32 test("assign (no change)", () => {33 produce({a: 0}, s => {34 s.a = 035 })36 expect(onAssign).not.toBeCalled()37 })38 test("delete", () => {39 produce({a: 1}, s => {40 delete s.a41 })42 expect(onAssign).not.toBeCalled()43 })44 test("nested assignments", () => {45 produce({a: {b: {c: 1, d: 1, e: 1}}}, s => {46 const {b} = s.a47 b.c = 248 delete b.d49 b.e = 1 // no-op50 })51 expectCalls(onAssign)52 })53 })54 describe("when draft is an array", () => {55 test("assign", () => {56 produce([1], s => {57 s[0] = 058 })59 expectCalls(onAssign)60 })61 test("push", () => {62 produce([], s => {63 s.push(4)64 })65 expectCalls(onAssign)66 })67 test("pop", () => {68 produce([1], s => {69 s.pop()70 })71 expect(onAssign).not.toBeCalled()72 })73 test("unshift", () => {74 produce([1], s => {75 s.unshift(0)76 })77 expectCalls(onAssign)78 })79 test("length = 0", () => {80 produce([1], s => {81 s.length = 082 })83 expect(onAssign).not.toBeCalled()84 })85 test("splice (length += 1)", () => {86 produce([1, 2, 3], s => {87 s.splice(1, 1, 0, 0)88 })89 expectCalls(onAssign)90 })91 test("splice (length += 0)", () => {92 produce([1, 2, 3], s => {93 s.splice(1, 1, 0)94 })95 expectCalls(onAssign)96 })97 test("splice (length -= 1)", () => {98 produce([1, 2, 3], s => {99 s.splice(0, 2, 6)100 })101 expectCalls(onAssign)102 })103 })104 describe("when a draft is moved into a new object", () => {105 it("is called in the right order", () => {106 const calls = []107 onAssign.mockImplementation((_, prop) => {108 calls.push(prop)109 })110 produce({a: {b: 1, c: {}}}, s => {111 s.a.b = 0112 s.a.c.d = 1113 s.x = {y: {z: s.a}}114 delete s.a115 })116 // Sibling properties use enumeration order, which means new117 // properties come last among their siblings. The deepest118 // properties always come first in their ancestor chain.119 expect(calls).toEqual(["b", "d", "c", "x"])120 })121 })22 describe("onAssign()", () => {23 useSharedTests(() => onAssign)24 describe("when draft is an object", () => {25 test("assign", () => {26 produce({a: 0, b: 0, c: 0}, s => {27 s.a++28 s.c++29 })30 expectCalls(onAssign)31 })32 test("assign (no change)", () => {33 produce({a: 0}, s => {34 s.a = 035 })36 expect(onAssign).not.toBeCalled()37 })38 test("delete", () => {39 produce({a: 1}, s => {40 delete s.a41 })42 expect(onAssign).not.toBeCalled()43 })44 test("nested assignments", () => {45 produce({a: {b: {c: 1, d: 1, e: 1}}}, s => {46 const {b} = s.a47 b.c = 248 delete b.d49 b.e = 1 // no-op50 })51 expectCalls(onAssign)52 })53 })54 describe("when draft is an array", () => {55 test("assign", () => {56 produce([1], s => {57 s[0] = 058 })59 expectCalls(onAssign)60 })61 test("push", () => {62 produce([], s => {63 s.push(4)64 })65 expectCalls(onAssign)66 })67 test("pop", () => {68 produce([1], s => {69 s.pop()70 })71 expect(onAssign).not.toBeCalled()72 })73 test("unshift", () => {74 produce([1], s => {75 s.unshift(0)76 })77 expectCalls(onAssign)78 })79 test("length = 0", () => {80 produce([1], s => {81 s.length = 082 })83 expect(onAssign).not.toBeCalled()84 })85 test("splice (length += 1)", () => {86 produce([1, 2, 3], s => {87 s.splice(1, 1, 0, 0)88 })89 expectCalls(onAssign)90 })91 test("splice (length += 0)", () => {92 produce([1, 2, 3], s => {93 s.splice(1, 1, 0)94 })95 expectCalls(onAssign)96 })97 test("splice (length -= 1)", () => {98 produce([1, 2, 3], s => {99 s.splice(0, 2, 6)100 })101 expectCalls(onAssign)102 })103 })104 describe("when a draft is moved into a new object", () => {105 it("is called in the right order", () => {106 const calls = []107 onAssign.mockImplementation((_, prop) => {108 calls.push(prop)109 })110 produce({a: {b: 1, c: {}}}, s => {111 s.a.b = 0112 s.a.c.d = 1113 s.x = {y: {z: s.a}}114 delete s.a115 })116 // Sibling properties use enumeration order, which means new117 // properties come last among their siblings. The deepest118 // properties always come first in their ancestor chain.119 expect(calls).toEqual(["b", "d", "c", "x"])120 })121 })122123 describe("when draft is a Map", () => {124 test("assign", () => {125 const key1 = {prop: "val1"}126 const key2 = {prop: "val2"}127 produce(new Map([["a", 0], [key1, 1], [key2, 2]]), s => {128 s.set("a", 10)129 s.set(key1, 11)130 })131 expectCalls(onAssign)132 })133 test("assign (no change)", () => {134 produce(new Map([["a", 0]]), s => {135 s.set("a", 0)136 })137 expect(onAssign).not.toBeCalled()138 })139 test("delete", () => {140 produce(new Map([["a", 0]]), s => {141 s.delete("a")142 })143 expect(onAssign).not.toBeCalled()144 })145 test("nested assignments", () => {146 const key1 = {prop: "val1"}147 produce(148 new Map([149 [150 "a",151 new Map([152 [key1, new Map([["b", 1], ["c", 1], ["d", 1]])]153 ])154 ]155 ]),156 s => {157 const nested = s.get("a").get(key1)158 nested.set("b", 2)159 nested.delete("c")160 nested.set("d", 1) // no-op161 }162 )163 expectCalls(onAssign)164 })165 })123 describe("when draft is a Map", () => {124 test("assign", () => {125 const key1 = {prop: "val1"}126 const key2 = {prop: "val2"}127 produce(new Map([["a", 0], [key1, 1], [key2, 2]]), s => {128 s.set("a", 10)129 s.set(key1, 11)130 })131 expectCalls(onAssign)132 })133 test("assign (no change)", () => {134 produce(new Map([["a", 0]]), s => {135 s.set("a", 0)136 })137 expect(onAssign).not.toBeCalled()138 })139 test("delete", () => {140 produce(new Map([["a", 0]]), s => {141 s.delete("a")142 })143 expect(onAssign).not.toBeCalled()144 })145 test("nested assignments", () => {146 const key1 = {prop: "val1"}147 produce(148 new Map([149 ["a", new Map([[key1, new Map([["b", 1], ["c", 1], ["d", 1]])]])]150 ]),151 s => {152 const nested = s.get("a").get(key1)153 nested.set("b", 2)154 nested.delete("c")155 nested.set("d", 1) // no-op156 }157 )158 expectCalls(onAssign)159 })160 })161167 describe("when draft is a Set", () => {168 test("assign", () => {169 produce({a: new Set([1, 2, 3])}, s => {170 s.a.add(4)171 })172 expectCalls(onAssign)173 })174 test("assign (no change)", () => {175 produce({a: new Set([1, 2, 3])}, s => {176 s.a.add(3)177 })178 expect(onAssign).not.toBeCalled()179 })180 // Any mutation of a Set results in a new assignment. Including deletes.181 test("delete", () => {182 produce({a: new Set([1, 2, 3])}, s => {183 s.a.delete(1)184 })185 expectCalls(onAssign)186 })187 test("nested assignments", () => {188 const val1 = {prop: "val1"}189 produce({a: new Set(["a", new Set([val1, 1])])}, s => {190 let nested191 s.a.forEach(value => {192 if (isSet(value)) {193 nested = value194 }195 })196 nested.add(2)197 nested.delete(val1)198 nested.add(1) // no-op199 })200 expectCalls(onAssign)201 })202 })203 })162 describe("when draft is a Set", () => {163 test("assign", () => {164 produce({a: new Set([1, 2, 3])}, s => {165 s.a.add(4)166 })167 expectCalls(onAssign)168 })169 test("assign (no change)", () => {170 produce({a: new Set([1, 2, 3])}, s => {171 s.a.add(3)172 })173 expect(onAssign).not.toBeCalled()174 })175 // Any mutation of a Set results in a new assignment. Including deletes.176 test("delete", () => {177 produce({a: new Set([1, 2, 3])}, s => {178 s.a.delete(1)179 })180 expectCalls(onAssign)181 })182 test("nested assignments", () => {183 const val1 = {prop: "val1"}184 produce({a: new Set(["a", new Set([val1, 1])])}, s => {185 let nested186 s.a.forEach(value => {187 if (isSet(value)) {188 nested = value189 }190 })191 nested.add(2)192 nested.delete(val1)193 nested.add(1) // no-op194 })195 expectCalls(onAssign)196 })197 })198 })199205 describe("onDelete()", () => {206 useSharedTests(() => onDelete)207 describe("when draft is an object -", () => {208 test("delete", () => {209 produce({a: 1, b: 1, c: 1}, s => {210 delete s.a211 delete s.c212 })213 expectCalls(onDelete)214 })215 test("delete (no change)", () => {216 produce({}, s => {217 delete s.a218 })219 expect(onDelete).not.toBeCalled()220 })221 test("nested deletions", () => {222 produce({a: {b: {c: 1}}}, s => {223 delete s.a.b.c224 })225 expectCalls(onDelete)226 })227 })228 describe("when draft is an array -", () => {229 test("pop", () => {230 produce([1], s => {231 s.pop()232 })233 expectCalls(onDelete)234 })235 test("length = 0", () => {236 produce([1], s => {237 s.length = 0238 })239 expectCalls(onDelete)240 })241 test("splice (length -= 1)", () => {242 produce([1, 2, 3], s => {243 s.splice(0, 2, 6)244 })245 expectCalls(onDelete)246 })247 })200 describe("onDelete()", () => {201 useSharedTests(() => onDelete)202 describe("when draft is an object -", () => {203 test("delete", () => {204 produce({a: 1, b: 1, c: 1}, s => {205 delete s.a206 delete s.c207 })208 expectCalls(onDelete)209 })210 test("delete (no change)", () => {211 produce({}, s => {212 delete s.a213 })214 expect(onDelete).not.toBeCalled()215 })216 test("nested deletions", () => {217 produce({a: {b: {c: 1}}}, s => {218 delete s.a.b.c219 })220 expectCalls(onDelete)221 })222 })223 describe("when draft is an array -", () => {224 test("pop", () => {225 produce([1], s => {226 s.pop()227 })228 expectCalls(onDelete)229 })230 test("length = 0", () => {231 produce([1], s => {232 s.length = 0233 })234 expectCalls(onDelete)235 })236 test("splice (length -= 1)", () => {237 produce([1, 2, 3], s => {238 s.splice(0, 2, 6)239 })240 expectCalls(onDelete)241 })242 })243249 describe("when draft is a Map -", () => {250 test("delete", () => {251 const key1 = {prop: "val1"}252 const key2 = {prop: "val2"}253 produce(new Map([["a", 0], [key1, 1], [key2, 2]]), s => {254 s.delete("a")255 s.delete(key1)256 })257 expectCalls(onDelete)258 })259 test("delete (no change)", () => {260 produce(new Map(), s => {261 s.delete("a")262 })263 expect(onDelete).not.toBeCalled()264 })265 test("nested deletions", () => {266 const key1 = {prop: "val1"}267 produce(268 new Map([["a", new Map([[key1, new Map([["b", 1]])]])]]),269 s => {270 s.get("a")271 .get(key1)272 .delete("b")273 }274 )275 expectCalls(onDelete)276 })277 })244 describe("when draft is a Map -", () => {245 test("delete", () => {246 const key1 = {prop: "val1"}247 const key2 = {prop: "val2"}248 produce(new Map([["a", 0], [key1, 1], [key2, 2]]), s => {249 s.delete("a")250 s.delete(key1)251 })252 expectCalls(onDelete)253 })254 test("delete (no change)", () => {255 produce(new Map(), s => {256 s.delete("a")257 })258 expect(onDelete).not.toBeCalled()259 })260 test("nested deletions", () => {261 const key1 = {prop: "val1"}262 produce(new Map([["a", new Map([[key1, new Map([["b", 1]])]])]]), s => {263 s.get("a")264 .get(key1)265 .delete("b")266 })267 expectCalls(onDelete)268 })269 })270279 describe("when draft is a Set -", () => {280 test("delete", () => {281 produce({a: new Set([1])}, s => {282 s.a.delete(1)283 })284 expect(onDelete).not.toBeCalled()285 })286 })287 })271 describe("when draft is a Set -", () => {272 test("delete", () => {273 produce({a: new Set([1])}, s => {274 s.a.delete(1)275 })276 expect(onDelete).not.toBeCalled()277 })278 })279 })280289 describe("onCopy()", () => {290 let calls291 beforeEach(() => {292 calls = []293 onCopy.mockImplementation(s => {294 calls.push(s.base)295 })296 })281 describe("onCopy()", () => {282 let calls283 beforeEach(() => {284 calls = []285 onCopy.mockImplementation(s => {286 calls.push(s.base)287 })288 })289298 useSharedTests(() => onCopy)299 it("is called in the right order for objects", () => {300 const base = {a: {b: {c: 1}}}301 produce(base, s => {302 delete s.a.b.c303 })304 expect(calls).toShallowEqual([base.a.b, base.a, base])305 })290 useSharedTests(() => onCopy)291 it("is called in the right order for objects", () => {292 const base = {a: {b: {c: 1}}}293 produce(base, s => {294 delete s.a.b.c295 })296 expect(calls).toShallowEqual([base.a.b, base.a, base])297 })298307 it("is called in the right order for Maps", () => {308 const base = new Map([["a", new Map([["b", 0]])]])309 produce(base, s => {310 s.get("a").delete("b")311 })312 expect(calls).toShallowEqual([base.get("a"), base])313 })299 it("is called in the right order for Maps", () => {300 const base = new Map([["a", new Map([["b", 0]])]])301 produce(base, s => {302 s.get("a").delete("b")303 })304 expect(calls).toShallowEqual([base.get("a"), base])305 })306315 it("is called in the right order for Sets", () => {316 const item1 = {a: 0}317 const base = new Set([item1])318 produce(base, s => {319 s.forEach(item => item.a++)320 })321 expect(calls).toShallowEqual([item1, base])322 })323 })307 it("is called in the right order for Sets", () => {308 const item1 = {a: 0}309 const base = new Set([item1])310 produce(base, s => {311 s.forEach(item => item.a++)312 })313 expect(calls).toShallowEqual([item1, base])314 })315 })316325 function useSharedTests(getHook) {326 it("is called before the parent is frozen", () => {327 const hook = getHook()328 hook.mockImplementation(s => {329 // Parent object must not be frozen.330 expect(Object.isFrozen(s.base)).toBeFalsy()331 })332 produce({a: {b: {c: 0}}}, s => {333 if (hook == onDelete) delete s.a.b.c334 else s.a.b.c = 1335 })336 expect(hook).toHaveBeenCalledTimes(hook == onDelete ? 1 : 3)337 })338 }317 function useSharedTests(getHook) {318 it("is called before the parent is frozen", () => {319 const hook = getHook()320 hook.mockImplementation(s => {321 // Parent object must not be frozen.322 expect(Object.isFrozen(s.base)).toBeFalsy()323 })324 produce({a: {b: {c: 0}}}, s => {325 if (hook == onDelete) delete s.a.b.c326 else s.a.b.c = 1327 })328 expect(hook).toHaveBeenCalledTimes(hook == onDelete ? 1 : 3)329 })330 }331}332333// Produce a snapshot of the hook arguments (minus any draft state).334function expectCalls(hook) {343 expect(344 hook.mock.calls.map(call => {345 return call.slice(1)346 })347 ).toMatchSnapshot()335 expect(336 hook.mock.calls.map(call => {337 return call.slice(1)338 })339 ).toMatchSnapshot()340}341342expect.extend({351 toShallowEqual(received, expected) {352 const match = matchers.toBe(received, expected)353 return match.pass || !received || typeof received !== "object"354 ? match355 : !Array.isArray(expected) ||356 (Array.isArray(received) && received.length === expected.length)357 ? matchers.toEqual(received, expected)358 : match359 }343 toShallowEqual(received, expected) {344 const match = matchers.toBe(received, expected)345 return match.pass || !received || typeof received !== "object"346 ? match347 : !Array.isArray(expected) ||348 (Array.isArray(received) && received.length === expected.length)349 ? matchers.toEqual(received, expected)350 : match351 }352})
modified:__tests__/manual.js+104 added-104 removed
1"use strict"2import {3 setUseProxies,4 createDraft,5 finishDraft,6 produce,7 isDraft3 setUseProxies,4 createDraft,5 finishDraft,6 produce,7 isDraft8} from "../src/index"910runTests("proxy", true)11runTests("es5", false)1213function runTests(name, useProxies) {14 describe("manual - " + name, () => {15 setUseProxies(useProxies)14 describe("manual - " + name, () => {15 setUseProxies(useProxies)1617 it("should check arguments", () => {18 expect(() => createDraft(3)).toThrowErrorMatchingSnapshot()19 const buf = new Buffer([])20 expect(() => createDraft(buf)).toThrowErrorMatchingSnapshot()21 expect(() => finishDraft({})).toThrowErrorMatchingSnapshot()22 })17 it("should check arguments", () => {18 expect(() => createDraft(3)).toThrowErrorMatchingSnapshot()19 const buf = new Buffer([])20 expect(() => createDraft(buf)).toThrowErrorMatchingSnapshot()21 expect(() => finishDraft({})).toThrowErrorMatchingSnapshot()22 })2324 it("should support manual drafts", () => {25 const state = [{}, {}, {}]24 it("should support manual drafts", () => {25 const state = [{}, {}, {}]2627 const draft = createDraft(state)28 draft.forEach((item, index) => {29 item.index = index30 })27 const draft = createDraft(state)28 draft.forEach((item, index) => {29 item.index = index30 })3132 const result = finishDraft(draft)32 const result = finishDraft(draft)3334 expect(result).not.toBe(state)35 expect(result).toEqual([{index: 0}, {index: 1}, {index: 2}])36 expect(state).toEqual([{}, {}, {}])37 })34 expect(result).not.toBe(state)35 expect(result).toEqual([{index: 0}, {index: 1}, {index: 2}])36 expect(state).toEqual([{}, {}, {}])37 })3839 it("cannot modify after finish", () => {40 const state = {a: 1}39 it("cannot modify after finish", () => {40 const state = {a: 1}4142 const draft = createDraft(state)43 draft.a = 244 expect(finishDraft(draft)).toEqual({a: 2})45 expect(() => {46 draft.a = 347 }).toThrowErrorMatchingSnapshot()48 })42 const draft = createDraft(state)43 draft.a = 244 expect(finishDraft(draft)).toEqual({a: 2})45 expect(() => {46 draft.a = 347 }).toThrowErrorMatchingSnapshot()48 })4950 it("should support patches drafts", () => {51 const state = {a: 1}50 it("should support patches drafts", () => {51 const state = {a: 1}5253 const draft = createDraft(state)54 draft.a = 255 draft.b = 353 const draft = createDraft(state)54 draft.a = 255 draft.b = 35657 const listener = jest.fn()58 const result = finishDraft(draft, listener)57 const listener = jest.fn()58 const result = finishDraft(draft, listener)5960 expect(result).not.toBe(state)61 expect(result).toEqual({a: 2, b: 3})62 expect(listener.mock.calls).toMatchSnapshot()63 })60 expect(result).not.toBe(state)61 expect(result).toEqual({a: 2, b: 3})62 expect(listener.mock.calls).toMatchSnapshot()63 })6465 it("should handle multiple create draft calls", () => {66 const state = {a: 1}65 it("should handle multiple create draft calls", () => {66 const state = {a: 1}6768 const draft = createDraft(state)69 draft.a = 268 const draft = createDraft(state)69 draft.a = 27071 const draft2 = createDraft(state)72 draft2.b = 371 const draft2 = createDraft(state)72 draft2.b = 37374 const result = finishDraft(draft)74 const result = finishDraft(draft)7576 expect(result).not.toBe(state)77 expect(result).toEqual({a: 2})76 expect(result).not.toBe(state)77 expect(result).toEqual({a: 2})7879 draft2.a = 480 const result2 = finishDraft(draft2)81 expect(result2).not.toBe(result)82 expect(result2).toEqual({a: 4, b: 3})83 })79 draft2.a = 480 const result2 = finishDraft(draft2)81 expect(result2).not.toBe(result)82 expect(result2).toEqual({a: 4, b: 3})83 })8485 it("combines with produce - 1", () => {86 const state = {a: 1}85 it("combines with produce - 1", () => {86 const state = {a: 1}8788 const draft = createDraft(state)89 draft.a = 290 const res1 = produce(draft, d => {91 d.b = 392 })93 draft.b = 494 const res2 = finishDraft(draft)95 expect(res1).toEqual({a: 2, b: 3})96 expect(res2).toEqual({a: 2, b: 4})97 })88 const draft = createDraft(state)89 draft.a = 290 const res1 = produce(draft, d => {91 d.b = 392 })93 draft.b = 494 const res2 = finishDraft(draft)95 expect(res1).toEqual({a: 2, b: 3})96 expect(res2).toEqual({a: 2, b: 4})97 })9899 it("combines with produce - 2", () => {100 const state = {a: 1}99 it("combines with produce - 2", () => {100 const state = {a: 1}101102 const res1 = produce(state, draft => {103 draft.b = 3104 const draft2 = createDraft(draft)105 draft.c = 4106 draft2.d = 5107 const res2 = finishDraft(draft2)108 expect(res2).toEqual({109 a: 1,110 b: 3,111 d: 5112 })113 draft.d = 2114 })115 expect(res1).toEqual({116 a: 1,117 b: 3,118 c: 4,119 d: 2120 })121 })102 const res1 = produce(state, draft => {103 draft.b = 3104 const draft2 = createDraft(draft)105 draft.c = 4106 draft2.d = 5107 const res2 = finishDraft(draft2)108 expect(res2).toEqual({109 a: 1,110 b: 3,111 d: 5112 })113 draft.d = 2114 })115 expect(res1).toEqual({116 a: 1,117 b: 3,118 c: 4,119 d: 2120 })121 })122123 it("should not finish drafts from produce", () => {124 produce({x: 1}, draft => {125 expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()126 })127 })123 it("should not finish drafts from produce", () => {124 produce({x: 1}, draft => {125 expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()126 })127 })128129 it("should not finish twice", () => {130 const draft = createDraft({a: 1})131 draft.a++132 finishDraft(draft)133 expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()134 })135 })129 it("should not finish twice", () => {130 const draft = createDraft({a: 1})131 draft.a++132 finishDraft(draft)133 expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()134 })135 })136}
modified:__tests__/null-base.js+5 added-5 removed
modified:__tests__/original.js+37 added-37 removed
modified:__tests__/patch.js+557 added-563 removed
2 unmodified lines
34jest.setTimeout(1000)56function runPatchTest(base, producer, patches, inversePathes) {7 function runPatchTestHelper() {8 let recordedPatches9 let recordedInversePatches7 function runPatchTestHelper() {8 let recordedPatches9 let recordedInversePatches1011 const res = produce(base, producer, (p, i) => {12 recordedPatches = p13 recordedInversePatches = i14 })11 const res = produce(base, producer, (p, i) => {12 recordedPatches = p13 recordedInversePatches = i14 })1516 test("produces the correct patches", () => {17 expect(recordedPatches).toEqual(patches)18 if (inversePathes)19 expect(recordedInversePatches).toEqual(inversePathes)20 })16 test("produces the correct patches", () => {17 expect(recordedPatches).toEqual(patches)18 if (inversePathes) expect(recordedInversePatches).toEqual(inversePathes)19 })2022 test("patches are replayable", () => {23 expect(applyPatches(base, recordedPatches)).toEqual(res)24 })21 test("patches are replayable", () => {22 expect(applyPatches(base, recordedPatches)).toEqual(res)23 })2426 test("patches can be reversed", () => {27 expect(applyPatches(res, recordedInversePatches)).toEqual(base)28 })29 }25 test("patches can be reversed", () => {26 expect(applyPatches(res, recordedInversePatches)).toEqual(base)27 })28 }2931 describe(`proxy`, () => {32 setUseProxies(true)33 runPatchTestHelper()34 })30 describe(`proxy`, () => {31 setUseProxies(true)32 runPatchTestHelper()33 })3436 describe(`es5`, () => {37 setUseProxies(false)38 runPatchTestHelper()39 })35 describe(`es5`, () => {36 setUseProxies(false)37 runPatchTestHelper()38 })39}4041describe("applyPatches", () => {43 it("mutates the base state when it is a draft", () => {44 produce({a: 1}, draft => {45 const result = applyPatches(draft, [46 {op: "replace", path: ["a"], value: 2}47 ])48 expect(result).toBe(draft)49 expect(draft.a).toBe(2)50 })51 })52 it("produces a copy of the base state when not a draft", () => {53 const base = {a: 1}54 const result = applyPatches(base, [55 {op: "replace", path: ["a"], value: 2}56 ])57 expect(result).not.toBe(base)58 expect(result.a).toBe(2)59 expect(base.a).toBe(1)60 })61 it('throws when `op` is not "add", "replace", nor "remove"', () => {62 expect(() => {63 const patch = {op: "copy", from: [0], path: [1]}64 applyPatches([2], [patch])65 }).toThrowErrorMatchingSnapshot()66 })67 it("throws when `path` cannot be resolved", () => {68 // missing parent69 expect(() => {70 const patch = {op: "add", path: ["a", "b"], value: 1}71 applyPatches({}, [patch])72 }).toThrowErrorMatchingSnapshot()42 it("mutates the base state when it is a draft", () => {43 produce({a: 1}, draft => {44 const result = applyPatches(draft, [45 {op: "replace", path: ["a"], value: 2}46 ])47 expect(result).toBe(draft)48 expect(draft.a).toBe(2)49 })50 })51 it("produces a copy of the base state when not a draft", () => {52 const base = {a: 1}53 const result = applyPatches(base, [{op: "replace", path: ["a"], value: 2}])54 expect(result).not.toBe(base)55 expect(result.a).toBe(2)56 expect(base.a).toBe(1)57 })58 it('throws when `op` is not "add", "replace", nor "remove"', () => {59 expect(() => {60 const patch = {op: "copy", from: [0], path: [1]}61 applyPatches([2], [patch])62 }).toThrowErrorMatchingSnapshot()63 })64 it("throws when `path` cannot be resolved", () => {65 // missing parent66 expect(() => {67 const patch = {op: "add", path: ["a", "b"], value: 1}68 applyPatches({}, [patch])69 }).toThrowErrorMatchingSnapshot()7074 // missing grand-parent75 expect(() => {76 const patch = {op: "add", path: ["a", "b", "c"], value: 1}77 applyPatches({}, [patch])78 }).toThrowErrorMatchingSnapshot()79 })71 // missing grand-parent72 expect(() => {73 const patch = {op: "add", path: ["a", "b", "c"], value: 1}74 applyPatches({}, [patch])75 }).toThrowErrorMatchingSnapshot()76 })77})7879describe("simple assignment - 1", () => {83 runPatchTest(84 {x: 3},85 d => {86 d.x++87 },88 [{op: "replace", path: ["x"], value: 4}]89 )80 runPatchTest(81 {x: 3},82 d => {83 d.x++84 },85 [{op: "replace", path: ["x"], value: 4}]86 )87})8889describe("simple assignment - 2", () => {93 runPatchTest(94 {x: {y: 4}},95 d => {96 d.x.y++97 },98 [{op: "replace", path: ["x", "y"], value: 5}]99 )90 runPatchTest(91 {x: {y: 4}},92 d => {93 d.x.y++94 },95 [{op: "replace", path: ["x", "y"], value: 5}]96 )97})9899describe("simple assignment - 3", () => {103 runPatchTest(104 {x: [{y: 4}]},105 d => {106 d.x[0].y++107 },108 [{op: "replace", path: ["x", 0, "y"], value: 5}]109 )100 runPatchTest(101 {x: [{y: 4}]},102 d => {103 d.x[0].y++104 },105 [{op: "replace", path: ["x", 0, "y"], value: 5}]106 )107})108109describe("simple assignment - 4", () => {113 runPatchTest(114 new Map([["x", {y: 4}]]),115 d => {116 d.get("x").y++117 },118 [{op: "replace", path: ["x", "y"], value: 5}],119 [{op: "replace", path: ["x", "y"], value: 4}]120 )110 runPatchTest(111 new Map([["x", {y: 4}]]),112 d => {113 d.get("x").y++114 },115 [{op: "replace", path: ["x", "y"], value: 5}],116 [{op: "replace", path: ["x", "y"], value: 4}]117 )118})119120describe("simple assignment - 5", () => {124 runPatchTest(125 {x: new Map([["y", 4]])},126 d => {127 d.x.set("y", 5)128 },129 [{op: "replace", path: ["x", "y"], value: 5}],130 [{op: "replace", path: ["x", "y"], value: 4}]131 )121 runPatchTest(122 {x: new Map([["y", 4]])},123 d => {124 d.x.set("y", 5)125 },126 [{op: "replace", path: ["x", "y"], value: 5}],127 [{op: "replace", path: ["x", "y"], value: 4}]128 )129})130131describe("simple assignment - 6", () => {135 runPatchTest(136 new Map([["x", 1]]),137 d => {138 // Map.prototype.set should return the Map itself139 const res = d.set("x", 2)140 res.set("y", 3)141 },142 [143 {op: "replace", path: ["x"], value: 2},144 {op: "add", path: ["y"], value: 3}145 ],146 [{op: "replace", path: ["x"], value: 1}, {op: "remove", path: ["y"]}]147 )132 runPatchTest(133 new Map([["x", 1]]),134 d => {135 // Map.prototype.set should return the Map itself136 const res = d.set("x", 2)137 res.set("y", 3)138 },139 [140 {op: "replace", path: ["x"], value: 2},141 {op: "add", path: ["y"], value: 3}142 ],143 [{op: "replace", path: ["x"], value: 1}, {op: "remove", path: ["y"]}]144 )145})146147describe("simple assignment - 7", () => {151 const key1 = {prop: "val1"}152 const key2 = {prop: "val2"}153 runPatchTest(154 {x: new Map([[key1, 4]])},155 d => {156 d.x.set(key1, 5)157 d.x.set(key2, 6)158 },159 [160 {op: "replace", path: ["x", key1], value: 5},161 {op: "add", path: ["x", key2], value: 6}162 ],163 [164 {op: "replace", path: ["x", key1], value: 4},165 {op: "remove", path: ["x", key2]}166 ]167 )148 const key1 = {prop: "val1"}149 const key2 = {prop: "val2"}150 runPatchTest(151 {x: new Map([[key1, 4]])},152 d => {153 d.x.set(key1, 5)154 d.x.set(key2, 6)155 },156 [157 {op: "replace", path: ["x", key1], value: 5},158 {op: "add", path: ["x", key2], value: 6}159 ],160 [161 {op: "replace", path: ["x", key1], value: 4},162 {op: "remove", path: ["x", key2]}163 ]164 )165})166167describe("delete 1", () => {171 runPatchTest(172 {x: {y: 4}},173 d => {174 delete d.x175 },176 [{op: "remove", path: ["x"]}]177 )168 runPatchTest(169 {x: {y: 4}},170 d => {171 delete d.x172 },173 [{op: "remove", path: ["x"]}]174 )175})176177describe("delete 2", () => {181 runPatchTest(182 new Map([["x", 1]]),183 d => {184 d.delete("x")185 },186 [{op: "remove", path: ["x"]}],187 [{op: "add", path: ["x"], value: 1}]188 )178 runPatchTest(179 new Map([["x", 1]]),180 d => {181 d.delete("x")182 },183 [{op: "remove", path: ["x"]}],184 [{op: "add", path: ["x"], value: 1}]185 )186})187188describe("delete 3", () => {192 runPatchTest(193 {x: new Map([["y", 1]])},194 d => {195 d.x.delete("y")196 },197 [{op: "remove", path: ["x", "y"]}],198 [{op: "add", path: ["x", "y"], value: 1}]199 )189 runPatchTest(190 {x: new Map([["y", 1]])},191 d => {192 d.x.delete("y")193 },194 [{op: "remove", path: ["x", "y"]}],195 [{op: "add", path: ["x", "y"], value: 1}]196 )197})198199describe("delete 5", () => {203 const key1 = {prop: "val1"}204 const key2 = {prop: "val2"}205 runPatchTest(206 {x: new Map([[key1, 1], [key2, 2]])},207 d => {208 d.x.delete(key1)209 d.x.delete(key2)210 },211 [{op: "remove", path: ["x", key1]}, {op: "remove", path: ["x", key2]}],212 [213 {op: "add", path: ["x", key1], value: 1},214 {op: "add", path: ["x", key2], value: 2}215 ]216 )200 const key1 = {prop: "val1"}201 const key2 = {prop: "val2"}202 runPatchTest(203 {x: new Map([[key1, 1], [key2, 2]])},204 d => {205 d.x.delete(key1)206 d.x.delete(key2)207 },208 [{op: "remove", path: ["x", key1]}, {op: "remove", path: ["x", key2]}],209 [210 {op: "add", path: ["x", key1], value: 1},211 {op: "add", path: ["x", key2], value: 2}212 ]213 )214})215216describe("delete 6", () => {220 runPatchTest(221 new Set(["x", 1]),222 d => {223 d.delete("x")224 },225 [{op: "remove", path: [0], value: "x"}],226 [{op: "add", path: [0], value: "x"}]227 )217 runPatchTest(218 new Set(["x", 1]),219 d => {220 d.delete("x")221 },222 [{op: "remove", path: [0], value: "x"}],223 [{op: "add", path: [0], value: "x"}]224 )225})226227describe("delete 7", () => {231 runPatchTest(232 {x: new Set(["y", 1])},233 d => {234 d.x.delete("y")235 },236 [{op: "remove", path: ["x", 0], value: "y"}],237 [{op: "add", path: ["x", 0], value: "y"}]238 )228 runPatchTest(229 {x: new Set(["y", 1])},230 d => {231 d.x.delete("y")232 },233 [{op: "remove", path: ["x", 0], value: "y"}],234 [{op: "add", path: ["x", 0], value: "y"}]235 )236})237238describe("renaming properties", () => {242 describe("nested object (no changes)", () => {243 runPatchTest(244 {a: {b: 1}},245 d => {246 d.x = d.a247 delete d.a248 },249 [250 {op: "add", path: ["x"], value: {b: 1}},251 {op: "remove", path: ["a"]}252 ]253 )254 })239 describe("nested object (no changes)", () => {240 runPatchTest(241 {a: {b: 1}},242 d => {243 d.x = d.a244 delete d.a245 },246 [{op: "add", path: ["x"], value: {b: 1}}, {op: "remove", path: ["a"]}]247 )248 })249256 describe("nested map (no changes)", () => {257 runPatchTest(258 new Map([["a", new Map([["b", 1]])]]),259 d => {260 d.set("x", d.get("a"))261 d.delete("a")262 },263 [264 {op: "add", path: ["x"], value: new Map([["b", 1]])},265 {op: "remove", path: ["a"]}266 ],267 [268 {op: "remove", path: ["x"]},269 {op: "add", path: ["a"], value: new Map([["b", 1]])}270 ]271 )272 })250 describe("nested map (no changes)", () => {251 runPatchTest(252 new Map([["a", new Map([["b", 1]])]]),253 d => {254 d.set("x", d.get("a"))255 d.delete("a")256 },257 [258 {op: "add", path: ["x"], value: new Map([["b", 1]])},259 {op: "remove", path: ["a"]}260 ],261 [262 {op: "remove", path: ["x"]},263 {op: "add", path: ["a"], value: new Map([["b", 1]])}264 ]265 )266 })267274 describe("nested object (with changes)", () => {275 runPatchTest(276 {a: {b: 1, c: 1}},277 d => {278 let a = d.a279 a.b = 2 // change280 delete a.c // delete281 a.y = 2 // add268 describe("nested object (with changes)", () => {269 runPatchTest(270 {a: {b: 1, c: 1}},271 d => {272 let a = d.a273 a.b = 2 // change274 delete a.c // delete275 a.y = 2 // add276283 // rename284 d.x = a285 delete d.a286 },287 [288 {op: "add", path: ["x"], value: {b: 2, y: 2}},289 {op: "remove", path: ["a"]}290 ]291 )292 })277 // rename278 d.x = a279 delete d.a280 },281 [282 {op: "add", path: ["x"], value: {b: 2, y: 2}},283 {op: "remove", path: ["a"]}284 ]285 )286 })287294 describe("nested map (with changes)", () => {295 runPatchTest(296 new Map([["a", new Map([["b", 1], ["c", 1]])]]),297 d => {298 let a = d.get("a")299 a.set("b", 2) // change300 a.delete("c") // delete301 a.set("y", 2) // add288 describe("nested map (with changes)", () => {289 runPatchTest(290 new Map([["a", new Map([["b", 1], ["c", 1]])]]),291 d => {292 let a = d.get("a")293 a.set("b", 2) // change294 a.delete("c") // delete295 a.set("y", 2) // add296303 // rename304 d.set("x", a)305 d.delete("a")306 },307 [308 {op: "add", path: ["x"], value: new Map([["b", 2], ["y", 2]])},309 {op: "remove", path: ["a"]}310 ],311 [312 {op: "remove", path: ["x"]},313 {op: "add", path: ["a"], value: new Map([["b", 1], ["c", 1]])}314 ]315 )316 })297 // rename298 d.set("x", a)299 d.delete("a")300 },301 [302 {op: "add", path: ["x"], value: new Map([["b", 2], ["y", 2]])},303 {op: "remove", path: ["a"]}304 ],305 [306 {op: "remove", path: ["x"]},307 {op: "add", path: ["a"], value: new Map([["b", 1], ["c", 1]])}308 ]309 )310 })311318 describe("deeply nested object (with changes)", () => {319 runPatchTest(320 {a: {b: {c: 1, d: 1}}},321 d => {322 let b = d.a.b323 b.c = 2 // change324 delete b.d // delete325 b.y = 2 // add312 describe("deeply nested object (with changes)", () => {313 runPatchTest(314 {a: {b: {c: 1, d: 1}}},315 d => {316 let b = d.a.b317 b.c = 2 // change318 delete b.d // delete319 b.y = 2 // add320327 // rename328 d.a.x = b329 delete d.a.b330 },331 [332 {op: "add", path: ["a", "x"], value: {c: 2, y: 2}},333 {op: "remove", path: ["a", "b"]}334 ]335 )336 })321 // rename322 d.a.x = b323 delete d.a.b324 },325 [326 {op: "add", path: ["a", "x"], value: {c: 2, y: 2}},327 {op: "remove", path: ["a", "b"]}328 ]329 )330 })331338 describe("deeply nested map (with changes)", () => {339 runPatchTest(340 new Map([["a", new Map([["b", new Map([["c", 1], ["d", 1]])]])]]),341 d => {342 let b = d.get("a").get("b")343 b.set("c", 2) // change344 b.delete("d") // delete345 b.set("y", 2) // add332 describe("deeply nested map (with changes)", () => {333 runPatchTest(334 new Map([["a", new Map([["b", new Map([["c", 1], ["d", 1]])]])]]),335 d => {336 let b = d.get("a").get("b")337 b.set("c", 2) // change338 b.delete("d") // delete339 b.set("y", 2) // add340347 // rename348 d.get("a").set("x", b)349 d.get("a").delete("b")350 },351 [352 {353 op: "add",354 path: ["a", "x"],355 value: new Map([["c", 2], ["y", 2]])356 },357 {op: "remove", path: ["a", "b"]}358 ],359 [360 {op: "remove", path: ["a", "x"]},361 {362 op: "add",363 path: ["a", "b"],364 value: new Map([["c", 1], ["d", 1]])365 }366 ]367 )368 })341 // rename342 d.get("a").set("x", b)343 d.get("a").delete("b")344 },345 [346 {347 op: "add",348 path: ["a", "x"],349 value: new Map([["c", 2], ["y", 2]])350 },351 {op: "remove", path: ["a", "b"]}352 ],353 [354 {op: "remove", path: ["a", "x"]},355 {356 op: "add",357 path: ["a", "b"],358 value: new Map([["c", 1], ["d", 1]])359 }360 ]361 )362 })363})364365describe("minimum amount of changes", () => {372 runPatchTest(373 {x: 3, y: {a: 4}, z: 3},374 d => {375 d.y.a = 4376 d.y.b = 5377 Object.assign(d, {x: 4, y: {a: 2}})378 },379 [380 {op: "replace", path: ["x"], value: 4},381 {op: "replace", path: ["y"], value: {a: 2}}382 ]383 )366 runPatchTest(367 {x: 3, y: {a: 4}, z: 3},368 d => {369 d.y.a = 4370 d.y.b = 5371 Object.assign(d, {x: 4, y: {a: 2}})372 },373 [374 {op: "replace", path: ["x"], value: 4},375 {op: "replace", path: ["y"], value: {a: 2}}376 ]377 )378})379380describe("arrays - prepend", () => {387 runPatchTest(388 {x: [1, 2, 3]},389 d => {390 d.x.unshift(4)391 },392 [{op: "add", path: ["x", 0], value: 4}]393 )381 runPatchTest(382 {x: [1, 2, 3]},383 d => {384 d.x.unshift(4)385 },386 [{op: "add", path: ["x", 0], value: 4}]387 )388})389390describe("arrays - multiple prepend", () => {397 runPatchTest(398 {x: [1, 2, 3]},399 d => {400 d.x.unshift(4)401 d.x.unshift(5)402 },403 [404 {op: "add", path: ["x", 0], value: 5},405 {op: "add", path: ["x", 1], value: 4}406 ]407 )391 runPatchTest(392 {x: [1, 2, 3]},393 d => {394 d.x.unshift(4)395 d.x.unshift(5)396 },397 [398 {op: "add", path: ["x", 0], value: 5},399 {op: "add", path: ["x", 1], value: 4}400 ]401 )402})403404describe("arrays - splice middle", () => {411 runPatchTest(412 {x: [1, 2, 3]},413 d => {414 d.x.splice(1, 1)415 },416 [{op: "remove", path: ["x", 1]}]417 )405 runPatchTest(406 {x: [1, 2, 3]},407 d => {408 d.x.splice(1, 1)409 },410 [{op: "remove", path: ["x", 1]}]411 )412})413414describe("arrays - multiple splice", () => {421 runPatchTest(422 [0, 1, 2, 3, 4, 5, 0],423 d => {424 d.splice(4, 2, 3)425 d.splice(1, 2, 3)426 },427 [428 {op: "replace", path: [1], value: 3},429 {op: "replace", path: [2], value: 3},430 {op: "remove", path: [5]},431 {op: "remove", path: [4]}432 ]433 )415 runPatchTest(416 [0, 1, 2, 3, 4, 5, 0],417 d => {418 d.splice(4, 2, 3)419 d.splice(1, 2, 3)420 },421 [422 {op: "replace", path: [1], value: 3},423 {op: "replace", path: [2], value: 3},424 {op: "remove", path: [5]},425 {op: "remove", path: [4]}426 ]427 )428})429430describe("arrays - modify and shrink", () => {437 runPatchTest(438 {x: [1, 2, 3]},439 d => {440 d.x[0] = 4441 d.x.length = 2442 },443 [444 {op: "replace", path: ["x", 0], value: 4},445 {op: "replace", path: ["x", "length"], value: 2}446 ]447 )431 runPatchTest(432 {x: [1, 2, 3]},433 d => {434 d.x[0] = 4435 d.x.length = 2436 },437 [438 {op: "replace", path: ["x", 0], value: 4},439 {op: "replace", path: ["x", "length"], value: 2}440 ]441 )442})443444describe("arrays - prepend then splice middle", () => {451 runPatchTest(452 {x: [1, 2, 3]},453 d => {454 d.x.unshift(4)455 d.x.splice(2, 1)456 },457 [458 {op: "replace", path: ["x", 0], value: 4},459 {op: "replace", path: ["x", 1], value: 1}460 ]461 )445 runPatchTest(446 {x: [1, 2, 3]},447 d => {448 d.x.unshift(4)449 d.x.splice(2, 1)450 },451 [452 {op: "replace", path: ["x", 0], value: 4},453 {op: "replace", path: ["x", 1], value: 1}454 ]455 )456})457458describe("arrays - splice middle then prepend", () => {465 runPatchTest(466 {x: [1, 2, 3]},467 d => {468 d.x.splice(1, 1)469 d.x.unshift(4)470 },471 [472 {op: "replace", path: ["x", 0], value: 4},473 {op: "replace", path: ["x", 1], value: 1}474 ]475 )459 runPatchTest(460 {x: [1, 2, 3]},461 d => {462 d.x.splice(1, 1)463 d.x.unshift(4)464 },465 [466 {op: "replace", path: ["x", 0], value: 4},467 {op: "replace", path: ["x", 1], value: 1}468 ]469 )470})471472describe("arrays - truncate", () => {479 runPatchTest(480 {x: [1, 2, 3]},481 d => {482 d.x.length -= 2483 },484 [{op: "replace", path: ["x", "length"], value: 1}],485 [486 {op: "add", path: ["x", 1], value: 2},487 {op: "add", path: ["x", 2], value: 3}488 ]489 )473 runPatchTest(474 {x: [1, 2, 3]},475 d => {476 d.x.length -= 2477 },478 [{op: "replace", path: ["x", "length"], value: 1}],479 [480 {op: "add", path: ["x", 1], value: 2},481 {op: "add", path: ["x", 2], value: 3}482 ]483 )484})485486describe("arrays - pop twice", () => {493 runPatchTest(494 {x: [1, 2, 3]},495 d => {496 d.x.pop()497 d.x.pop()498 },499 [{op: "replace", path: ["x", "length"], value: 1}]500 )487 runPatchTest(488 {x: [1, 2, 3]},489 d => {490 d.x.pop()491 d.x.pop()492 },493 [{op: "replace", path: ["x", "length"], value: 1}]494 )495})496497describe("arrays - push multiple", () => {504 runPatchTest(505 {x: [1, 2, 3]},506 d => {507 d.x.push(4, 5)508 },509 [510 {op: "add", path: ["x", 3], value: 4},511 {op: "add", path: ["x", 4], value: 5}512 ],513 [{op: "replace", path: ["x", "length"], value: 3}]514 )498 runPatchTest(499 {x: [1, 2, 3]},500 d => {501 d.x.push(4, 5)502 },503 [504 {op: "add", path: ["x", 3], value: 4},505 {op: "add", path: ["x", 4], value: 5}506 ],507 [{op: "replace", path: ["x", "length"], value: 3}]508 )509})510511describe("arrays - splice (expand)", () => {518 runPatchTest(519 {x: [1, 2, 3]},520 d => {521 d.x.splice(1, 1, 4, 5, 6)522 },523 [524 {op: "replace", path: ["x", 1], value: 4},525 {op: "add", path: ["x", 2], value: 5},526 {op: "add", path: ["x", 3], value: 6}527 ],528 [529 {op: "replace", path: ["x", 1], value: 2},530 {op: "remove", path: ["x", 3]},531 {op: "remove", path: ["x", 2]}532 ]533 )512 runPatchTest(513 {x: [1, 2, 3]},514 d => {515 d.x.splice(1, 1, 4, 5, 6)516 },517 [518 {op: "replace", path: ["x", 1], value: 4},519 {op: "add", path: ["x", 2], value: 5},520 {op: "add", path: ["x", 3], value: 6}521 ],522 [523 {op: "replace", path: ["x", 1], value: 2},524 {op: "remove", path: ["x", 3]},525 {op: "remove", path: ["x", 2]}526 ]527 )528})529530describe("arrays - splice (shrink)", () => {537 runPatchTest(538 {x: [1, 2, 3, 4, 5]},539 d => {540 d.x.splice(1, 3, 6)541 },542 [543 {op: "replace", path: ["x", 1], value: 6},544 {op: "remove", path: ["x", 3]},545 {op: "remove", path: ["x", 2]}546 ],547 [548 {op: "replace", path: ["x", 1], value: 2},549 {op: "add", path: ["x", 2], value: 3},550 {op: "add", path: ["x", 3], value: 4}551 ]552 )531 runPatchTest(532 {x: [1, 2, 3, 4, 5]},533 d => {534 d.x.splice(1, 3, 6)535 },536 [537 {op: "replace", path: ["x", 1], value: 6},538 {op: "remove", path: ["x", 3]},539 {op: "remove", path: ["x", 2]}540 ],541 [542 {op: "replace", path: ["x", 1], value: 2},543 {op: "add", path: ["x", 2], value: 3},544 {op: "add", path: ["x", 3], value: 4}545 ]546 )547})548549describe("sets - add - 1", () => {556 runPatchTest(557 new Set([1]),558 d => {559 d.add(2)560 },561 [{op: "add", path: [1], value: 2}],562 [{op: "remove", path: [1], value: 2}]563 )550 runPatchTest(551 new Set([1]),552 d => {553 d.add(2)554 },555 [{op: "add", path: [1], value: 2}],556 [{op: "remove", path: [1], value: 2}]557 )558})559560describe("sets - add, delete, add - 1", () => {567 runPatchTest(568 new Set([1]),569 d => {570 d.add(2)571 d.delete(2)572 d.add(2)573 },574 [{op: "add", path: [1], value: 2}],575 [{op: "remove", path: [1], value: 2}]576 )561 runPatchTest(562 new Set([1]),563 d => {564 d.add(2)565 d.delete(2)566 d.add(2)567 },568 [{op: "add", path: [1], value: 2}],569 [{op: "remove", path: [1], value: 2}]570 )571})572573describe("sets - add, delete, add - 2", () => {580 runPatchTest(581 new Set([2, 1]),582 d => {583 d.add(2)584 d.delete(2)585 d.add(2)586 },587 [],588 []589 )574 runPatchTest(575 new Set([2, 1]),576 d => {577 d.add(2)578 d.delete(2)579 d.add(2)580 },581 [],582 []583 )584})585586describe("sets - mutate - 1", () => {593 const findById = (set, id) => {594 for (const item of set) {595 if (item.id === id) return item596 }597 }598 runPatchTest(599 new Set([{id: 1, val: "We"}, {id: 2, val: "will"}]),600 d => {601 const obj1 = findById(d, 1)602 const obj2 = findById(d, 2)603 obj1.val = "rock"604 obj2.val = "you"605 },606 [607 {op: "remove", path: [0], value: {id: 1, val: "We"}},608 {op: "remove", path: [1], value: {id: 2, val: "will"}},609 {op: "add", path: [0], value: {id: 1, val: "rock"}},610 {op: "add", path: [1], value: {id: 2, val: "you"}}611 ],612 [613 {op: "remove", path: [1], value: {id: 2, val: "you"}},614 {op: "remove", path: [0], value: {id: 1, val: "rock"}},615 {op: "add", path: [1], value: {id: 2, val: "will"}},616 {op: "add", path: [0], value: {id: 1, val: "We"}}617 ]618 )587 const findById = (set, id) => {588 for (const item of set) {589 if (item.id === id) return item590 }591 }592 runPatchTest(593 new Set([{id: 1, val: "We"}, {id: 2, val: "will"}]),594 d => {595 const obj1 = findById(d, 1)596 const obj2 = findById(d, 2)597 obj1.val = "rock"598 obj2.val = "you"599 },600 [601 {op: "remove", path: [0], value: {id: 1, val: "We"}},602 {op: "remove", path: [1], value: {id: 2, val: "will"}},603 {op: "add", path: [0], value: {id: 1, val: "rock"}},604 {op: "add", path: [1], value: {id: 2, val: "you"}}605 ],606 [607 {op: "remove", path: [1], value: {id: 2, val: "you"}},608 {op: "remove", path: [0], value: {id: 1, val: "rock"}},609 {op: "add", path: [1], value: {id: 2, val: "will"}},610 {op: "add", path: [0], value: {id: 1, val: "We"}}611 ]612 )613})614615describe("simple replacement", () => {622 runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])616 runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])617})618619describe("same value replacement - 1", () => {626 runPatchTest(627 {x: {y: 3}},628 d => {629 const a = d.x630 d.x = a631 },632 []633 )620 runPatchTest(621 {x: {y: 3}},622 d => {623 const a = d.x624 d.x = a625 },626 []627 )628})629630describe("same value replacement - 2", () => {637 runPatchTest(638 {x: {y: 3}},639 d => {640 const a = d.x641 d.x = 4642 d.x = a643 },644 []645 )631 runPatchTest(632 {x: {y: 3}},633 d => {634 const a = d.x635 d.x = 4636 d.x = a637 },638 []639 )640})641642describe("same value replacement - 3", () => {649 runPatchTest(650 {x: 3},651 d => {652 d.x = 3653 },654 []655 )643 runPatchTest(644 {x: 3},645 d => {646 d.x = 3647 },648 []649 )650})651652describe("same value replacement - 4", () => {659 runPatchTest(660 {x: 3},661 d => {662 d.x = 4663 d.x = 3664 },665 []666 )653 runPatchTest(654 {x: 3},655 d => {656 d.x = 4657 d.x = 3658 },659 []660 )661})662663describe("same value replacement - 5", () => {670 runPatchTest(671 new Map([["x", 3]]),672 d => {673 d.set("x", 4)674 d.set("x", 3)675 },676 [],677 []678 )664 runPatchTest(665 new Map([["x", 3]]),666 d => {667 d.set("x", 4)668 d.set("x", 3)669 },670 [],671 []672 )673})674675describe("same value replacement - 6", () => {682 runPatchTest(683 new Set(["x", 3]),684 d => {685 d.delete("x")686 d.add("x")687 },688 [],689 []690 )676 runPatchTest(677 new Set(["x", 3]),678 d => {679 d.delete("x")680 d.add("x")681 },682 [],683 []684 )685})686687describe("simple delete", () => {694 runPatchTest(695 {x: 2},696 d => {697 delete d.x698 },699 [700 {701 op: "remove",702 path: ["x"]703 }704 ]705 )688 runPatchTest(689 {x: 2},690 d => {691 delete d.x692 },693 [694 {695 op: "remove",696 path: ["x"]697 }698 ]699 )700})
modified:__tests__/polyfills.js+42 added-42 removed
13 unmodified lines
14Object.assign = assign15Reflect.ownKeys = ownKeys1617describe("Symbol", () => {18 test("NOTHING", () => {19 const value = common.NOTHING20 expect(value).toBeTruthy()21 expect(typeof value).toBe("object")22 })23 test("DRAFTABLE", () => {24 const value = common.DRAFTABLE25 expect(typeof value).toBe("string")26 })27 test("DRAFT_STATE", () => {28 const value = common.DRAFT_STATE29 expect(typeof value).toBe("string")30 })18 test("NOTHING", () => {19 const value = common.NOTHING20 expect(value).toBeTruthy()21 expect(typeof value).toBe("object")22 })23 test("DRAFTABLE", () => {24 const value = common.DRAFTABLE25 expect(typeof value).toBe("string")26 })27 test("DRAFT_STATE", () => {28 const value = common.DRAFT_STATE29 expect(typeof value).toBe("string")30 })31})3233describe("Object.assign", () => {34 const {assign} = common34 const {assign} = common3536 it("only copies enumerable keys", () => {37 const src = {a: 1}38 Object.defineProperty(src, "b", {value: 1})39 const dest = {}40 assign(dest, src)41 expect(dest.a).toBe(1)42 expect(dest.b).toBeUndefined()43 })36 it("only copies enumerable keys", () => {37 const src = {a: 1}38 Object.defineProperty(src, "b", {value: 1})39 const dest = {}40 assign(dest, src)41 expect(dest.a).toBe(1)42 expect(dest.b).toBeUndefined()43 })4445 it("only copies own properties", () => {46 const src = Object.create({a: 1})47 src.b = 148 const dest = {}49 assign(dest, src)50 expect(dest.a).toBeUndefined()51 expect(dest.b).toBe(1)52 })45 it("only copies own properties", () => {46 const src = Object.create({a: 1})47 src.b = 148 const dest = {}49 assign(dest, src)50 expect(dest.a).toBeUndefined()51 expect(dest.b).toBe(1)52 })53})5455describe("Reflect.ownKeys", () => {56 const {ownKeys} = common56 const {ownKeys} = common5758 // Symbol keys are always last.59 it("includes symbol keys", () => {60 const s = SymbolConstructor()61 const obj = {[s]: 1, b: 1}62 expect(ownKeys(obj)).toEqual(["b", s])63 })58 // Symbol keys are always last.59 it("includes symbol keys", () => {60 const s = SymbolConstructor()61 const obj = {[s]: 1, b: 1}62 expect(ownKeys(obj)).toEqual(["b", s])63 })6465 it("includes non-enumerable keys", () => {66 const obj = {a: 1}67 Object.defineProperty(obj, "b", {value: 1})68 expect(ownKeys(obj)).toEqual(["a", "b"])69 })65 it("includes non-enumerable keys", () => {66 const obj = {a: 1}67 Object.defineProperty(obj, "b", {value: 1})68 expect(ownKeys(obj)).toEqual(["a", "b"])69 })70})
modified:__tests__/readme.js+127 added-127 removed
1"use strict"2import produce, {applyPatches, immerable} from "../src/index"34describe("readme example", () => {5 it("works", () => {6 const baseState = [7 {8 todo: "Learn typescript",9 done: true10 },11 {12 todo: "Try immer",13 done: false14 }15 ]5 it("works", () => {6 const baseState = [7 {8 todo: "Learn typescript",9 done: true10 },11 {12 todo: "Try immer",13 done: false14 }15 ]1617 const nextState = produce(baseState, draft => {18 draft.push({todo: "Tweet about it"})19 draft[1].done = true20 })17 const nextState = produce(baseState, draft => {18 draft.push({todo: "Tweet about it"})19 draft[1].done = true20 })2122 // the new item is only added to the next state,23 // base state is unmodified24 expect(baseState.length).toBe(2)25 expect(nextState.length).toBe(3)22 // the new item is only added to the next state,23 // base state is unmodified24 expect(baseState.length).toBe(2)25 expect(nextState.length).toBe(3)2627 // same for the changed 'done' prop28 expect(baseState[1].done).toBe(false)29 expect(nextState[1].done).toBe(true)27 // same for the changed 'done' prop28 expect(baseState[1].done).toBe(false)29 expect(nextState[1].done).toBe(true)3031 // unchanged data is structurally shared32 expect(nextState[0]).toBe(baseState[0])33 // changed data not (dûh)34 expect(nextState[1]).not.toBe(baseState[1])35 })31 // unchanged data is structurally shared32 expect(nextState[0]).toBe(baseState[0])33 // changed data not (dûh)34 expect(nextState[1]).not.toBe(baseState[1])35 })3637 it("patches", () => {38 let state = {39 name: "Micheal",40 age: 3241 }37 it("patches", () => {38 let state = {39 name: "Micheal",40 age: 3241 }4243 // Let's assume the user is in a wizard, and we don't know whether44 // his changes should be updated45 let fork = state46 // all the changes the user made in the wizard47 let changes = []48 // all the inverse patches49 let inverseChanges = []43 // Let's assume the user is in a wizard, and we don't know whether44 // his changes should be updated45 let fork = state46 // all the changes the user made in the wizard47 let changes = []48 // all the inverse patches49 let inverseChanges = []5051 fork = produce(52 fork,53 draft => {54 draft.age = 3355 },56 // The third argument to produce is a callback to which the patches will be fed57 (patches, inversePatches) => {58 changes.push(...patches)59 inverseChanges.push(...inversePatches)60 }61 )51 fork = produce(52 fork,53 draft => {54 draft.age = 3355 },56 // The third argument to produce is a callback to which the patches will be fed57 (patches, inversePatches) => {58 changes.push(...patches)59 inverseChanges.push(...inversePatches)60 }61 )6263 // In the mean time, our original state is updated as well, as changes come in from the server64 state = produce(state, draft => {65 draft.name = "Michel"66 })63 // In the mean time, our original state is updated as well, as changes come in from the server64 state = produce(state, draft => {65 draft.name = "Michel"66 })6768 // When the wizard finishes (successfully) we can replay the changes made in the fork onto the *new* state!69 state = applyPatches(state, changes)68 // When the wizard finishes (successfully) we can replay the changes made in the fork onto the *new* state!69 state = applyPatches(state, changes)7071 // state now contains the changes from both code paths!72 expect(state).toEqual({73 name: "Michel",74 age: 3375 })71 // state now contains the changes from both code paths!72 expect(state).toEqual({73 name: "Michel",74 age: 3375 })7677 // Even after finishing the wizard, the user might change his mind...78 state = applyPatches(state, inverseChanges)79 expect(state).toEqual({80 name: "Michel",81 age: 3282 })83 })77 // Even after finishing the wizard, the user might change his mind...78 state = applyPatches(state, inverseChanges)79 expect(state).toEqual({80 name: "Michel",81 age: 3282 })83 })8485 it("can update set", () => {86 const state = {87 title: "hello",88 tokenSet: new Set()89 }85 it("can update set", () => {86 const state = {87 title: "hello",88 tokenSet: new Set()89 }9091 const nextState = produce(state, draft => {92 draft.title = draft.title.toUpperCase()93 draft.tokenSet.add("c1342")94 })91 const nextState = produce(state, draft => {92 draft.title = draft.title.toUpperCase()93 draft.tokenSet.add("c1342")94 })9596 expect(state).toEqual({title: "hello", tokenSet: new Set()})97 expect(nextState).toEqual({98 title: "HELLO",99 tokenSet: new Set(["c1342"])100 })101 })96 expect(state).toEqual({title: "hello", tokenSet: new Set()})97 expect(nextState).toEqual({98 title: "HELLO",99 tokenSet: new Set(["c1342"])100 })101 })102103 it("can deep update map", () => {104 const state = {105 users: new Map([["michel", {name: "miche", age: 27}]])106 }103 it("can deep update map", () => {104 const state = {105 users: new Map([["michel", {name: "miche", age: 27}]])106 }107108 const nextState = produce(state, draft => {109 draft.users.get("michel").name = "michel"110 })108 const nextState = produce(state, draft => {109 draft.users.get("michel").name = "michel"110 })111112 expect(state).toEqual({113 users: new Map([["michel", {name: "miche", age: 27}]])114 })115 expect(nextState).toEqual({116 users: new Map([["michel", {name: "michel", age: 27}]])117 })118 })112 expect(state).toEqual({113 users: new Map([["michel", {name: "miche", age: 27}]])114 })115 expect(nextState).toEqual({116 users: new Map([["michel", {name: "michel", age: 27}]])117 })118 })119120 it("supports immerable", () => {121 class Clock {122 constructor(hours = 0, minutes = 0) {123 this.hours = hours124 this.minutes = minutes125 }120 it("supports immerable", () => {121 class Clock {122 constructor(hours = 0, minutes = 0) {123 this.hours = hours124 this.minutes = minutes125 }126127 increment(hours, minutes = 0) {128 return produce(this, d => {129 d.hours += hours130 d.minutes += minutes131 })132 }127 increment(hours, minutes = 0) {128 return produce(this, d => {129 d.hours += hours130 d.minutes += minutes131 })132 }133134 toString() {135 return `${("" + this.hours).padStart(2, 0)}:${(136 "" + this.minutes137 ).padStart(2, 0)}`138 }139 }140 Clock[immerable] = true134 toString() {135 return `${("" + this.hours).padStart(2, 0)}:${(136 "" + this.minutes137 ).padStart(2, 0)}`138 }139 }140 Clock[immerable] = true141142 const midnight = new Clock()143 const lunch = midnight.increment(12, 30)142 const midnight = new Clock()143 const lunch = midnight.increment(12, 30)144145 expect(midnight).not.toBe(lunch)146 expect(lunch).toBeInstanceOf(Clock)147 expect(midnight.toString()).toBe("00:00")148 expect(lunch.toString()).toBe("12:30")145 expect(midnight).not.toBe(lunch)146 expect(lunch).toBeInstanceOf(Clock)147 expect(midnight.toString()).toBe("00:00")148 expect(lunch.toString()).toBe("12:30")149150 const diner = lunch.increment(6)150 const diner = lunch.increment(6)151152 expect(diner).not.toBe(lunch)153 expect(lunch).toBeInstanceOf(Clock)154 expect(diner.toString()).toBe("18:30")155 })152 expect(diner).not.toBe(lunch)153 expect(lunch).toBeInstanceOf(Clock)154 expect(diner.toString()).toBe("18:30")155 })156})
modified:src/common.js+137 added-137 removed
1export const NOTHING =2 typeof Symbol !== "undefined"3 ? Symbol("immer-nothing")4 : {["immer-nothing"]: true}2 typeof Symbol !== "undefined"3 ? Symbol("immer-nothing")4 : {["immer-nothing"]: true}56export const DRAFTABLE =7 typeof Symbol !== "undefined"8 ? Symbol.for("immer-draftable")9 : "__$immer_draftable"7 typeof Symbol !== "undefined"8 ? Symbol.for("immer-draftable")9 : "__$immer_draftable"1011export const DRAFT_STATE =12 typeof Symbol !== "undefined" ? Symbol.for("immer-state") : "__$immer_state"12 typeof Symbol !== "undefined" ? Symbol.for("immer-state") : "__$immer_state"1314export function isDraft(value) {15 return !!value && !!value[DRAFT_STATE]15 return !!value && !!value[DRAFT_STATE]16}1718export function isDraftable(value) {19 if (!value || typeof value !== "object") return false20 if (Array.isArray(value)) return true21 const proto = Object.getPrototypeOf(value)22 if (!proto || proto === Object.prototype) return true23 if (isMap(value) || isSet(value)) return true24 return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]19 if (!value || typeof value !== "object") return false20 if (Array.isArray(value)) return true21 const proto = Object.getPrototypeOf(value)22 if (!proto || proto === Object.prototype) return true23 if (isMap(value) || isSet(value)) return true24 return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]25}2627export function original(value) {28 if (value && value[DRAFT_STATE]) {29 return value[DRAFT_STATE].base30 }31 // otherwise return undefined28 if (value && value[DRAFT_STATE]) {29 return value[DRAFT_STATE].base30 }31 // otherwise return undefined32}3334// We use Maps as `drafts` for Sets, not Objects35// See proxy.js36export function assignSet(target, override) {37 override.forEach(value => {38 // When we add new drafts we have to remove their originals if present39 const prev = original(value)40 if (prev) target.delete(prev)41 target.add(value)42 })43 return target37 override.forEach(value => {38 // When we add new drafts we have to remove their originals if present39 const prev = original(value)40 if (prev) target.delete(prev)41 target.add(value)42 })43 return target44}4546// We use Maps as `drafts` for Maps, not Objects47// See proxy.js48export function assignMap(target, override) {49 override.forEach((value, key) => target.set(key, value))50 return target49 override.forEach((value, key) => target.set(key, value))50 return target51}5253export const assign =54 Object.assign ||55 ((target, ...overrides) => {56 overrides.forEach(override =>57 Object.keys(override).forEach(key => (target[key] = override[key]))58 )59 return target60 })54 Object.assign ||55 ((target, ...overrides) => {56 overrides.forEach(override =>57 Object.keys(override).forEach(key => (target[key] = override[key]))58 )59 return target60 })6162export const ownKeys =63 typeof Reflect !== "undefined" && Reflect.ownKeys64 ? Reflect.ownKeys65 : typeof Object.getOwnPropertySymbols !== "undefined"66 ? obj =>67 Object.getOwnPropertyNames(obj).concat(68 Object.getOwnPropertySymbols(obj)69 )70 : Object.getOwnPropertyNames63 typeof Reflect !== "undefined" && Reflect.ownKeys64 ? Reflect.ownKeys65 : typeof Object.getOwnPropertySymbols !== "undefined"66 ? obj =>67 Object.getOwnPropertyNames(obj).concat(68 Object.getOwnPropertySymbols(obj)69 )70 : Object.getOwnPropertyNames7172export function shallowCopy(base, invokeGetters = false) {73 if (Array.isArray(base)) return base.slice()74 if (isMap(base)) return new Map(base)75 if (isSet(base)) return new Set(base)76 const clone = Object.create(Object.getPrototypeOf(base))77 ownKeys(base).forEach(key => {78 if (key === DRAFT_STATE) {79 return // Never copy over draft state.80 }81 const desc = Object.getOwnPropertyDescriptor(base, key)82 let {value} = desc83 if (desc.get) {84 if (!invokeGetters) {85 throw new Error("Immer drafts cannot have computed properties")86 }87 value = desc.get.call(base)88 }89 if (desc.enumerable) {90 clone[key] = value91 } else {92 Object.defineProperty(clone, key, {93 value,94 writable: true,95 configurable: true96 })97 }98 })99 return clone73 if (Array.isArray(base)) return base.slice()74 if (isMap(base)) return new Map(base)75 if (isSet(base)) return new Set(base)76 const clone = Object.create(Object.getPrototypeOf(base))77 ownKeys(base).forEach(key => {78 if (key === DRAFT_STATE) {79 return // Never copy over draft state.80 }81 const desc = Object.getOwnPropertyDescriptor(base, key)82 let {value} = desc83 if (desc.get) {84 if (!invokeGetters) {85 throw new Error("Immer drafts cannot have computed properties")86 }87 value = desc.get.call(base)88 }89 if (desc.enumerable) {90 clone[key] = value91 } else {92 Object.defineProperty(clone, key, {93 value,94 writable: true,95 configurable: true96 })97 }98 })99 return clone100}101102export function each(obj, iter) {103 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {104 obj.forEach((entry, index) => iter(index, entry, obj))105 } else {106 ownKeys(obj).forEach(key => iter(key, obj[key], obj))107 }103 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {104 obj.forEach((entry, index) => iter(index, entry, obj))105 } else {106 ownKeys(obj).forEach(key => iter(key, obj[key], obj))107 }108}109110export function isEnumerable(base, prop) {111 const desc = Object.getOwnPropertyDescriptor(base, prop)112 return !!desc && desc.enumerable111 const desc = Object.getOwnPropertyDescriptor(base, prop)112 return !!desc && desc.enumerable113}114115export function has(thing, prop) {116 return isMap(thing)117 ? thing.has(prop)118 : Object.prototype.hasOwnProperty.call(thing, prop)116 return isMap(thing)117 ? thing.has(prop)118 : Object.prototype.hasOwnProperty.call(thing, prop)119}120121export function get(thing, prop) {122 return isMap(thing) ? thing.get(prop) : thing[prop]122 return isMap(thing) ? thing.get(prop) : thing[prop]123}124125export function is(x, y) {126 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js127 if (x === y) {128 return x !== 0 || 1 / x === 1 / y129 } else {130 return x !== x && y !== y131 }126 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js127 if (x === y) {128 return x !== 0 || 1 / x === 1 / y129 } else {130 return x !== x && y !== y131 }132}133134const hasMap = typeof Map !== "undefined"135136export function isMap(target) {137 return hasMap && target instanceof Map137 return hasMap && target instanceof Map138}139140const hasSet = typeof Set !== "undefined"141142export function isSet(target) {143 return hasSet && target instanceof Set143 return hasSet && target instanceof Set144}145146export function makeIterable(next) {147 let self148 return (self = {149 [Symbol.iterator]: () => self,150 next151 })147 let self148 return (self = {149 [Symbol.iterator]: () => self,150 next151 })152}153154/** Map.prototype.values _-or-_ Map.prototype.entries */155export function iterateMapValues(state, prop, receiver) {156 const isEntries = prop !== "values"157 return () => {158 const iterator = latest(state)[Symbol.iterator]()159 return makeIterable(() => {160 const result = iterator.next()161 if (!result.done) {162 const [key] = result.value163 const value = receiver.get(key)164 result.value = isEntries ? [key, value] : value165 }166 return result167 })168 }156 const isEntries = prop !== "values"157 return () => {158 const iterator = latest(state)[Symbol.iterator]()159 return makeIterable(() => {160 const result = iterator.next()161 if (!result.done) {162 const [key] = result.value163 const value = receiver.get(key)164 result.value = isEntries ? [key, value] : value165 }166 return result167 })168 }169}170171export function makeIterateSetValues(createProxy) {172 function iterateSetValues(state, prop) {173 const isEntries = prop === "entries"174 return () => {175 const iterator = latest(state)[Symbol.iterator]()176 return makeIterable(() => {177 const result = iterator.next()178 if (!result.done) {179 const value = wrapSetValue(state, result.value)180 result.value = isEntries ? [value, value] : value181 }182 return result183 })184 }185 }172 function iterateSetValues(state, prop) {173 const isEntries = prop === "entries"174 return () => {175 const iterator = latest(state)[Symbol.iterator]()176 return makeIterable(() => {177 const result = iterator.next()178 if (!result.done) {179 const value = wrapSetValue(state, result.value)180 result.value = isEntries ? [value, value] : value181 }182 return result183 })184 }185 }186187 function wrapSetValue(state, value) {188 const key = original(value) || value189 let draft = state.drafts.get(key)190 if (!draft) {191 if (state.finalized || !isDraftable(value) || state.finalizing) {192 return value193 }194 draft = createProxy(value, state)195 state.drafts.set(key, draft)196 if (state.modified) {197 state.copy.add(draft)198 }199 }200 return draft201 }187 function wrapSetValue(state, value) {188 const key = original(value) || value189 let draft = state.drafts.get(key)190 if (!draft) {191 if (state.finalized || !isDraftable(value) || state.finalizing) {192 return value193 }194 draft = createProxy(value, state)195 state.drafts.set(key, draft)196 if (state.modified) {197 state.copy.add(draft)198 }199 }200 return draft201 }202203 return iterateSetValues203 return iterateSetValues204}205206function latest(state) {207 return state.copy || state.base207 return state.copy || state.base208}
modified:src/es5.js+364 added-366 removed
1"use strict"2import {3 each,4 has,5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 isMap,10 isSet,11 shallowCopy,12 DRAFT_STATE,13 iterateMapValues,14 makeIterable,15 makeIterateSetValues3 each,4 has,5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 isMap,10 isSet,11 shallowCopy,12 DRAFT_STATE,13 iterateMapValues,14 makeIterable,15 makeIterateSetValues16} from "./common"17import {ImmerScope} from "./scope"1819export function willFinalize(scope, result, isReplaced) {20 scope.drafts.forEach(draft => {21 draft[DRAFT_STATE].finalizing = true22 })23 if (!isReplaced) {24 if (scope.patches) {25 markChangesRecursively(scope.drafts[0])26 }27 // This is faster when we don't care about which attributes changed.28 markChangesSweep(scope.drafts)29 }30 // When a child draft is returned, look for changes.31 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {32 markChangesSweep(scope.drafts)33 }20 scope.drafts.forEach(draft => {21 draft[DRAFT_STATE].finalizing = true22 })23 if (!isReplaced) {24 if (scope.patches) {25 markChangesRecursively(scope.drafts[0])26 }27 // This is faster when we don't care about which attributes changed.28 markChangesSweep(scope.drafts)29 }30 // When a child draft is returned, look for changes.31 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {32 markChangesSweep(scope.drafts)33 }34}3536export function createProxy(base, parent) {37 const isArray = Array.isArray(base)38 const draft = clonePotentialDraft(base)37 const isArray = Array.isArray(base)38 const draft = clonePotentialDraft(base)3940 if (isMap(base)) {41 proxyMap(draft)42 } else if (isSet(base)) {43 proxySet(draft)44 } else {45 each(draft, prop => {46 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))47 })48 }40 if (isMap(base)) {41 proxyMap(draft)42 } else if (isSet(base)) {43 proxySet(draft)44 } else {45 each(draft, prop => {46 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))47 })48 }4950 // See "proxy.js" for property documentation.51 const scope = parent ? parent.scope : ImmerScope.current52 const state = {53 scope,54 modified: false,55 finalizing: false, // es5 only56 finalized: false,57 assigned: isMap(base) ? new Map() : {},58 parent,59 base,60 draft,61 drafts: isSet(base) ? new Map() : null,62 copy: null,63 revoke,64 revoked: false // es5 only65 }50 // See "proxy.js" for property documentation.51 const scope = parent ? parent.scope : ImmerScope.current52 const state = {53 scope,54 modified: false,55 finalizing: false, // es5 only56 finalized: false,57 assigned: isMap(base) ? new Map() : {},58 parent,59 base,60 draft,61 drafts: isSet(base) ? new Map() : null,62 copy: null,63 revoke,64 revoked: false // es5 only65 }6667 createHiddenProperty(draft, DRAFT_STATE, state)68 scope.drafts.push(draft)69 return draft67 createHiddenProperty(draft, DRAFT_STATE, state)68 scope.drafts.push(draft)69 return draft70}7172function revoke() {73 this.revoked = true73 this.revoked = true74}7576function latest(state) {77 return state.copy || state.base77 return state.copy || state.base78}7980// Access a property without creating an Immer draft.81function peek(draft, prop) {82 const state = draft[DRAFT_STATE]83 if (state && !state.finalizing) {84 state.finalizing = true85 const value = draft[prop]86 state.finalizing = false87 return value88 }89 return draft[prop]82 const state = draft[DRAFT_STATE]83 if (state && !state.finalizing) {84 state.finalizing = true85 const value = draft[prop]86 state.finalizing = false87 return value88 }89 return draft[prop]90}9192function get(state, prop) {93 assertUnrevoked(state)94 const value = peek(latest(state), prop)95 if (state.finalizing) return value96 // Create a draft if the value is unmodified.97 if (value === peek(state.base, prop) && isDraftable(value)) {98 prepareCopy(state)99 return (state.copy[prop] = createProxy(value, state))100 }101 return value93 assertUnrevoked(state)94 const value = peek(latest(state), prop)95 if (state.finalizing) return value96 // Create a draft if the value is unmodified.97 if (value === peek(state.base, prop) && isDraftable(value)) {98 prepareCopy(state)99 return (state.copy[prop] = createProxy(value, state))100 }101 return value102}103104function set(state, prop, value) {105 assertUnrevoked(state)106 state.assigned[prop] = true107 if (!state.modified) {108 if (is(value, peek(latest(state), prop))) return109 markChanged(state)110 prepareCopy(state)111 }112 state.copy[prop] = value105 assertUnrevoked(state)106 state.assigned[prop] = true107 if (!state.modified) {108 if (is(value, peek(latest(state), prop))) return109 markChanged(state)110 prepareCopy(state)111 }112 state.copy[prop] = value113}114115function markChanged(state) {116 if (!state.modified) {117 state.modified = true118 if (state.parent) markChanged(state.parent)119 }116 if (!state.modified) {117 state.modified = true118 if (state.parent) markChanged(state.parent)119 }120}121122function prepareCopy(state) {123 if (!state.copy) state.copy = clonePotentialDraft(state.base)123 if (!state.copy) state.copy = clonePotentialDraft(state.base)124}125126function clonePotentialDraft(base) {127 const state = base && base[DRAFT_STATE]128 if (state) {129 state.finalizing = true130 const draft = shallowCopy(state.draft, true)131 state.finalizing = false132 return draft133 }134 return shallowCopy(base)127 const state = base && base[DRAFT_STATE]128 if (state) {129 state.finalizing = true130 const draft = shallowCopy(state.draft, true)131 state.finalizing = false132 return draft133 }134 return shallowCopy(base)135}136137// property descriptors are recycled to make sure we don't create a get and set closure per property,138// but share them all instead139const descriptors = {}140141function proxyProperty(draft, prop, enumerable) {142 let desc = descriptors[prop]143 if (desc) {144 desc.enumerable = enumerable145 } else {146 descriptors[prop] = desc = {147 configurable: true,148 enumerable,149 get() {150 return get(this[DRAFT_STATE], prop)151 },152 set(value) {153 set(this[DRAFT_STATE], prop, value)154 }155 }156 }157 Object.defineProperty(draft, prop, desc)142 let desc = descriptors[prop]143 if (desc) {144 desc.enumerable = enumerable145 } else {146 descriptors[prop] = desc = {147 configurable: true,148 enumerable,149 get() {150 return get(this[DRAFT_STATE], prop)151 },152 set(value) {153 set(this[DRAFT_STATE], prop, value)154 }155 }156 }157 Object.defineProperty(draft, prop, desc)158}159160function proxyMap(target) {161 Object.defineProperties(target, mapTraps)161 Object.defineProperties(target, mapTraps)162163 if (typeof Symbol !== undefined) {164 Object.defineProperty(165 target,166 Symbol.iterator,167 proxyMethod(iterateMapValues)168 )169 }163 if (typeof Symbol !== undefined) {164 Object.defineProperty(165 target,166 Symbol.iterator,167 proxyMethod(iterateMapValues)168 )169 }170}171172const mapTraps = finalizeTraps({173 size: state => latest(state).size,174 has: state => key => latest(state).has(key),175 set: state => (key, value) => {176 if (latest(state).get(key) !== value) {177 prepareCopy(state)178 markChanged(state)179 state.assigned.set(key, true)180 state.copy.set(key, value)181 }182 return state.draft183 },184 delete: state => key => {185 prepareCopy(state)186 markChanged(state)187 state.assigned.set(key, false)188 state.copy.delete(key)189 return false190 },191 clear: state => () => {192 if (!state.copy) {193 prepareCopy(state)194 }195 markChanged(state)196 state.assigned = new Map()197 for (const key of latest(state).keys()) {198 state.assigned.set(key, false)199 }200 return state.copy.clear()201 },202 forEach: (state, key, reciever) => cb => {203 latest(state).forEach((value, key, map) => {204 cb(reciever.get(key), key, map)205 })206 },207 get: state => key => {208 const value = latest(state).get(key)173 size: state => latest(state).size,174 has: state => key => latest(state).has(key),175 set: state => (key, value) => {176 if (latest(state).get(key) !== value) {177 prepareCopy(state)178 markChanged(state)179 state.assigned.set(key, true)180 state.copy.set(key, value)181 }182 return state.draft183 },184 delete: state => key => {185 prepareCopy(state)186 markChanged(state)187 state.assigned.set(key, false)188 state.copy.delete(key)189 return false190 },191 clear: state => () => {192 if (!state.copy) {193 prepareCopy(state)194 }195 markChanged(state)196 state.assigned = new Map()197 for (const key of latest(state).keys()) {198 state.assigned.set(key, false)199 }200 return state.copy.clear()201 },202 forEach: (state, key, reciever) => cb => {203 latest(state).forEach((value, key, map) => {204 cb(reciever.get(key), key, map)205 })206 },207 get: state => key => {208 const value = latest(state).get(key)209210 if (state.finalizing || state.finalized || !isDraftable(value)) {211 return value212 }210 if (state.finalizing || state.finalized || !isDraftable(value)) {211 return value212 }213214 if (value !== state.base.get(key)) {215 return value216 }217 const draft = createProxy(value, state)218 prepareCopy(state)219 state.copy.set(key, draft)220 return draft221 },222 keys: state => () => latest(state).keys(),223 values: iterateMapValues,224 entries: iterateMapValues214 if (value !== state.base.get(key)) {215 return value216 }217 const draft = createProxy(value, state)218 prepareCopy(state)219 state.copy.set(key, draft)220 return draft221 },222 keys: state => () => latest(state).keys(),223 values: iterateMapValues,224 entries: iterateMapValues225})226227function proxySet(target) {228 Object.defineProperties(target, setTraps)228 Object.defineProperties(target, setTraps)229230 if (typeof Symbol !== undefined) {231 Object.defineProperty(232 target,233 Symbol.iterator,234 proxyMethod(iterateSetValues)235 )236 }230 if (typeof Symbol !== undefined) {231 Object.defineProperty(232 target,233 Symbol.iterator,234 proxyMethod(iterateSetValues)235 )236 }237}238239const iterateSetValues = makeIterateSetValues(createProxy)240241const setTraps = finalizeTraps({242 size: state => {243 return latest(state).size244 },245 add: state => value => {246 if (!latest(state).has(value)) {247 markChanged(state)248 if (!state.copy) {249 prepareCopy(state)250 }251 state.copy.add(value)252 }253 return state.draft254 },255 delete: state => value => {256 markChanged(state)257 if (!state.copy) {258 prepareCopy(state)259 }260 return state.copy.delete(value)261 },262 has: state => key => {263 return latest(state).has(key)264 },265 clear: state => () => {266 markChanged(state)267 if (!state.copy) {268 prepareCopy(state)269 }270 return state.copy.clear()271 },272 keys: iterateSetValues,273 entries: iterateSetValues,274 values: iterateSetValues,275 forEach: state => (cb, thisArg) => {276 const iterator = iterateSetValues(state)()277 let result = iterator.next()278 while (!result.done) {279 cb.call(thisArg, result.value, result.value, state.draft)280 result = iterator.next()281 }282 }242 size: state => {243 return latest(state).size244 },245 add: state => value => {246 if (!latest(state).has(value)) {247 markChanged(state)248 if (!state.copy) {249 prepareCopy(state)250 }251 state.copy.add(value)252 }253 return state.draft254 },255 delete: state => value => {256 markChanged(state)257 if (!state.copy) {258 prepareCopy(state)259 }260 return state.copy.delete(value)261 },262 has: state => key => {263 return latest(state).has(key)264 },265 clear: state => () => {266 markChanged(state)267 if (!state.copy) {268 prepareCopy(state)269 }270 return state.copy.clear()271 },272 keys: iterateSetValues,273 entries: iterateSetValues,274 values: iterateSetValues,275 forEach: state => (cb, thisArg) => {276 const iterator = iterateSetValues(state)()277 let result = iterator.next()278 while (!result.done) {279 cb.call(thisArg, result.value, result.value, state.draft)280 result = iterator.next()281 }282 }283})284285function finalizeTraps(traps) {286 return Object.keys(traps).reduce(function(acc, key) {287 const builder = key === "size" ? proxyAttr : proxyMethod288 acc[key] = builder(traps[key], key)289 return acc290 }, {})286 return Object.keys(traps).reduce(function(acc, key) {287 const builder = key === "size" ? proxyAttr : proxyMethod288 acc[key] = builder(traps[key], key)289 return acc290 }, {})291}292293function proxyAttr(fn) {294 return {295 get() {296 const state = this[DRAFT_STATE]297 assertUnrevoked(state)298 return fn(state)299 }300 }294 return {295 get() {296 const state = this[DRAFT_STATE]297 assertUnrevoked(state)298 return fn(state)299 }300 }301}302303function proxyMethod(trap, key) {304 return {305 get() {306 return (...args) => {307 const state = this[DRAFT_STATE]308 assertUnrevoked(state)309 return trap(state, key, state.draft)(...args)310 }311 }312 }304 return {305 get() {306 return (...args) => {307 const state = this[DRAFT_STATE]308 assertUnrevoked(state)309 return trap(state, key, state.draft)(...args)310 }311 }312 }313}314315function assertUnrevoked(state) {316 if (state.revoked === true)317 throw new Error(318 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +319 JSON.stringify(latest(state))320 )316 if (state.revoked === true)317 throw new Error(318 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +319 JSON.stringify(latest(state))320 )321}322323// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.324function markChangesSweep(drafts) {325 // The natural order of drafts in the `scope` array is based on when they326 // were accessed. By processing drafts in reverse natural order, we have a327 // better chance of processing leaf nodes first. When a leaf node is known to328 // have changed, we can avoid any traversal of its ancestor nodes.329 for (let i = drafts.length - 1; i >= 0; i--) {330 const state = drafts[i][DRAFT_STATE]331 if (!state.modified) {332 if (Array.isArray(state.base)) {333 if (hasArrayChanges(state)) markChanged(state)334 } else if (isMap(state.base)) {335 if (hasMapChanges(state)) markChanged(state)336 } else if (isSet(state.base)) {337 if (hasSetChanges(state)) markChanged(state)338 } else if (hasObjectChanges(state)) {339 markChanged(state)340 }341 }342 }325 // The natural order of drafts in the `scope` array is based on when they326 // were accessed. By processing drafts in reverse natural order, we have a327 // better chance of processing leaf nodes first. When a leaf node is known to328 // have changed, we can avoid any traversal of its ancestor nodes.329 for (let i = drafts.length - 1; i >= 0; i--) {330 const state = drafts[i][DRAFT_STATE]331 if (!state.modified) {332 if (Array.isArray(state.base)) {333 if (hasArrayChanges(state)) markChanged(state)334 } else if (isMap(state.base)) {335 if (hasMapChanges(state)) markChanged(state)336 } else if (isSet(state.base)) {337 if (hasSetChanges(state)) markChanged(state)338 } else if (hasObjectChanges(state)) {339 markChanged(state)340 }341 }342 }343}344345function markChangesRecursively(object) {346 if (!object || typeof object !== "object") return347 const state = object[DRAFT_STATE]348 if (!state) return349 const {base, draft, assigned} = state350 if (!Array.isArray(object)) {351 // Look for added keys.352 Object.keys(draft).forEach(key => {353 // The `undefined` check is a fast path for pre-existing keys.354 if (base[key] === undefined && !has(base, key)) {355 assigned[key] = true356 markChanged(state)357 } else if (!assigned[key]) {358 // Only untouched properties trigger recursion.359 markChangesRecursively(draft[key])360 }361 })362 // Look for removed keys.363 Object.keys(base).forEach(key => {364 // The `undefined` check is a fast path for pre-existing keys.365 if (draft[key] === undefined && !has(draft, key)) {366 assigned[key] = false367 markChanged(state)368 }369 })370 } else if (hasArrayChanges(state)) {371 markChanged(state)372 assigned.length = true373 if (draft.length < base.length) {374 for (let i = draft.length; i < base.length; i++) assigned[i] = false375 } else {376 for (let i = base.length; i < draft.length; i++) assigned[i] = true377 }378 for (let i = 0; i < draft.length; i++) {379 // Only untouched indices trigger recursion.380 if (assigned[i] === undefined) markChangesRecursively(draft[i])381 }382 }346 if (!object || typeof object !== "object") return347 const state = object[DRAFT_STATE]348 if (!state) return349 const {base, draft, assigned} = state350 if (!Array.isArray(object)) {351 // Look for added keys.352 Object.keys(draft).forEach(key => {353 // The `undefined` check is a fast path for pre-existing keys.354 if (base[key] === undefined && !has(base, key)) {355 assigned[key] = true356 markChanged(state)357 } else if (!assigned[key]) {358 // Only untouched properties trigger recursion.359 markChangesRecursively(draft[key])360 }361 })362 // Look for removed keys.363 Object.keys(base).forEach(key => {364 // The `undefined` check is a fast path for pre-existing keys.365 if (draft[key] === undefined && !has(draft, key)) {366 assigned[key] = false367 markChanged(state)368 }369 })370 } else if (hasArrayChanges(state)) {371 markChanged(state)372 assigned.length = true373 if (draft.length < base.length) {374 for (let i = draft.length; i < base.length; i++) assigned[i] = false375 } else {376 for (let i = base.length; i < draft.length; i++) assigned[i] = true377 }378 for (let i = 0; i < draft.length; i++) {379 // Only untouched indices trigger recursion.380 if (assigned[i] === undefined) markChangesRecursively(draft[i])381 }382 }383}384385function hasObjectChanges(state) {386 const {base, draft} = state386 const {base, draft} = state387388 // Search for added keys and changed keys. Start at the back, because389 // non-numeric keys are ordered by time of definition on the object.390 const keys = Object.keys(draft)391 for (let i = keys.length - 1; i >= 0; i--) {392 const key = keys[i]393 const baseValue = base[key]394 // The `undefined` check is a fast path for pre-existing keys.395 if (baseValue === undefined && !has(base, key)) {396 return true397 }398 // Once a base key is deleted, future changes go undetected, because its399 // descriptor is erased. This branch detects any missed changes.400 else {401 const value = draft[key]402 const state = value && value[DRAFT_STATE]403 if (state ? state.base !== baseValue : !is(value, baseValue)) {404 return true405 }406 }407 }388 // Search for added keys and changed keys. Start at the back, because389 // non-numeric keys are ordered by time of definition on the object.390 const keys = Object.keys(draft)391 for (let i = keys.length - 1; i >= 0; i--) {392 const key = keys[i]393 const baseValue = base[key]394 // The `undefined` check is a fast path for pre-existing keys.395 if (baseValue === undefined && !has(base, key)) {396 return true397 }398 // Once a base key is deleted, future changes go undetected, because its399 // descriptor is erased. This branch detects any missed changes.400 else {401 const value = draft[key]402 const state = value && value[DRAFT_STATE]403 if (state ? state.base !== baseValue : !is(value, baseValue)) {404 return true405 }406 }407 }408409 // At this point, no keys were added or changed.410 // Compare key count to determine if keys were deleted.411 return keys.length !== Object.keys(base).length409 // At this point, no keys were added or changed.410 // Compare key count to determine if keys were deleted.411 return keys.length !== Object.keys(base).length412}413414function hasArrayChanges(state) {415 const {draft} = state416 if (draft.length !== state.base.length) return true417 // See #116418 // If we first shorten the length, our array interceptors will be removed.419 // If after that new items are added, result in the same original length,420 // those last items will have no intercepting property.421 // So if there is no own descriptor on the last position, we know that items were removed and added422 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check423 // the last one424 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)425 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)426 if (descriptor && !descriptor.get) return true427 // For all other cases, we don't have to compare, as they would have been picked up by the index setters428 return false415 const {draft} = state416 if (draft.length !== state.base.length) return true417 // See #116418 // If we first shorten the length, our array interceptors will be removed.419 // If after that new items are added, result in the same original length,420 // those last items will have no intercepting property.421 // So if there is no own descriptor on the last position, we know that items were removed and added422 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check423 // the last one424 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)425 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)426 if (descriptor && !descriptor.get) return true427 // For all other cases, we don't have to compare, as they would have been picked up by the index setters428 return false429}430431function hasMapChanges(state) {432 const {base, draft} = state432 const {base, draft} = state433434 if (base.size !== draft.size) return true434 if (base.size !== draft.size) return true435436 // IE11 supports only forEach iteration437 let hasChanges = false438 draft.forEach(function(value, key) {439 if (!hasChanges) {440 hasChanges = isDraftable(value)441 ? value.modified442 : value !== base.get(key)443 }444 })445 return hasChanges436 // IE11 supports only forEach iteration437 let hasChanges = false438 draft.forEach(function(value, key) {439 if (!hasChanges) {440 hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)441 }442 })443 return hasChanges444}445446function hasSetChanges(state) {449 const {base, draft} = state447 const {base, draft} = state448451 if (base.size !== draft.size) return true449 if (base.size !== draft.size) return true450453 // IE11 supports only forEach iteration454 let hasChanges = false455 draft.forEach(function(value, key) {456 if (!hasChanges) {457 hasChanges = isDraftable(value) ? value.modified : !base.has(key)458 }459 })460 return hasChanges451 // IE11 supports only forEach iteration452 let hasChanges = false453 draft.forEach(function(value, key) {454 if (!hasChanges) {455 hasChanges = isDraftable(value) ? value.modified : !base.has(key)456 }457 })458 return hasChanges459}460461function createHiddenProperty(target, prop, value) {464 Object.defineProperty(target, prop, {465 value: value,466 enumerable: false,467 writable: true468 })462 Object.defineProperty(target, prop, {463 value: value,464 enumerable: false,465 writable: true466 })467}
modified:src/immer.js+268 added-273 removed
1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"3import {applyPatches, generatePatches} from "./patches"4import {5 assign,6 each,7 get,8 has,9 is,10 isDraft,11 isDraftable,12 isEnumerable,13 isMap,14 shallowCopy,15 DRAFT_STATE,16 NOTHING,17 isSet,18 original5 assign,6 each,7 get,8 has,9 is,10 isDraft,11 isDraftable,12 isEnumerable,13 isMap,14 shallowCopy,15 DRAFT_STATE,16 NOTHING,17 isSet,18 original19} from "./common"20import {ImmerScope} from "./scope"2122function verifyMinified() {}2324const configDefaults = {25 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",26 autoFreeze:27 typeof process !== "undefined"28 ? process.env.NODE_ENV !== "production"29 : verifyMinified.name === "verifyMinified",30 onAssign: null,31 onDelete: null,32 onCopy: null25 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",26 autoFreeze:27 typeof process !== "undefined"28 ? process.env.NODE_ENV !== "production"29 : verifyMinified.name === "verifyMinified",30 onAssign: null,31 onDelete: null,32 onCopy: null33}3435export class Immer {36 constructor(config) {37 assign(this, configDefaults, config)38 this.setUseProxies(this.useProxies)39 this.produce = this.produce.bind(this)40 }41 produce(base, recipe, patchListener) {42 // curried invocation43 if (typeof base === "function" && typeof recipe !== "function") {44 const defaultBase = recipe45 recipe = base36 constructor(config) {37 assign(this, configDefaults, config)38 this.setUseProxies(this.useProxies)39 this.produce = this.produce.bind(this)40 }41 produce(base, recipe, patchListener) {42 // curried invocation43 if (typeof base === "function" && typeof recipe !== "function") {44 const defaultBase = recipe45 recipe = base4647 const self = this48 return function curriedProduce(base = defaultBase, ...args) {49 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore50 }51 }47 const self = this48 return function curriedProduce(base = defaultBase, ...args) {49 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore50 }51 }5253 // prettier-ignore54 {53 // prettier-ignore54 {55 if (typeof recipe !== "function") {56 throw new Error("The first or second argument to `produce` must be a function")57 }58 if (patchListener !== undefined && typeof patchListener !== "function") {59 throw new Error("The third argument to `produce` must be a function or undefined")60 }61 }6263 let result63 let result6465 // Only plain objects, arrays, and "immerable classes" are drafted.66 if (isDraftable(base)) {67 const scope = ImmerScope.enter()68 const proxy = this.createProxy(base)69 let hasError = true70 try {71 result = recipe(proxy)72 hasError = false73 } finally {74 // finally instead of catch + rethrow better preserves original stack75 if (hasError) scope.revoke()76 else scope.leave()77 }78 if (result instanceof Promise) {79 return result.then(80 result => {81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 },84 error => {85 scope.revoke()86 throw error87 }88 )89 }90 scope.usePatches(patchListener)91 return this.processResult(result, scope)92 } else {93 result = recipe(base)94 if (result === undefined) return base95 return result !== NOTHING ? result : undefined96 }97 }98 createDraft(base) {99 if (!isDraftable(base)) {100 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore101 }102 const scope = ImmerScope.enter()103 const proxy = this.createProxy(base)104 proxy[DRAFT_STATE].isManual = true105 scope.leave()106 return proxy107 }108 finishDraft(draft, patchListener) {109 const state = draft && draft[DRAFT_STATE]110 if (!state || !state.isManual) {111 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore112 }113 if (state.finalized) {114 throw new Error("The given draft is already finalized") // prettier-ignore115 }116 const {scope} = state117 scope.usePatches(patchListener)118 return this.processResult(undefined, scope)119 }120 setAutoFreeze(value) {121 this.autoFreeze = value122 }123 setUseProxies(value) {124 this.useProxies = value125 assign(this, value ? modernProxy : legacyProxy)126 }127 applyPatches(base, patches) {128 // Mutate the base state when a draft is passed.129 if (isDraft(base)) {130 return applyPatches(base, patches)131 }132 // Otherwise, produce a copy of the base state.133 return this.produce(base, draft => applyPatches(draft, patches))134 }135 /** @internal */136 processResult(result, scope) {137 const baseDraft = scope.drafts[0]138 const isReplaced = result !== undefined && result !== baseDraft139 this.willFinalize(scope, result, isReplaced)140 if (isReplaced) {141 if (baseDraft[DRAFT_STATE].modified) {142 scope.revoke()143 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore144 }145 if (isDraftable(result)) {146 // Finalize the result in case it contains (or is) a subset of the draft.147 result = this.finalize(result, null, scope)148 }149 if (scope.patches) {150 scope.patches.push({151 op: "replace",152 path: [],153 value: result154 })155 scope.inversePatches.push({156 op: "replace",157 path: [],158 value: baseDraft[DRAFT_STATE].base159 })160 }161 } else {162 // Finalize the base draft.163 result = this.finalize(baseDraft, [], scope)164 }165 scope.revoke()166 if (scope.patches) {167 scope.patchListener(scope.patches, scope.inversePatches)168 }169 return result !== NOTHING ? result : undefined170 }171 /**172 * @internal173 * Finalize a draft, returning either the unmodified base state or a modified174 * copy of the base state.175 */176 finalize(draft, path, scope) {177 const state = draft[DRAFT_STATE]178 if (!state) {179 if (Object.isFrozen(draft)) return draft180 return this.finalizeTree(draft, null, scope)181 }182 // Never finalize drafts owned by another scope.183 if (state.scope !== scope) {184 return draft185 }186 if (!state.modified) {187 return state.base188 }189 if (!state.finalized) {190 state.finalized = true191 this.finalizeTree(state.draft, path, scope)65 // Only plain objects, arrays, and "immerable classes" are drafted.66 if (isDraftable(base)) {67 const scope = ImmerScope.enter()68 const proxy = this.createProxy(base)69 let hasError = true70 try {71 result = recipe(proxy)72 hasError = false73 } finally {74 // finally instead of catch + rethrow better preserves original stack75 if (hasError) scope.revoke()76 else scope.leave()77 }78 if (result instanceof Promise) {79 return result.then(80 result => {81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 },84 error => {85 scope.revoke()86 throw error87 }88 )89 }90 scope.usePatches(patchListener)91 return this.processResult(result, scope)92 } else {93 result = recipe(base)94 if (result === undefined) return base95 return result !== NOTHING ? result : undefined96 }97 }98 createDraft(base) {99 if (!isDraftable(base)) {100 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore101 }102 const scope = ImmerScope.enter()103 const proxy = this.createProxy(base)104 proxy[DRAFT_STATE].isManual = true105 scope.leave()106 return proxy107 }108 finishDraft(draft, patchListener) {109 const state = draft && draft[DRAFT_STATE]110 if (!state || !state.isManual) {111 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore112 }113 if (state.finalized) {114 throw new Error("The given draft is already finalized") // prettier-ignore115 }116 const {scope} = state117 scope.usePatches(patchListener)118 return this.processResult(undefined, scope)119 }120 setAutoFreeze(value) {121 this.autoFreeze = value122 }123 setUseProxies(value) {124 this.useProxies = value125 assign(this, value ? modernProxy : legacyProxy)126 }127 applyPatches(base, patches) {128 // Mutate the base state when a draft is passed.129 if (isDraft(base)) {130 return applyPatches(base, patches)131 }132 // Otherwise, produce a copy of the base state.133 return this.produce(base, draft => applyPatches(draft, patches))134 }135 /** @internal */136 processResult(result, scope) {137 const baseDraft = scope.drafts[0]138 const isReplaced = result !== undefined && result !== baseDraft139 this.willFinalize(scope, result, isReplaced)140 if (isReplaced) {141 if (baseDraft[DRAFT_STATE].modified) {142 scope.revoke()143 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore144 }145 if (isDraftable(result)) {146 // Finalize the result in case it contains (or is) a subset of the draft.147 result = this.finalize(result, null, scope)148 }149 if (scope.patches) {150 scope.patches.push({151 op: "replace",152 path: [],153 value: result154 })155 scope.inversePatches.push({156 op: "replace",157 path: [],158 value: baseDraft[DRAFT_STATE].base159 })160 }161 } else {162 // Finalize the base draft.163 result = this.finalize(baseDraft, [], scope)164 }165 scope.revoke()166 if (scope.patches) {167 scope.patchListener(scope.patches, scope.inversePatches)168 }169 return result !== NOTHING ? result : undefined170 }171 /**172 * @internal173 * Finalize a draft, returning either the unmodified base state or a modified174 * copy of the base state.175 */176 finalize(draft, path, scope) {177 const state = draft[DRAFT_STATE]178 if (!state) {179 if (Object.isFrozen(draft)) return draft180 return this.finalizeTree(draft, null, scope)181 }182 // Never finalize drafts owned by another scope.183 if (state.scope !== scope) {184 return draft185 }186 if (!state.modified) {187 return state.base188 }189 if (!state.finalized) {190 state.finalized = true191 this.finalizeTree(state.draft, path, scope)192193 // We cannot really delete anything inside of a Set. We can only replace the whole Set.194 if (this.onDelete && !isSet(state.base)) {195 // The `assigned` object is unreliable with ES5 drafts.196 if (this.useProxies) {197 const {assigned} = state198 each(assigned, (prop, exists) => {199 if (!exists) this.onDelete(state, prop)200 })201 } else {202 // TODO: Figure it out for Maps and Sets if we need to support ES5203 const {base, copy} = state204 each(base, prop => {205 if (!has(copy, prop)) this.onDelete(state, prop)206 })207 }208 }209 if (this.onCopy) {210 this.onCopy(state)211 }193 // We cannot really delete anything inside of a Set. We can only replace the whole Set.194 if (this.onDelete && !isSet(state.base)) {195 // The `assigned` object is unreliable with ES5 drafts.196 if (this.useProxies) {197 const {assigned} = state198 each(assigned, (prop, exists) => {199 if (!exists) this.onDelete(state, prop)200 })201 } else {202 // TODO: Figure it out for Maps and Sets if we need to support ES5203 const {base, copy} = state204 each(base, prop => {205 if (!has(copy, prop)) this.onDelete(state, prop)206 })207 }208 }209 if (this.onCopy) {210 this.onCopy(state)211 }212213 // At this point, all descendants of `state.copy` have been finalized,214 // so we can be sure that `scope.canAutoFreeze` is accurate.215 if (this.autoFreeze && scope.canAutoFreeze) {216 Object.freeze(state.copy)217 }213 // At this point, all descendants of `state.copy` have been finalized,214 // so we can be sure that `scope.canAutoFreeze` is accurate.215 if (this.autoFreeze && scope.canAutoFreeze) {216 Object.freeze(state.copy)217 }218219 if (path && scope.patches) {220 generatePatches(221 state,222 path,223 scope.patches,224 scope.inversePatches225 )226 }227 }228 return state.copy229 }230 /**231 * @internal232 * Finalize all drafts in the given state tree.233 */234 finalizeTree(root, rootPath, scope) {235 const state = root[DRAFT_STATE]236 if (state) {237 if (!this.useProxies) {238 // Create the final copy, with added keys and without deleted keys.239 state.copy = shallowCopy(state.draft, true)240 }241 root = state.copy242 }219 if (path && scope.patches) {220 generatePatches(state, path, scope.patches, scope.inversePatches)221 }222 }223 return state.copy224 }225 /**226 * @internal227 * Finalize all drafts in the given state tree.228 */229 finalizeTree(root, rootPath, scope) {230 const state = root[DRAFT_STATE]231 if (state) {232 if (!this.useProxies) {233 // Create the final copy, with added keys and without deleted keys.234 state.copy = shallowCopy(state.draft, true)235 }236 root = state.copy237 }238244 const needPatches = !!rootPath && !!scope.patches245 const finalizeProperty = (prop, value, parent) => {246 if (value === parent) {247 throw Error("Immer forbids circular references")248 }239 const needPatches = !!rootPath && !!scope.patches240 const finalizeProperty = (prop, value, parent) => {241 if (value === parent) {242 throw Error("Immer forbids circular references")243 }244250 // In the `finalizeTree` method, only the `root` object may be a draft.251 const isDraftProp = !!state && parent === root252 const isSetMember = isSet(parent)245 // In the `finalizeTree` method, only the `root` object may be a draft.246 const isDraftProp = !!state && parent === root247 const isSetMember = isSet(parent)248254 if (isDraft(value)) {255 const path =256 isDraftProp &&257 needPatches &&258 !isSetMember && // Set objects are atomic since they have no keys.259 !has(state.assigned, prop) // Skip deep patches for assigned keys.260 ? rootPath.concat(prop)261 : null249 if (isDraft(value)) {250 const path =251 isDraftProp &&252 needPatches &&253 !isSetMember && // Set objects are atomic since they have no keys.254 !has(state.assigned, prop) // Skip deep patches for assigned keys.255 ? rootPath.concat(prop)256 : null257263 // Drafts owned by `scope` are finalized here.264 value = this.finalize(value, path, scope)265 replace(parent, prop, value)258 // Drafts owned by `scope` are finalized here.259 value = this.finalize(value, path, scope)260 replace(parent, prop, value)261267 // Drafts from another scope must prevent auto-freezing.268 if (isDraft(value)) {269 scope.canAutoFreeze = false270 }262 // Drafts from another scope must prevent auto-freezing.263 if (isDraft(value)) {264 scope.canAutoFreeze = false265 }266272 // Unchanged drafts are never passed to the `onAssign` hook.273 if (isDraftProp && value === get(state.base, prop)) return274 }275 // Unchanged draft properties are ignored.276 else if (isDraftProp && is(value, get(state.base, prop))) {277 return278 }279 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.280 else if (isDraftable(value) && !Object.isFrozen(value)) {281 each(value, finalizeProperty)282 }267 // Unchanged drafts are never passed to the `onAssign` hook.268 if (isDraftProp && value === get(state.base, prop)) return269 }270 // Unchanged draft properties are ignored.271 else if (isDraftProp && is(value, get(state.base, prop))) {272 return273 }274 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.275 else if (isDraftable(value) && !Object.isFrozen(value)) {276 each(value, finalizeProperty)277 }278284 // We cannot really assign anything inside of a Set. We can only replace the whole Set.285 if (isDraftProp && this.onAssign && !isSetMember) {286 this.onAssign(state, prop, value)287 }288 }279 // We cannot really assign anything inside of a Set. We can only replace the whole Set.280 if (isDraftProp && this.onAssign && !isSetMember) {281 this.onAssign(state, prop, value)282 }283 }284290 each(root, finalizeProperty)291 return root292 }285 each(root, finalizeProperty)286 return root287 }288}289290function replace(parent, prop, value) {296 if (isMap(parent)) {297 parent.set(prop, value)298 } else if (isSet(parent)) {299 // In this case, the `prop` is actually a draft.300 parent.delete(prop)301 parent.add(value)302 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {303 // Preserve non-enumerable properties.304 parent[prop] = value305 } else {306 Object.defineProperty(parent, prop, {307 value,308 writable: true,309 configurable: true310 })311 }291 if (isMap(parent)) {292 parent.set(prop, value)293 } else if (isSet(parent)) {294 // In this case, the `prop` is actually a draft.295 parent.delete(prop)296 parent.add(value)297 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {298 // Preserve non-enumerable properties.299 parent[prop] = value300 } else {301 Object.defineProperty(parent, prop, {302 value,303 writable: true,304 configurable: true305 })306 }307}
modified:src/index.js+5 added-5 removed
61 unmodified lines
62 */63export const finishDraft = immer.finishDraft.bind(immer)6465export {66 original,67 isDraft,68 isDraftable,69 NOTHING as nothing,70 DRAFTABLE as immerable66 original,67 isDraft,68 isDraftable,69 NOTHING as nothing,70 DRAFTABLE as immerable71} from "./common"7273export {Immer}
modified:src/patches.js+169 added-173 removed
1import {get, each, isMap, isSet, has} from "./common"23export function generatePatches(state, basePath, patches, inversePatches) {4 const generatePatchesFn = Array.isArray(state.base)5 ? generateArrayPatches6 : isSet(state.base)7 ? generateSetPatches8 : generatePatchesFromAssigned4 const generatePatchesFn = Array.isArray(state.base)5 ? generateArrayPatches6 : isSet(state.base)7 ? generateSetPatches8 : generatePatchesFromAssigned910 generatePatchesFn(state, basePath, patches, inversePatches)10 generatePatchesFn(state, basePath, patches, inversePatches)11}1213function generateArrayPatches(state, basePath, patches, inversePatches) {14 let {base, copy, assigned} = state14 let {base, copy, assigned} = state1516 // Reduce complexity by ensuring `base` is never longer.17 if (copy.length < base.length) {18 ;[base, copy] = [copy, base]19 ;[patches, inversePatches] = [inversePatches, patches]20 }16 // Reduce complexity by ensuring `base` is never longer.17 if (copy.length < base.length) {18 ;[base, copy] = [copy, base]19 ;[patches, inversePatches] = [inversePatches, patches]20 }2122 const delta = copy.length - base.length22 const delta = copy.length - base.length2324 // Find the first replaced index.25 let start = 026 while (base[start] === copy[start] && start < base.length) {27 ++start28 }24 // Find the first replaced index.25 let start = 026 while (base[start] === copy[start] && start < base.length) {27 ++start28 }2930 // Find the last replaced index. Search from the end to optimize splice patches.31 let end = base.length32 while (end > start && base[end - 1] === copy[end + delta - 1]) {33 --end34 }30 // Find the last replaced index. Search from the end to optimize splice patches.31 let end = base.length32 while (end > start && base[end - 1] === copy[end + delta - 1]) {33 --end34 }3536 // Process replaced indices.37 for (let i = start; i < end; ++i) {38 if (assigned[i] && copy[i] !== base[i]) {39 const path = basePath.concat([i])40 patches.push({41 op: "replace",42 path,43 value: copy[i]44 })45 inversePatches.push({46 op: "replace",47 path,48 value: base[i]49 })50 }51 }36 // Process replaced indices.37 for (let i = start; i < end; ++i) {38 if (assigned[i] && copy[i] !== base[i]) {39 const path = basePath.concat([i])40 patches.push({41 op: "replace",42 path,43 value: copy[i]44 })45 inversePatches.push({46 op: "replace",47 path,48 value: base[i]49 })50 }51 }5253 const useRemove = end != base.length54 const replaceCount = patches.length53 const useRemove = end != base.length54 const replaceCount = patches.length5556 // Process added indices.57 for (let i = end + delta - 1; i >= end; --i) {58 const path = basePath.concat([i])59 patches[replaceCount + i - end] = {60 op: "add",61 path,62 value: copy[i]63 }64 if (useRemove) {65 inversePatches.push({66 op: "remove",67 path68 })69 }70 }56 // Process added indices.57 for (let i = end + delta - 1; i >= end; --i) {58 const path = basePath.concat([i])59 patches[replaceCount + i - end] = {60 op: "add",61 path,62 value: copy[i]63 }64 if (useRemove) {65 inversePatches.push({66 op: "remove",67 path68 })69 }70 }7172 // One "replace" patch reverses all non-splicing "add" patches.73 if (!useRemove) {74 inversePatches.push({75 op: "replace",76 path: basePath.concat(["length"]),77 value: base.length78 })79 }72 // One "replace" patch reverses all non-splicing "add" patches.73 if (!useRemove) {74 inversePatches.push({75 op: "replace",76 path: basePath.concat(["length"]),77 value: base.length78 })79 }80}8182// This is used for both Map objects and normal objects.83function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {84 const {base, copy} = state85 each(state.assigned, (key, assignedValue) => {86 const origValue = get(base, key)87 const value = get(copy, key)88 const op = !assignedValue89 ? "remove"90 : has(base, key)91 ? "replace"92 : "add"93 if (origValue === value && op === "replace") return94 const path = basePath.concat(key)95 patches.push(op === "remove" ? {op, path} : {op, path, value})96 inversePatches.push(97 op === "add"98 ? {op: "remove", path}99 : op === "remove"100 ? {op: "add", path, value: origValue}101 : {op: "replace", path, value: origValue}102 )103 })84 const {base, copy} = state85 each(state.assigned, (key, assignedValue) => {86 const origValue = get(base, key)87 const value = get(copy, key)88 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"89 if (origValue === value && op === "replace") return90 const path = basePath.concat(key)91 patches.push(op === "remove" ? {op, path} : {op, path, value})92 inversePatches.push(93 op === "add"94 ? {op: "remove", path}95 : op === "remove"96 ? {op: "add", path, value: origValue}97 : {op: "replace", path, value: origValue}98 )99 })100}101102function generateSetPatches(state, basePath, patches, inversePatches) {107 let {base, copy} = state103 let {base, copy} = state104109 let i = 0110 for (const value of base) {111 if (!copy.has(value)) {112 const path = basePath.concat([i])113 patches.push({114 op: "remove",115 path,116 value117 })118 inversePatches.unshift({119 op: "add",120 path,121 value122 })123 }124 i++125 }126 i = 0127 for (const value of copy) {128 if (!base.has(value)) {129 const path = basePath.concat([i])130 patches.push({131 op: "add",132 path,133 value134 })135 inversePatches.unshift({136 op: "remove",137 path,138 value139 })140 }141 i++142 }105 let i = 0106 for (const value of base) {107 if (!copy.has(value)) {108 const path = basePath.concat([i])109 patches.push({110 op: "remove",111 path,112 value113 })114 inversePatches.unshift({115 op: "add",116 path,117 value118 })119 }120 i++121 }122 i = 0123 for (const value of copy) {124 if (!base.has(value)) {125 const path = basePath.concat([i])126 patches.push({127 op: "add",128 path,129 value130 })131 inversePatches.unshift({132 op: "remove",133 path,134 value135 })136 }137 i++138 }139}140141export function applyPatches(draft, patches) {146 for (let i = 0; i < patches.length; i++) {147 const patch = patches[i]148 const {path} = patch149 if (path.length === 0 && patch.op === "replace") {150 draft = patch.value151 } else {152 let base = draft153 for (let i = 0; i < path.length - 1; i++) {154 base = get(base, path[i])155 if (!base || typeof base !== "object")142 for (let i = 0; i < patches.length; i++) {143 const patch = patches[i]144 const {path} = patch145 if (path.length === 0 && patch.op === "replace") {146 draft = patch.value147 } else {148 let base = draft149 for (let i = 0; i < path.length - 1; i++) {150 base = get(base, path[i])151 if (!base || typeof base !== "object")152 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore157 }158 const key = path[path.length - 1]153 }154 const key = path[path.length - 1]155160 const replace = (key, value) => {161 if (isMap(base)) {162 base.set(key, value)163 return164 }165 if (isSet(base)) {166 throw new Error('Sets cannot have "replace" patches.')167 }168 base[key] = value169 }170 const add = (key, value) =>171 Array.isArray(base)172 ? base.splice(key, 0, value)173 : isMap(base)174 ? base.set(key, value)175 : isSet(base)176 ? base.add(value)177 : (base[key] = value)178 const remove = (key, value) =>179 Array.isArray(base)180 ? base.splice(key, 1)181 : isMap(base)182 ? base.delete(key)183 : isSet(base)184 ? base.delete(value)185 : delete base[key]156 const replace = (key, value) => {157 if (isMap(base)) {158 base.set(key, value)159 return160 }161 if (isSet(base)) {162 throw new Error('Sets cannot have "replace" patches.')163 }164 base[key] = value165 }166 const add = (key, value) =>167 Array.isArray(base)168 ? base.splice(key, 0, value)169 : isMap(base)170 ? base.set(key, value)171 : isSet(base)172 ? base.add(value)173 : (base[key] = value)174 const remove = (key, value) =>175 Array.isArray(base)176 ? base.splice(key, 1)177 : isMap(base)178 ? base.delete(key)179 : isSet(base)180 ? base.delete(value)181 : delete base[key]182187 switch (patch.op) {188 case "replace":189 replace(key, patch.value)190 break191 case "add":192 add(key, patch.value)193 break194 case "remove":195 remove(key, patch.value)196 break197 default:198 throw new Error("Unsupported patch operation: " + patch.op)199 }200 }201 }202 return draft183 switch (patch.op) {184 case "replace":185 replace(key, patch.value)186 break187 case "add":188 add(key, patch.value)189 break190 case "remove":191 remove(key, patch.value)192 break193 default:194 throw new Error("Unsupported patch operation: " + patch.op)195 }196 }197 }198 return draft199}
modified:src/proxy.js+275 added-275 removed
1"use strict"2import {3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 shallowCopy,12 makeIterable,13 DRAFT_STATE,14 assignMap,15 assignSet,16 original,17 iterateMapValues,18 makeIterateSetValues3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 shallowCopy,12 makeIterable,13 DRAFT_STATE,14 assignMap,15 assignSet,16 original,17 iterateMapValues,18 makeIterateSetValues19} from "./common"20import {ImmerScope} from "./scope"2122// Do nothing before being finalized.
4 unmodified lines
27 *28 * The second argument is the parent draft-state (used internally).29 */30export function createProxy(base, parent) {31 const scope = parent ? parent.scope : ImmerScope.current32 const state = {33 // Track which produce call this is associated with.34 scope,35 // True for both shallow and deep changes.36 modified: false,37 // Used during finalization.38 finalized: false,39 // Track which properties have been assigned (true) or deleted (false).40 assigned: {},41 // The parent draft state.42 parent,43 // The base state.44 base,45 // The base proxy.46 draft: null,47 // Any property proxies.48 drafts: {},49 // The base copy with any updated values.50 copy: null,51 // Called by the `produce` function.52 revoke: null53 }31 const scope = parent ? parent.scope : ImmerScope.current32 const state = {33 // Track which produce call this is associated with.34 scope,35 // True for both shallow and deep changes.36 modified: false,37 // Used during finalization.38 finalized: false,39 // Track which properties have been assigned (true) or deleted (false).40 assigned: {},41 // The parent draft state.42 parent,43 // The base state.44 base,45 // The base proxy.46 draft: null,47 // Any property proxies.48 drafts: {},49 // The base copy with any updated values.50 copy: null,51 // Called by the `produce` function.52 revoke: null53 }5455 let target = state56 let traps = objectTraps57 if (Array.isArray(base)) {58 target = [state]59 traps = arrayTraps60 }61 // Map drafts must support object keys, so we use Map objects to track changes.62 else if (isMap(base)) {63 traps = mapTraps64 state.drafts = new Map()65 state.assigned = new Map()66 }67 // Set drafts use a Map object to track which of its values are drafted.68 // And we don't need the "assigned" property, because Set objects have no keys.69 else if (isSet(base)) {70 traps = setTraps71 state.drafts = new Map()72 }55 let target = state56 let traps = objectTraps57 if (Array.isArray(base)) {58 target = [state]59 traps = arrayTraps60 }61 // Map drafts must support object keys, so we use Map objects to track changes.62 else if (isMap(base)) {63 traps = mapTraps64 state.drafts = new Map()65 state.assigned = new Map()66 }67 // Set drafts use a Map object to track which of its values are drafted.68 // And we don't need the "assigned" property, because Set objects have no keys.69 else if (isSet(base)) {70 traps = setTraps71 state.drafts = new Map()72 }7374 const {revoke, proxy} = Proxy.revocable(target, traps)74 const {revoke, proxy} = Proxy.revocable(target, traps)7576 state.draft = proxy77 state.revoke = revoke76 state.draft = proxy77 state.revoke = revoke7879 scope.drafts.push(proxy)80 return proxy79 scope.drafts.push(proxy)80 return proxy81}8283/**84 * Object drafts85 */8687const objectTraps = {88 get(state, prop) {89 if (prop === DRAFT_STATE) return state90 let {drafts} = state88 get(state, prop) {89 if (prop === DRAFT_STATE) return state90 let {drafts} = state9192 // Check for existing draft in unmodified state.93 if (!state.modified && has(drafts, prop)) {94 return drafts[prop]95 }92 // Check for existing draft in unmodified state.93 if (!state.modified && has(drafts, prop)) {94 return drafts[prop]95 }9697 const value = latest(state)[prop]98 if (state.finalized || !isDraftable(value)) {99 return value100 }97 const value = latest(state)[prop]98 if (state.finalized || !isDraftable(value)) {99 return value100 }101102 // Check for existing draft in modified state.103 if (state.modified) {104 // Assigned values are never drafted. This catches any drafts we created, too.105 if (value !== peek(state.base, prop)) return value106 // Store drafts on the copy (when one exists).107 drafts = state.copy108 }102 // Check for existing draft in modified state.103 if (state.modified) {104 // Assigned values are never drafted. This catches any drafts we created, too.105 if (value !== peek(state.base, prop)) return value106 // Store drafts on the copy (when one exists).107 drafts = state.copy108 }109110 return (drafts[prop] = createProxy(value, state))111 },112 has(state, prop) {113 return prop in latest(state)114 },115 ownKeys(state) {116 return Reflect.ownKeys(latest(state))117 },118 set(state, prop, value) {119 if (!state.modified) {120 const baseValue = peek(state.base, prop)121 // Optimize based on value's truthiness. Truthy values are guaranteed to122 // never be undefined, so we can avoid the `in` operator. Lastly, truthy123 // values may be drafts, but falsy values are never drafts.124 const isUnchanged = value125 ? is(baseValue, value) || value === state.drafts[prop]126 : is(baseValue, value) && prop in state.base127 if (isUnchanged) return true128 markChanged(state)129 }130 state.assigned[prop] = true131 state.copy[prop] = value132 return true133 },134 deleteProperty(state, prop) {135 // The `undefined` check is a fast path for pre-existing keys.136 if (peek(state.base, prop) !== undefined || prop in state.base) {137 state.assigned[prop] = false138 markChanged(state)139 }140 if (state.copy) delete state.copy[prop]141 return true142 },143 // Note: We never coerce `desc.value` into an Immer draft, because we can't make144 // the same guarantee in ES5 mode.145 getOwnPropertyDescriptor(state, prop) {146 const owner = latest(state)147 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)148 if (desc) {149 desc.writable = true150 desc.configurable = !Array.isArray(owner) || prop !== "length"151 }152 return desc153 },154 defineProperty() {155 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore156 },157 getPrototypeOf(state) {158 return Object.getPrototypeOf(state.base)159 },160 setPrototypeOf() {161 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore162 }110 return (drafts[prop] = createProxy(value, state))111 },112 has(state, prop) {113 return prop in latest(state)114 },115 ownKeys(state) {116 return Reflect.ownKeys(latest(state))117 },118 set(state, prop, value) {119 if (!state.modified) {120 const baseValue = peek(state.base, prop)121 // Optimize based on value's truthiness. Truthy values are guaranteed to122 // never be undefined, so we can avoid the `in` operator. Lastly, truthy123 // values may be drafts, but falsy values are never drafts.124 const isUnchanged = value125 ? is(baseValue, value) || value === state.drafts[prop]126 : is(baseValue, value) && prop in state.base127 if (isUnchanged) return true128 markChanged(state)129 }130 state.assigned[prop] = true131 state.copy[prop] = value132 return true133 },134 deleteProperty(state, prop) {135 // The `undefined` check is a fast path for pre-existing keys.136 if (peek(state.base, prop) !== undefined || prop in state.base) {137 state.assigned[prop] = false138 markChanged(state)139 }140 if (state.copy) delete state.copy[prop]141 return true142 },143 // Note: We never coerce `desc.value` into an Immer draft, because we can't make144 // the same guarantee in ES5 mode.145 getOwnPropertyDescriptor(state, prop) {146 const owner = latest(state)147 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)148 if (desc) {149 desc.writable = true150 desc.configurable = !Array.isArray(owner) || prop !== "length"151 }152 return desc153 },154 defineProperty() {155 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore156 },157 getPrototypeOf(state) {158 return Object.getPrototypeOf(state.base)159 },160 setPrototypeOf() {161 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore162 }163}164165/**166 * Array drafts167 */168169const arrayTraps = {}170each(objectTraps, (key, fn) => {171 arrayTraps[key] = function() {172 arguments[0] = arguments[0][0]173 return fn.apply(this, arguments)174 }171 arrayTraps[key] = function() {172 arguments[0] = arguments[0][0]173 return fn.apply(this, arguments)174 }175})176arrayTraps.deleteProperty = function(state, prop) {177 if (isNaN(parseInt(prop))) {178 throw new Error("Immer only supports deleting array indices") // prettier-ignore179 }180 return objectTraps.deleteProperty.call(this, state[0], prop)177 if (isNaN(parseInt(prop))) {178 throw new Error("Immer only supports deleting array indices") // prettier-ignore179 }180 return objectTraps.deleteProperty.call(this, state[0], prop)181}182arrayTraps.set = function(state, prop, value) {183 if (prop !== "length" && isNaN(parseInt(prop))) {184 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore185 }186 return objectTraps.set.call(this, state[0], prop, value)183 if (prop !== "length" && isNaN(parseInt(prop))) {184 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore185 }186 return objectTraps.set.call(this, state[0], prop, value)187}188189// Used by Map and Set drafts190const reflectTraps = makeReflectTraps([191 "ownKeys",192 "has",193 "set",194 "deleteProperty",195 "defineProperty",196 "getOwnPropertyDescriptor",197 "preventExtensions",198 "isExtensible",199 "getPrototypeOf"191 "ownKeys",192 "has",193 "set",194 "deleteProperty",195 "defineProperty",196 "getOwnPropertyDescriptor",197 "preventExtensions",198 "isExtensible",199 "getPrototypeOf"200])201202/**203 * Map drafts204 */205206const mapTraps = makeTrapsForGetters({207 [DRAFT_STATE]: state => state,208 size: state => latest(state).size,209 has: state => key => latest(state).has(key),210 set: state => (key, value) => {211 const values = latest(state)212 if (!values.has(key) || values.get(key) !== value) {213 markChanged(state)214 state.assigned.set(key, true)215 state.copy.set(key, value)216 }217 return state.draft218 },219 delete: state => key => {220 if (latest(state).has(key)) {221 markChanged(state)222 state.assigned.set(key, false)223 return state.copy.delete(key)224 }225 return false226 },227 clear: state => () => {228 markChanged(state)229 state.assigned = new Map()230 for (const key of latest(state).keys()) {231 state.assigned.set(key, false)232 }233 return state.copy.clear()234 },235 forEach: (state, _, receiver) => (cb, thisArg) =>236 latest(state).forEach((_, key, map) => {237 const value = receiver.get(key)238 cb.call(thisArg, value, key, map)239 }),240 get: state => key => {241 const drafts = state[state.modified ? "copy" : "drafts"]242 if (drafts.has(key)) {243 return drafts.get(key)244 }207 [DRAFT_STATE]: state => state,208 size: state => latest(state).size,209 has: state => key => latest(state).has(key),210 set: state => (key, value) => {211 const values = latest(state)212 if (!values.has(key) || values.get(key) !== value) {213 markChanged(state)214 state.assigned.set(key, true)215 state.copy.set(key, value)216 }217 return state.draft218 },219 delete: state => key => {220 if (latest(state).has(key)) {221 markChanged(state)222 state.assigned.set(key, false)223 return state.copy.delete(key)224 }225 return false226 },227 clear: state => () => {228 markChanged(state)229 state.assigned = new Map()230 for (const key of latest(state).keys()) {231 state.assigned.set(key, false)232 }233 return state.copy.clear()234 },235 forEach: (state, _, receiver) => (cb, thisArg) =>236 latest(state).forEach((_, key, map) => {237 const value = receiver.get(key)238 cb.call(thisArg, value, key, map)239 }),240 get: state => key => {241 const drafts = state[state.modified ? "copy" : "drafts"]242 if (drafts.has(key)) {243 return drafts.get(key)244 }245246 const value = latest(state).get(key)247 if (state.finalized || !isDraftable(value)) {248 return value249 }246 const value = latest(state).get(key)247 if (state.finalized || !isDraftable(value)) {248 return value249 }250251 const draft = createProxy(value, state)252 drafts.set(key, draft)253 return draft254 },255 keys: state => () => latest(state).keys(),256 values: iterateMapValues,257 entries: iterateMapValues,258 [Symbol.iterator]: iterateMapValues251 const draft = createProxy(value, state)252 drafts.set(key, draft)253 return draft254 },255 keys: state => () => latest(state).keys(),256 values: iterateMapValues,257 entries: iterateMapValues,258 [Symbol.iterator]: iterateMapValues259})260261const iterateSetValues = makeIterateSetValues(createProxy)262/**263 * Set drafts264 */265266const setTraps = makeTrapsForGetters({267 [DRAFT_STATE]: state => state,268 size: state => latest(state).size,269 has: state => key => latest(state).has(key),270 add: state => value => {271 if (!latest(state).has(value)) {272 markChanged(state)273 state.copy.add(value)274 }275 return state.draft276 },277 delete: state => value => {278 markChanged(state)279 return state.copy.delete(value)280 },281 clear: state => () => {282 markChanged(state)283 return state.copy.clear()284 },285 forEach: state => (cb, thisArg) => {286 const iterator = iterateSetValues(state)()287 let result = iterator.next()288 while (!result.done) {289 cb.call(thisArg, result.value, result.value, state.draft)290 result = iterator.next()291 }292 },293 keys: iterateSetValues,294 values: iterateSetValues,295 entries: iterateSetValues,296 [Symbol.iterator]: iterateSetValues267 [DRAFT_STATE]: state => state,268 size: state => latest(state).size,269 has: state => key => latest(state).has(key),270 add: state => value => {271 if (!latest(state).has(value)) {272 markChanged(state)273 state.copy.add(value)274 }275 return state.draft276 },277 delete: state => value => {278 markChanged(state)279 return state.copy.delete(value)280 },281 clear: state => () => {282 markChanged(state)283 return state.copy.clear()284 },285 forEach: state => (cb, thisArg) => {286 const iterator = iterateSetValues(state)()287 let result = iterator.next()288 while (!result.done) {289 cb.call(thisArg, result.value, result.value, state.draft)290 result = iterator.next()291 }292 },293 keys: iterateSetValues,294 values: iterateSetValues,295 entries: iterateSetValues,296 [Symbol.iterator]: iterateSetValues297})298299/**300 * Helpers301 */302303// Retrieve the latest values of the draft.304function latest(state) {305 return state.copy || state.base305 return state.copy || state.base306}307308// Access a property without creating an Immer draft.309function peek(draft, prop) {310 const state = draft[DRAFT_STATE]311 const desc = Reflect.getOwnPropertyDescriptor(312 state ? latest(state) : draft,313 prop314 )315 return desc && desc.value310 const state = draft[DRAFT_STATE]311 const desc = Reflect.getOwnPropertyDescriptor(312 state ? latest(state) : draft,313 prop314 )315 return desc && desc.value316}317318function markChanged(state) {319 if (!state.modified) {320 state.modified = true319 if (!state.modified) {320 state.modified = true321322 const {base, drafts, parent} = state323 const copy = shallowCopy(base)322 const {base, drafts, parent} = state323 const copy = shallowCopy(base)324325 if (isSet(base)) {326 // Note: The `drafts` property is preserved for Set objects, since327 // we need to keep track of which values are drafted.328 assignSet(copy, drafts)329 } else {330 // Merge nested drafts into the copy.331 if (isMap(base)) assignMap(copy, drafts)332 else assign(copy, drafts)333 state.drafts = null334 }325 if (isSet(base)) {326 // Note: The `drafts` property is preserved for Set objects, since327 // we need to keep track of which values are drafted.328 assignSet(copy, drafts)329 } else {330 // Merge nested drafts into the copy.331 if (isMap(base)) assignMap(copy, drafts)332 else assign(copy, drafts)333 state.drafts = null334 }335336 state.copy = copy337 if (parent) {338 markChanged(parent)339 }340 }336 state.copy = copy337 if (parent) {338 markChanged(parent)339 }340 }341}342343/** Create traps that all use the `Reflect` API on the `latest(state)` */344function makeReflectTraps(names) {345 return names.reduce((traps, name) => {346 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)347 return traps348 }, {})345 return names.reduce((traps, name) => {346 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)347 return traps348 }, {})349}350351function makeTrapsForGetters(getters) {352 return {353 ...reflectTraps,354 get(state, prop, receiver) {355 return getters.hasOwnProperty(prop)356 ? getters[prop](state, prop, receiver)357 : Reflect.get(state, prop, receiver)358 },359 setPrototypeOf(state) {360 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore361 }362 }352 return {353 ...reflectTraps,354 get(state, prop, receiver) {355 return getters.hasOwnProperty(prop)356 ? getters[prop](state, prop, receiver)357 : Reflect.get(state, prop, receiver)358 },359 setPrototypeOf(state) {360 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore361 }362 }363}
modified:src/scope.js+28 added-28 removed
1import {DRAFT_STATE} from "./common"23/** Each scope represents a `produce` call. */4export class ImmerScope {5 constructor(parent) {6 this.drafts = []7 this.parent = parent5 constructor(parent) {6 this.drafts = []7 this.parent = parent89 // Whenever the modified draft contains a draft from another scope, we10 // need to prevent auto-freezing so the unowned draft can be finalized.11 this.canAutoFreeze = true9 // Whenever the modified draft contains a draft from another scope, we10 // need to prevent auto-freezing so the unowned draft can be finalized.11 this.canAutoFreeze = true1213 // To avoid prototype lookups:14 this.patches = null15 }16 usePatches(patchListener) {17 if (patchListener) {18 this.patches = []19 this.inversePatches = []20 this.patchListener = patchListener21 }22 }23 revoke() {24 this.leave()25 this.drafts.forEach(revoke)26 this.drafts = null // Make draft-related methods throw.27 }28 leave() {29 if (this === ImmerScope.current) {30 ImmerScope.current = this.parent31 }32 }13 // To avoid prototype lookups:14 this.patches = null15 }16 usePatches(patchListener) {17 if (patchListener) {18 this.patches = []19 this.inversePatches = []20 this.patchListener = patchListener21 }22 }23 revoke() {24 this.leave()25 this.drafts.forEach(revoke)26 this.drafts = null // Make draft-related methods throw.27 }28 leave() {29 if (this === ImmerScope.current) {30 ImmerScope.current = this.parent31 }32 }33}3435ImmerScope.current = null36ImmerScope.enter = function() {37 return (this.current = new ImmerScope(this.current))37 return (this.current = new ImmerScope(this.current))38}3940function revoke(draft) {41 draft[DRAFT_STATE].revoke()41 draft[DRAFT_STATE].revoke()42}
modified:.gitignore+1 added
57 unmodified lines
58.env5960.idea61dist/62website/build
modified:.prettierrc+3 added-3 removed
3 unmodified lines
4 "proseWrap": "never",5 "requirePragma": false,6 "semi": false,7 "singleQuote": false,8 "tabWidth": 4,8 "trailingComma": "none",10 "useTabs": false,9 "useTabs": true,10 "overrides": [11 {12 "files": [".prettierrc", "*.json"],13 "options": {14 "printWidth": 200,16 "tabWidth": 215 "tabWidth": 2,16 "useTabs": false17 }18 }19 ]20}