Skip to content
Myr

Merge branch 'patches'

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 · parents d0fd57f, d60eea0 · Browse files · 17 files+1350 added−344 removed
This commit

State

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

Diff stats

17 files+1350 added−344 removed

  • tests:+949 added−321 removed
  • other:+401 added−23 removed

17 files+1350 added−344 removed

modified:__performance_tests__/todo.js+38 added
192 unmodified lines
193 }194)195196measure(197 "immer (proxy) - without autofreeze - with patch listener",198 () => {199 setUseProxies(true)200 setAutoFreeze(false)201 },202 () => {203 produce(204 baseState,205 draft => {206 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {207 draft[i].done = true208 }209 },210 function() {}211 )212 }213)214215measure(216 "immer (es5) - without autofreeze",217 () => {218 setUseProxies(false)219 setAutoFreeze(false)
20 unmodified lines
240 }241 })242 }243)244245measure(246 "immer (es5) - without autofreeze - with patch listener",247 () => {248 setUseProxies(false)249 setAutoFreeze(false)250 },251 () => {252 produce(253 baseState,254 draft => {255 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {256 draft[i].done = true257 }258 },259 function() {}260 )261 }262)
modified:__tests__/flow/flow.js.flow+9 added-1 removed
1// @flow2import produce, {setAutoFreeze, setUseProxies, produce as produce2} from "../../src/immer"2import produce, {setAutoFreeze, setUseProxies, produce as produce2, applyPatches, Patch} from "../../src/immer"34setAutoFreeze(true)5setUseProxies(true)6
77 unmodified lines
8485 // $ExpectError86 console.log(draft.y)87 })88}8990{91 let p: Patch[] = []92 produce({ }, d=> {}, (patches, inverse) => {93 p = patches94 })95 applyPatches({}, p)96}
modified:__tests__/base.js+612 added-316 removed
6 unmodified lines
7jest.setTimeout(1000)89runBaseTest("proxy (no freeze)", true, false)10runBaseTest("proxy (autofreeze)", true, true)11runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)12runBaseTest("es5 (no freeze)", false, false)13runBaseTest("es5 (autofreeze)", false, true)14runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)1514function runBaseTest(name, useProxies, freeze) {16function runBaseTest(name, useProxies, freeze, useListener) {17 describe(`base functionality - ${name}`, () => {18 let baseState19 let origBaseState20 // make sure logic doesn't break when listener is attached21 let listener = useListener ? function() {} : undefined2223 beforeEach(() => {24 setAutoFreeze(freeze)25 setUseProxies(useProxies)26 origBaseState = baseState = createBaseState()27 })2829 it("should return the original without modifications", () => {26 const nextState = produce(baseState, () => {})30 const nextState = produce(baseState, () => {}, listener)31 expect(nextState).toBe(baseState)32 })3334 it("should return the original without modifications when reading stuff", () => {31 const nextState = produce(baseState, s => {32 expect(s.aProp).toBe("hi")33 expect(s.anObject.nested).toMatchObject({yummie: true})34 })35 const nextState = produce(36 baseState,37 s => {38 expect(s.aProp).toBe("hi")39 expect(s.anObject.nested).toMatchObject({yummie: true})40 },41 listener42 )43 expect(nextState).toBe(baseState)44 })4546 it("should return a copy when modifying stuff", () => {39 const nextState = produce(baseState, s => {40 s.aProp = "hello world"41 })47 const nextState = produce(48 baseState,49 s => {50 s.aProp = "hello world"51 },52 listener53 )54 expect(nextState).not.toBe(baseState)55 expect(baseState.aProp).toBe("hi")56 expect(nextState.aProp).toBe("hello world")57 // structural sharing?58 expect(nextState.nested).toBe(baseState.nested)59 })6061 it("should preserve type", () => {62 const nextState = produce(63 baseState,50 const nextState = produce(baseState, s => {51 expect(Object.getPrototypeOf(s)).toBe(Object.prototype)52 expect(Array.isArray(s.anArray)).toBe(true)53 s.anArray.push(3)54 s.aProp = "hello world"55 expect(Object.getPrototypeOf(s)).toBe(Object.prototype)56 expect(Array.isArray(s.anArray)).toBe(true)57 })64 s => {65 expect(Object.getPrototypeOf(s)).toBe(Object.prototype)66 expect(Array.isArray(s.anArray)).toBe(true)67 s.anArray.push(3)68 s.aProp = "hello world"69 expect(Object.getPrototypeOf(s)).toBe(Object.prototype)70 expect(Array.isArray(s.anArray)).toBe(true)71 },72 listener73 )74 expect(Object.getPrototypeOf(nextState)).toBe(Object.prototype)75 expect(Array.isArray(nextState.anArray)).toBe(true)76 })7778 it("deep change bubbles up", () => {63 const nextState = produce(baseState, s => {64 s.anObject.nested.yummie = false65 })79 const nextState = produce(80 baseState,81 s => {82 s.anObject.nested.yummie = false83 },84 listener85 )86 expect(nextState).not.toBe(baseState)87 expect(nextState.anObject).not.toBe(baseState.anObject)88 expect(baseState.anObject.nested.yummie).toBe(true)89 expect(nextState.anObject.nested.yummie).toBe(false)90 expect(nextState.anArray).toBe(baseState.anArray)91 })9293 it("can add props", () => {74 const nextState = produce(baseState, s => {75 s.anObject.cookie = {tasty: true}76 })94 const nextState = produce(95 baseState,96 s => {97 s.anObject.cookie = {tasty: true}98 },99 listener100 )101 expect(nextState).not.toBe(baseState)102 expect(nextState.anObject).not.toBe(baseState.anObject)103 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)104 expect(nextState.anObject.cookie).toEqual({tasty: true})105 })106107 it("can delete props", () => {84 const nextState = produce(baseState, s => {85 delete s.anObject.nested86 })108 const nextState = produce(109 baseState,110 s => {111 delete s.anObject.nested112 },113 listener114 )115 expect(nextState).not.toBe(baseState)116 expect(nextState.anObject).not.toBe(baseState.anObject)117 expect(nextState.anObject.nested).toBe(undefined)118 })119120 it("ignores single non-modification", () => {93 const nextState = produce(baseState, s => {94 s.aProp = "hi"95 })121 const nextState = produce(122 baseState,123 s => {124 s.aProp = "hi"125 },126 listener127 )128 expect(nextState).toBe(baseState)129 })130131 it("processes single modification", () => {100 const nextState = produce(baseState, s => {101 s.aProp = "hello"102 s.aProp = "hi"103 })132 const nextState = produce(133 baseState,134 s => {135 s.aProp = "hello"136 s.aProp = "hi"137 },138 listener139 )140 expect(nextState).not.toBe(baseState)141 expect(nextState).toEqual(baseState)142 })143
20 unmodified lines
164 base.x = 1165 base.y = Object.create(null)166 base.y.y = 2167 expect(base.__proto__).toBe(undefined)132 const next = produce(base, draft => {133 draft.y.z = 3134 draft.y.y++135 draft.x++136 })168 const next = produce(169 base,170 draft => {171 draft.y.z = 3172 draft.y.y++173 draft.x++174 },175 listener176 )177 expect(next).toEqual({178 x: 2,179 y: {y: 3, z: 3}180 })181 expect(next.__proto__).toBe(undefined)182 })183184 it("should support reading arrays", () => {145 const nextState = produce(baseState, s => {146 s.anArray.slice()147 })185 const nextState = produce(186 baseState,187 s => {188 s.anArray.slice()189 },190 listener191 )192 expect(nextState.anArray).toBe(baseState.anArray)193 expect(nextState).toBe(baseState)194 })195196 it("should support changing arrays", () => {153 const nextState = produce(baseState, s => {154 s.anArray[3] = true155 })197 const nextState = produce(198 baseState,199 s => {200 s.anArray[3] = true201 },202 listener203 )204 expect(nextState).not.toBe(baseState)205 expect(nextState.anArray).not.toBe(baseState.anArray)206 expect(nextState.anArray[3]).toEqual(true)207 })208209 it("should support changing arrays - 2", () => {162 const nextState = produce(baseState, s => {163 s.anArray.splice(1, 1, "a", "b")164 })210 const nextState = produce(211 baseState,212 s => {213 s.anArray.splice(1, 1, "a", "b")214 },215 listener216 )217 expect(nextState).not.toBe(baseState)218 expect(nextState.anArray).not.toBe(baseState.anArray)219220 expect(enumerableOnly(nextState.anArray)).toEqual([
5 unmodified lines
226 ])227 })228229 it("can delete array items", () => {178 const nextState = produce(baseState, s => {179 s.anArray.length = 3180 })230 const nextState = produce(231 baseState,232 s => {233 s.anArray.length = 3234 },235 listener236 )237 expect(nextState).not.toBe(baseState)238 expect(nextState.anObject).toBe(baseState.anObject)239 expect(nextState.anArray).not.toBe(baseState.anArray)240 expect(nextState.anArray).toEqual([3, 2, {c: 3}])241 })242243 it("should support sorting arrays", () => {188 const nextState = produce(baseState, s => {189 s.anArray[2].c = 4190 s.anArray.sort()191 s.anArray[3].c = 5192 })244 const nextState = produce(245 baseState,246 s => {247 s.anArray[2].c = 4248 s.anArray.sort()249 s.anArray[3].c = 5250 },251 listener252 )253 expect(nextState).not.toBe(baseState)254 expect(nextState.anArray).not.toBe(baseState.anArray)255 expect(enumerableOnly(nextState.anArray)).toEqual([1, 2, 3, {c: 5}])256 })257258 it("should expose property descriptors", () => {259 const nextState = produce(260 [],261 s => {262 expect(Object.getOwnPropertyDescriptor(s, 0)).toBe(199 const nextState = produce([], s => {200 expect(Object.getOwnPropertyDescriptor(s, 0)).toBe(undefined)201 s.unshift("x")202 expect(Object.getOwnPropertyDescriptor(s, 0)).toEqual({203 configurable: true,204 enumerable: true,205 value: "x",206 writable: true207 })208 expect(s.length).toBe(1)209 expect(s[0] === "x").toBe(true)210 })263 undefined264 )265 s.unshift("x")266 expect(Object.getOwnPropertyDescriptor(s, 0)).toEqual({267 configurable: true,268 enumerable: true,269 value: "x",270 writable: true271 })272 expect(s.length).toBe(1)273 expect(s[0] === "x").toBe(true)274 },275 listener276 )277 expect(nextState).toEqual(["x"])278 expect(Object.getOwnPropertyDescriptor(nextState, 0)).toEqual({279 configurable: !freeze,280 enumerable: true,
2 unmodified lines
283 })284 })285286 it("should support sorting arrays - 2", () => {221 const nextState = produce(baseState, s => {222 s.anArray.unshift("x")223 s.anArray[3].c = 4224 s.anArray.sort()225 s.anArray[3].c = 5226 s.anArray.unshift("y")227 })287 const nextState = produce(288 baseState,289 s => {290 s.anArray.unshift("x")291 s.anArray[3].c = 4292 s.anArray.sort()293 s.anArray[3].c = 5294 s.anArray.unshift("y")295 },296 listener297 )298 expect(nextState).not.toBe(baseState)299 expect(nextState.anArray).not.toBe(baseState.anArray)300 expect(enumerableOnly(nextState.anArray)).toEqual([301 "y",
5 unmodified lines
307 ])308 })309310 it("should updating inside arrays", () => {241 const nextState = produce(baseState, s => {242 s.anArray[2].test = true243 })311 const nextState = produce(312 baseState,313 s => {314 s.anArray[2].test = true315 },316 listener317 )318 expect(nextState).not.toBe(baseState)319 expect(nextState.anArray).not.toBe(baseState.anArray)320 expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])321 })322323 it("reusing object should work", () => {324 const nextState = produce(325 baseState,250 const nextState = produce(baseState, s => {251 const obj = s.anObject252 delete s.anObject253 s.messy = obj254 })326 s => {327 const obj = s.anObject328 delete s.anObject329 s.messy = obj330 },331 listener332 )333 expect(nextState).not.toBe(baseState)334 expect(nextState.anArray).toBe(baseState.anArray)335 expect(enumerableOnly(nextState)).toEqual({336 anArray: [3, 2, {c: 3}, 1],
8 unmodified lines
345 expect(nextState.messy.nested).toBe(baseState.anObject.nested)346 })347348 it("refs should be transparent", () => {349 const nextState = produce(350 baseState,271 const nextState = produce(baseState, s => {272 const obj = s.anObject273 s.aProp = "hello"274 delete s.anObject275 obj.coffee = true276 s.messy = obj277 })351 s => {352 const obj = s.anObject353 s.aProp = "hello"354 delete s.anObject355 obj.coffee = true356 s.messy = obj357 },358 listener359 )360 expect(nextState).not.toBe(baseState)361 expect(nextState.anArray).toBe(baseState.anArray)362 expect(enumerableOnly(nextState)).toEqual({363 anArray: [3, 2, {c: 3}, 1],
8 unmodified lines
372 expect(nextState.messy.nested).toBe(baseState.anObject.nested)373 })374375 it("should allow setting to undefined a defined draft property", () => {294 const nextState = produce(baseState, s => {295 s.aProp = undefined296 })376 const nextState = produce(377 baseState,378 s => {379 s.aProp = undefined380 },381 listener382 )383 expect(nextState).not.toBe(baseState)384 expect(baseState.aProp).toBe("hi")385 expect(nextState.aProp).toBe(undefined)386 })
1 unmodified line
388 // ES implementation does't protect against all outside modifications, just some..389 if (useProxies) {390 it("should revoke the proxy of the baseState after immer function is executed", () => {391 let proxy306 const nextState = produce(baseState, s => {307 proxy = s308 s.aProp = "hello"309 })392 const nextState = produce(393 baseState,394 s => {395 proxy = s396 s.aProp = "hello"397 },398 listener399 )400 expect(nextState).not.toBe(baseState)401 expect(baseState.aProp).toBe("hi")402 expect(nextState.aProp).toBe("hello")403
11 unmodified lines
415 }416417 it("should revoke the proxy of the baseState after immer function is executed - 2", () => {418 let proxy329 const nextState = produce(baseState, s => {330 proxy = s.anObject331 })419 const nextState = produce(420 baseState,421 s => {422 proxy = s.anObject423 },424 listener425 )426 expect(nextState).toBe(baseState)427 expect(() => {428 // In ES5 implemenation only protects existing props, but alas..429 proxy.coffee = "Hallo"
3 unmodified lines
433 }).toThrowError(/revoked/)434 })435436 it("should reflect all changes made in the draft immediately", () => {437 produce(438 baseState,343 produce(baseState, draft => {344 draft.anArray[0] = 5345 draft.anArray.unshift("test")346 // sliced here; jest will also compare non-enumerable keys, which would include the immer Symbols347 expect(draft.anArray.slice()).toMatchObject([348 "test",349 5,350 2,351 {c: 3},352 1353 ])354 draft.stuffz = "coffee"355 expect(draft.stuffz).toBe("coffee")356 })439 draft => {440 draft.anArray[0] = 5441 draft.anArray.unshift("test")442 // sliced here; jest will also compare non-enumerable keys, which would include the immer Symbols443 expect(draft.anArray.slice()).toMatchObject([444 "test",445 5,446 2,447 {c: 3},448 1449 ])450 draft.stuffz = "coffee"451 expect(draft.stuffz).toBe("coffee")452 },453 listener454 )455 })456457 it("should be able to get property descriptors from objects", () => {458 produce(459 {a: 1},360 produce({a: 1}, draft => {361 expect("a" in draft).toBe(true)362 expect("b" in draft).toBe(false)363 expect(364 Reflect.ownKeys(draft).filter(x => typeof x === "string")365 ).toEqual(["a"])460 draft => {461 expect("a" in draft).toBe(true)462 expect("b" in draft).toBe(false)463 expect(464 Reflect.ownKeys(draft).filter(465 x => typeof x === "string"466 )467 ).toEqual(["a"])468367 expect(368 Object.getOwnPropertyDescriptor(draft, "a")369 ).toMatchObject({370 configurable: true,371 enumerable: true372 })373 draft.a = 2374 expect(375 Object.getOwnPropertyDescriptor(draft, "a")376 ).toMatchObject({377 configurable: true,378 enumerable: true379 })380 expect(381 Object.getOwnPropertyDescriptor(draft, "b")382 ).toBeUndefined()383 draft.b = 2384 expect(385 Object.getOwnPropertyDescriptor(draft, "b")386 ).toMatchObject({387 configurable: true,388 enumerable: true389 })390 expect("a" in draft).toBe(true)391 expect("b" in draft).toBe(true)392 expect(393 Reflect.ownKeys(draft).filter(x => typeof x === "string")394 ).toEqual(["a", "b"])395 })469 expect(470 Object.getOwnPropertyDescriptor(draft, "a")471 ).toMatchObject({472 configurable: true,473 enumerable: true474 })475 draft.a = 2476 expect(477 Object.getOwnPropertyDescriptor(draft, "a")478 ).toMatchObject({479 configurable: true,480 enumerable: true481 })482 expect(483 Object.getOwnPropertyDescriptor(draft, "b")484 ).toBeUndefined()485 draft.b = 2486 expect(487 Object.getOwnPropertyDescriptor(draft, "b")488 ).toMatchObject({489 configurable: true,490 enumerable: true491 })492 expect("a" in draft).toBe(true)493 expect("b" in draft).toBe(true)494 expect(495 Reflect.ownKeys(draft).filter(496 x => typeof x === "string"497 )498 ).toEqual(["a", "b"])499 },500 listener501 )502 })503504 it("should be able to get property descriptors from arrays", () => {399 produce([1], draft => {400 expect(0 in draft).toBe(true)401 expect(1 in draft).toBe(false)402 expect("0" in draft).toBe(true)403 expect("1" in draft).toBe(false)404 expect(length in draft).toBe(true)405 expect(406 Reflect.ownKeys(draft).filter(x => typeof x === "string")407 ).toEqual(["0", "length"])505 produce(506 [1],507 draft => {508 expect(0 in draft).toBe(true)509 expect(1 in draft).toBe(false)510 expect("0" in draft).toBe(true)511 expect("1" in draft).toBe(false)512 expect(length in draft).toBe(true)513 expect(514 Reflect.ownKeys(draft).filter(515 x => typeof x === "string"516 )517 ).toEqual(["0", "length"])518409 expect(410 Object.getOwnPropertyDescriptor(draft, "length")411 ).toMatchObject({412 configurable: false,413 enumerable: false414 })415 draft[0] = 2416 expect(Object.getOwnPropertyDescriptor(draft, 0)).toMatchObject(417 {519 expect(520 Object.getOwnPropertyDescriptor(draft, "length")521 ).toMatchObject({522 configurable: false,523 enumerable: false524 })525 draft[0] = 2526 expect(527 Object.getOwnPropertyDescriptor(draft, 0)528 ).toMatchObject({529 configurable: true,530 enumerable: true420 }421 )422 expect(Object.getOwnPropertyDescriptor(draft, 0)).toMatchObject(423 {531 })532 expect(533 Object.getOwnPropertyDescriptor(draft, 0)534 ).toMatchObject({535 configurable: true,536 enumerable: true426 }427 )428 expect(429 Object.getOwnPropertyDescriptor(draft, 1)430 ).toBeUndefined()431 draft[1] = 2432 expect(Object.getOwnPropertyDescriptor(draft, 1)).toMatchObject(433 {537 })538 expect(539 Object.getOwnPropertyDescriptor(draft, 1)540 ).toBeUndefined()541 draft[1] = 2542 expect(543 Object.getOwnPropertyDescriptor(draft, 1)544 ).toMatchObject({545 configurable: true,546 enumerable: true436 }437 )438 expect(439 Reflect.ownKeys(draft).filter(x => typeof x === "string")440 ).toEqual(["0", "1", "length"])441 })547 })548 expect(549 Reflect.ownKeys(draft).filter(550 x => typeof x === "string"551 )552 ).toEqual(["0", "1", "length"])553 },554 listener555 )556 })557558 if (useProxies === true) {559 it("should not be possible to set property descriptors", () => {560 expect(() => {561 produce(562 {},447 produce({}, draft => {448 Object.defineProperty(draft, "xx", {449 enumerable: true,450 writeable: true,451 value: 2452 })453 })563 draft => {564 Object.defineProperty(draft, "xx", {565 enumerable: true,566 writeable: true,567 value: 2568 })569 },570 listener571 )572 }).toThrowError(/not support/)573 })574 }575576 it("should not throw error, see #53 - 1", () => {577 const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}460 const result = produce(base, draft => {461 draft.arr = draft.arr.filter(item => item.count > 2)462 })578 const result = produce(579 base,580 draft => {581 draft.arr = draft.arr.filter(item => item.count > 2)582 },583 listener584 )585 expect(result.arr[0].count).toEqual(3)586 expect(result).toEqual({587 arr: [{count: 3}]588 })
1 unmodified line
590 })591592 it("should not throw error, see #53 - 2", () => {593 const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}472 const result = produce(base, draft => {473 draft.newArr = draft.arr.filter(item => item.count > 2)474 })594 const result = produce(595 base,596 draft => {597 draft.newArr = draft.arr.filter(item => item.count > 2)598 },599 listener600 )601 expect(result.newArr[0].count).toEqual(3)602 expect(result.arr).toBe(base.arr)603 expect(result).toEqual({604 arr: [
18 unmodified lines
623 })624625 it("should not throw error, see #53 - 3", () => {626 const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}627 const result = produce(628 base,501 const result = produce(base, draft => {502 draft.newArr = draft.arr.filter(item => item.count > 2)503 delete draft.arr504 })629 draft => {630 draft.newArr = draft.arr.filter(item => item.count > 2)631 delete draft.arr632 },633 listener634 )635 expect(result.newArr[0].count).toEqual(3)636 expect(result).toEqual({637 newArr: [{count: 3}]638 })
1 unmodified line
640 })641642 it("should not throw error, see #53 - 4", () => {643 const base = {bear: {age: 10}}644 const result = produce(645 base,514 const result = produce(base, draft => {515 draft.bear.legs = 4516 draft.room = {elephant: {kiddo: draft.bear}}517 })646 draft => {647 draft.bear.legs = 4648 draft.room = {elephant: {kiddo: draft.bear}}649 },650 listener651 )652 expect(result).toEqual({653 bear: {age: 10, legs: 4},654 room: {elephant: {kiddo: {age: 10, legs: 4}}}655 })
113 unmodified lines
769 })770771 it("should handle nested immer calls correctly - 1", () => {772 const bear = {paw: {honey: true}}773 const next = produce(774 bear,639 const next = produce(bear, draft => {640 const paw2 = produce(bear.paw, draft => {641 draft.honey = false642 })643 expect(paw2.honey).toBe(false)644 expect(draft.paw.honey).toBe(true) // effects should not be visible outside645 })775 draft => {776 const paw2 = produce(bear.paw, draft => {777 draft.honey = false778 })779 expect(paw2.honey).toBe(false)780 expect(draft.paw.honey).toBe(true) // effects should not be visible outside781 },782 listener783 )784 expect(next.paw.honey).toBe(true)785 expect(next).toBe(bear)786 })787788 it("should handle nested immer calls correctly - 2", () => {789 const bear = {paw: {honey: true}}790 const next = produce(791 bear,652 const next = produce(bear, draft => {653 const paw2 = produce(bear.paw, draft => {654 draft.honey = false655 })656 expect(paw2.honey).toBe(false)657 expect(draft.paw.honey).toBe(true)658 draft.paw = paw2659 expect(draft.paw.honey).toBe(false)660 })792 draft => {793 const paw2 = produce(bear.paw, draft => {794 draft.honey = false795 })796 expect(paw2.honey).toBe(false)797 expect(draft.paw.honey).toBe(true)798 draft.paw = paw2799 expect(draft.paw.honey).toBe(false)800 },801 listener802 )803 expect(next.paw.honey).toBe(false)804 expect(next).not.toBe(bear)805 })806807 it("should not try to change immutable data, see #66", () => {808 const user = require("./test-data")809810 const base = {}669 const next = produce(base, draft => {670 draft.user = user671 })811 const next = produce(812 base,813 draft => {814 draft.user = user815 },816 listener817 )818 expect(next.user).toBe(user)819 expect(next).not.toBe(base)820 expect(next.user).toEqual(user)821 })
1 unmodified line
823 it("should not try to change immutable data, see #66 - 2", () => {824 const user = deepFreeze(cloneDeep(require("./test-data")))825826 const base = {}681 const next = produce(base, draft => {682 draft.user = user683 })827 const next = produce(828 base,829 draft => {830 draft.user = user831 },832 listener833 )834 expect(next.user).toBe(user)835 expect(next).not.toBe(base)836 expect(next.user).toEqual(user)837 })838839 if (freeze)840 it("should freeze new data well", () => {841 const base = {}692 const next = produce(base, draft => {693 draft.x = {y: [{z: true}]}694 })842 const next = produce(843 base,844 draft => {845 draft.x = {y: [{z: true}]}846 },847 listener848 )849 expect(Object.isFrozen(next)).toBe(true)850 expect(Object.isFrozen(next.x)).toBe(true)851 expect(Object.isFrozen(next.x.y)).toBe(true)852 expect(Object.isFrozen(next.x.y[0].z)).toBe(true)853 })854855 it("should structurally share identical objects in the tree", () => {856 const base = {bear: {legs: 4}, eagle: {legs: 3}}857 const next = produce(858 base,703 const next = produce(base, draft => {704 const animal = draft.bear705 animal.legs = animal.legs + 1706 draft.bear = animal707 draft.eagle = animal708 draft.cow = animal709 draft.kiddo = animal710 })859 draft => {860 const animal = draft.bear861 animal.legs = animal.legs + 1862 draft.bear = animal863 draft.eagle = animal864 draft.cow = animal865 draft.kiddo = animal866 },867 listener868 )869 expect(next).toEqual({870 bear: {legs: 5},871 eagle: {legs: 5},872 cow: {legs: 5},
4 unmodified lines
877 })878879 if (useProxies)880 it("should not allow changing prototype", () => {723 produce({}, draft => {724 expect(() => Object.setPrototypeOf(draft, Array)).toThrow(725 /does not support `setPrototype/726 )727 })881 produce(882 {},883 draft => {884 expect(() =>885 Object.setPrototypeOf(draft, Array)886 ).toThrow(/does not support `setPrototype/)887 },888 listener889 )890 })891892 it("'in' should work", () => {893 produce(894 createBaseState(),731 produce(createBaseState(), draft => {732 expect("anArray" in draft).toBe(true)733 expect(Reflect.has(draft, "anArray")).toBe(true)895 draft => {896 expect("anArray" in draft).toBe(true)897 expect(Reflect.has(draft, "anArray")).toBe(true)898735 expect("bla" in draft).toBe(false)736 expect(Reflect.has(draft, "bla")).toBe(false)899 expect("bla" in draft).toBe(false)900 expect(Reflect.has(draft, "bla")).toBe(false)901738 expect(0 in draft.anArray).toBe(true)739 expect("0" in draft.anArray).toBe(true)740 expect(Reflect.has(draft.anArray, 0)).toBe(true)741 expect(Reflect.has(draft.anArray, "0")).toBe(true)902 expect(0 in draft.anArray).toBe(true)903 expect("0" in draft.anArray).toBe(true)904 expect(Reflect.has(draft.anArray, 0)).toBe(true)905 expect(Reflect.has(draft.anArray, "0")).toBe(true)906743 expect(17 in draft.anArray).toBe(false)744 expect("17" in draft.anArray).toBe(false)745 expect(Reflect.has(draft.anArray, 17)).toBe(false)746 expect(Reflect.has(draft.anArray, "17")).toBe(false)747 })907 expect(17 in draft.anArray).toBe(false)908 expect("17" in draft.anArray).toBe(false)909 expect(Reflect.has(draft.anArray, 17)).toBe(false)910 expect(Reflect.has(draft.anArray, "17")).toBe(false)911 },912 listener913 )914 })915916 it("'this' should work - 1", () => {917 const base = {x: 3}752 const next1 = produce(base, function() {753 this.x = 4754 })918 const next1 = produce(919 base,920 function() {921 this.x = 4922 },923 listener924 )925 expect(next1).not.toBe(base)926 expect(next1.x).toBe(4)927 })928
15 unmodified lines
944 value: "val"945 }946 }947 }948 const nextState = produce(949 state,778 const nextState = produce(state, draft => {779 draft.users.existingID = {780 ...draft.users.existingID,781 loading: true782 }783 })950 draft => {951 draft.users.existingID = {952 ...draft.users.existingID,953 loading: true954 }955 },956 listener957 )958 expect(nextState).toEqual({959 users: {960 existingID: {961 loading: true,
4 unmodified lines
966 })967968 it("processes with lodash.set", () => {969 const base = [{id: 1, a: 1}]796 const result = produce(base, draft => {797 lodash.set(draft, "[0].a", 2)798 })970 const result = produce(971 base,972 draft => {973 lodash.set(draft, "[0].a", 2)974 },975 listener976 )977 expect(base[0].a).toEqual(1)978 expect(result[0].a).toEqual(2)979 })980981 it("processes with lodash.find", () => {982 const base = [{id: 1, a: 1}]983 const result = produce(984 base,805 const result = produce(base, draft => {806 const obj1 = lodash.find(draft, {id: 1})807 lodash.set(obj1, "a", 2)808 })985 draft => {986 const obj1 = lodash.find(draft, {id: 1})987 lodash.set(obj1, "a", 2)988 },989 listener990 )991 expect(base[0].a).toEqual(1)992 expect(result[0].a).toEqual(2)993 })994995 it("can produce from no state", () => {996 expect(997 produce(998 3,815 produce(3, draft => {816 expect(draft).toBe(3)817 return 5818 })999 draft => {1000 expect(draft).toBe(3)1001 return 51002 },1003 listener1004 )1005 ).toBe(5)1006 })10071008 it("can return something new ", () => {1009 const base = {x: 3}824 const res = produce(base, draft => {825 return {x: draft.x + 1}826 })1010 const res = produce(1011 base,1012 draft => {1013 return {x: draft.x + 1}1014 },1015 listener1016 )1017 expect(res).not.toBe(base)1018 expect(res).toEqual({x: 4})1019 })10201021 it("can return the draft new ", () => {1022 const base = {x: 3}1023 const res = produce(1024 base,833 const res = produce(base, draft => {834 draft.x = 4835 return draft836 })1025 draft => {1026 draft.x = 41027 return draft1028 },1029 listener1030 )1031 expect(res).not.toBe(base)1032 expect(res).toEqual({x: 4})1033 })10341035 it("should throw if modifying the draft and returning something new", () => {1036 const base = {x: 3}1037 expect(() => {1038 produce(1039 base,844 produce(base, draft => {845 draft.x = 4846 return {x: 5}847 })1040 draft => {1041 draft.x = 41042 return {x: 5}1043 },1044 listener1045 )1046 }).toThrow(/An immer producer returned a new value/)1047 })10481049 it("should fix #116", () => {852 const nextState = produce([1, 2, 3], s => {853 s.pop()854 s.push(100)855 })1050 const nextState = produce(1051 [1, 2, 3],1052 s => {1053 s.pop()1054 s.push(100)1055 },1056 listener1057 )1058 expect(nextState).toEqual([1, 2, 100])1059 })10601061 it("should fix #117", () => {1062 const reducer = (state, action) =>1063 produce(1064 state,861 produce(state, draft => {862 switch (action.type) {863 case "SET_STARTING_DOTS":864 return draft.availableStartingDots.map(a => a)865 default:866 break867 }868 })1065 draft => {1066 switch (action.type) {1067 case "SET_STARTING_DOTS":1068 return draft.availableStartingDots.map(a => a)1069 default:1070 break1071 }1072 },1073 listener1074 )1075 const base = {1076 availableStartingDots: [1077 {dots: 4, count: 1},1078 {dots: 3, count: 2},
7 unmodified lines
1086 })10871088 it("should fix #117 - 2", () => {1089 const reducer = (state, action) =>884 produce(state, draft => {885 switch (action.type) {886 case "SET_STARTING_DOTS":887 return {888 dots: draft.availableStartingDots.map(a => a)889 }890 default:891 break892 }893 })1090 produce(1091 state,1092 draft => {1093 switch (action.type) {1094 case "SET_STARTING_DOTS":1095 return {1096 dots: draft.availableStartingDots.map(1097 a => a1098 )1099 }1100 default:1101 break1102 }1103 },1104 listener1105 )1106 const base = {1107 availableStartingDots: [1108 {dots: 4, count: 1},1109 {dots: 3, count: 2},
6 unmodified lines
1116 })11171118 it("should return an unmodified primitive baseState (#148)", () => {1119 const baseState = "some string"908 const nextState = produce(baseState, () => {909 /* no modification */910 })1120 const nextState = produce(1121 baseState,1122 () => {1123 /* no modification */1124 },1125 listener1126 )1127 expect(nextState).toBe(baseState)1128 })11291130 it("should return an unmodified null baseState (#148)", () => {1131 const baseState = null916 const nextState = produce(baseState, () => {917 /* no modification */918 })1132 const nextState = produce(1133 baseState,1134 () => {1135 /* no modification */1136 },1137 listener1138 )1139 expect(nextState).toBe(baseState)1140 })11411142 it("should not detect noop assignments - 0", () => {1143 const baseState = {x: {y: 3}}1144 const nextState = produce(1145 baseState,1146 d => {1147 const a = d.x1148 d.x = a1149 },1150 listener1151 )1152 expect(nextState).toBe(baseState)1153 })11541155 it("should not detect noop assignments - 1", () => {1156 const baseState = {x: {y: 3}}1157 const nextState = produce(1158 baseState,1159 d => {1160 const a = d.x1161 d.x = 41162 d.x = a1163 },1164 listener1165 )1166 // Ideally, this should actually be the same instances1167 // but this would be pretty expensive to detect,1168 // so we don't atm1169 expect(nextState).not.toBe(baseState)1170 })11711172 it("should not detect noop assignments - 2", () => {1173 const baseState = {x: {y: 3}}1174 const nextState = produce(1175 baseState,1176 d => {1177 const a = d.x1178 const stuff = a.y + 31179 d.x = 41180 d.x = a1181 },1182 listener1183 )1184 // Ideally, this should actually be the same instances1185 // but this would be pretty expensive to detect,1186 // so we don't atm1187 expect(nextState).not.toBe(baseState)1188 })11891190 it("should not detect noop assignments - 3", () => {1191 const baseState = {x: 3}1192 const nextState = produce(1193 baseState,1194 d => {1195 d.x = 31196 },1197 listener1198 )1199 expect(nextState).toBe(baseState)1200 })12011202 it("should not detect noop assignments - 4", () => {1203 const baseState = {x: 3}1204 const nextState = produce(1205 baseState,1206 d => {1207 d.x = 41208 d.x = 31209 },1210 listener1211 )1212 // Ideally, this should actually be the same instances1213 // but this would be pretty expensive to detect,1214 // so we don't atm1215 expect(nextState).not.toBe(baseState)1216 })12171218 it("immer should have no dependencies", () => {1219 expect(require("../package.json").dependencies).toEqual(undefined)1220 })1221
25 unmodified lines
modified:__tests__/curry.js+2 added-2 removed
added:__tests__/patch.js+265 added
1"use strict"2import produce, {setUseProxies, applyPatches} from "../src/immer"34jest.setTimeout(1000)56function runPatchTest(base, producer, patches, inversePathes) {7 function runPatchTestHelper() {8 let recordedPatches9 let recordedInversePatches10 const res = produce(base, producer, (p, i) => {11 recordedPatches = p12 recordedInversePatches = i13 })1415 test("produces the correct patches", () => {16 expect(recordedPatches).toEqual(patches)17 if (inversePathes)18 expect(recordedInversePatches).toEqual(inversePathes)19 })2021 test("patches are replayable", () => {22 expect(applyPatches(base, recordedPatches)).toEqual(res)23 })2425 test("patches can be revered", () => {26 expect(applyPatches(res, recordedInversePatches)).toEqual(base)27 })28 }2930 describe(`proxy`, () => {31 setUseProxies(true)32 runPatchTestHelper()33 })3435 describe(`es5`, () => {36 setUseProxies(false)37 runPatchTestHelper()38 })39}4041describe("simple assignment", () => {42 runPatchTest(43 {x: 3},44 d => {45 d.x++46 },47 [{op: "replace", path: ["x"], value: 4}]48 )49})5051describe("simple assignment - 2", () => {52 runPatchTest(53 {x: {y: 4}},54 d => {55 d.x.y++56 },57 [{op: "replace", path: ["x", "y"], value: 5}]58 )59})6061describe("simple assignment - 2", () => {62 runPatchTest(63 {x: {y: 4}},64 d => {65 d.x.y++66 },67 [{op: "replace", path: ["x", "y"], value: 5}]68 )69})7071describe("delete 1", () => {72 runPatchTest(73 {x: {y: 4}},74 d => {75 delete d.x76 },77 [{op: "remove", path: ["x"]}]78 )79})8081describe("moving stuff", () => {82 runPatchTest(83 {x: {y: 4}},84 d => {85 d.z = d.x86 d.z.y++87 delete d.x88 },89 [{op: "add", path: ["z"], value: {y: 5}}, {op: "remove", path: ["x"]}]90 )91})9293describe("minimum amount of changes", () => {94 runPatchTest(95 {x: 3, y: {a: 4}, z: 3},96 d => {97 d.y.a = 498 d.y.b = 599 Object.assign(d, {x: 4, y: {a: 2}})100 },101 [102 {op: "replace", path: ["x"], value: 4},103 {op: "replace", path: ["y"], value: {a: 2}}104 ]105 )106})107108describe("arrays - 1", () => {109 runPatchTest(110 {x: [1, 2, 3]},111 d => {112 d.x.unshift(4)113 },114 [115 {op: "replace", path: ["x", 0], value: 4},116 {op: "replace", path: ["x", 1], value: 1},117 {op: "replace", path: ["x", 2], value: 2},118 {op: "add", path: ["x", 3], value: 3}119 ]120 )121})122123describe("arrays - 2", () => {124 runPatchTest(125 {x: [1, 2, 3]},126 d => {127 d.x.splice(1, 1)128 },129 [130 {op: "replace", path: ["x", 1], value: 3},131 {op: "replace", path: ["x", "length"], value: 2}132 ]133 )134})135136describe("arrays - 3", () => {137 runPatchTest(138 {x: [1, 2, 3]},139 d => {140 d.x.unshift(4)141 d.x.splice(2, 1)142 },143 [144 {op: "replace", path: ["x", 0], value: 4},145 {op: "replace", path: ["x", 1], value: 1}146 ]147 )148})149150describe("arrays - 4", () => {151 runPatchTest(152 {x: [1, 2, 3]},153 d => {154 d.x.splice(1, 1)155 d.x.unshift(4)156 },157 [158 {op: "replace", path: ["x", 0], value: 4},159 {op: "replace", path: ["x", 1], value: 1}160 ]161 )162})163164describe("arrays - 5a", () => {165 runPatchTest(166 {x: [1, 2, 3]},167 d => {168 d.x.length -= 2169 },170 [{op: "replace", path: ["x", "length"], value: 1}],171 [172 {op: "add", path: ["x", 1], value: 2},173 {op: "add", path: ["x", 2], value: 3}174 ]175 )176})177178describe("arrays - 5b", () => {179 runPatchTest(180 {x: [1, 2, 3]},181 d => {182 d.x.pop()183 d.x.pop()184 },185 [{op: "replace", path: ["x", "length"], value: 1}]186 )187})188189describe("arrays - 6", () => {190 runPatchTest(191 {x: [1, 2, 3]},192 d => {193 d.x.push(4, 5)194 },195 [196 {op: "add", path: ["x", 3], value: 4},197 {op: "add", path: ["x", 4], value: 5}198 ],199 [{op: "replace", path: ["x", "length"], value: 3}]200 )201})202203describe("simple replacement", () => {204 runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])205})206207describe("same value replacement - 1", () => {208 runPatchTest(209 {x: {y: 3}},210 d => {211 const a = d.x212 d.x = a213 },214 []215 )216})217218describe("same value replacement - 2", () => {219 runPatchTest(220 {x: {y: 3}},221 d => {222 const a = d.x223 d.x = 4224 d.x = a225 },226 // immer does not detect this is not an actual change227 [{op: "replace", path: ["x"], value: {y: 3}}]228 )229})230231describe("same value replacement - 3", () => {232 runPatchTest(233 {x: 3},234 d => {235 d.x = 3236 },237 []238 )239})240241describe("same value replacement - 4", () => {242 runPatchTest(243 {x: 3},244 d => {245 d.x = 4246 d.x = 3247 },248 // immer does not detect this is not an actual change249 [{op: "replace", path: ["x"], value: 3}]250 )251})252describe("simple delete", () => {253 runPatchTest(254 {x: 2},255 d => {256 delete d.x257 },258 [259 {260 op: "remove",261 path: ["x"]262 }263 ]264 )265})
modified:__tests__/readme.js+49 added-1 removed
modified:__tests__/types.ts+12 added-1 removed
1import produce, { produce as produce2} from '../src/immer';1import produce, { produce as produce2, applyPatches, Patch} from '../src/immer';23interface State {4 readonly num: number;5 readonly foo?: string;
76 unmodified lines
82 })(state);83 expect(newState).not.toBe(state);84 expect(newState).toEqual(expectedState);85});8687it('can apply patches', () => {88 let patches: Patch[]89 produce({ x: 3 }, d=> {90 d.x++91 }, (p) => {92 patches = p93 })9495 expect(applyPatches({}, patches)).toEqual({x: 4})96})
modified:src/common.js+29 added-5 removed
1import {generatePatches} from "./patches"23export const PROXY_STATE =4 typeof Symbol !== "undefined"5 ? Symbol("immer-proxy-state")6 : "__$immer_state"
78 unmodified lines
85 return Object.prototype.hasOwnProperty.call(thing, prop)86}8788// given a base object, returns it if unmodified, or return the changed cloned if modified87export function finalize(base) {89export function finalize(base, path, patches, inversePatches) {90 if (isProxy(base)) {91 const state = base[PROXY_STATE]92 if (state.modified === true) {93 if (state.finalized === true) return state.copy94 state.finalized = true93 return finalizeObject(95 const result = finalizeObject(96 useProxies ? state.copy : (state.copy = shallowCopy(base)),95 state97 state,98 path,99 patches,100 inversePatches101 )102 generatePatches(103 state,104 path,105 patches,106 inversePatches,107 state.base,108 result109 )110 return result111 } else {112 return state.base113 }114 }115 finalizeNonProxiedObject(base)116 return base117}118105function finalizeObject(copy, state) {119function finalizeObject(copy, state, path, patches, inversePatches) {120 const base = state.base121 each(copy, (prop, value) => {108 if (value !== base[prop]) copy[prop] = finalize(value)122 if (value !== base[prop]) {123 // if there was an assignment on this property, we don't need to generate124 // patches for the subtree125 const generatePatches = patches && !has(state.assigned, prop)126 copy[prop] = finalize(127 value,128 generatePatches && path.concat(prop),129 generatePatches && patches,130 inversePatches131 )132 }133 })134 return freeze(copy)135}136
32 unmodified lines
modified:src/es5.js+60 added-6 removed
16 unmodified lines
1718function createState(parent, proxy, base) {19 return {20 modified: false,21 assigned: {}, // true: value was assigned to these props, false: was removed22 hasCopy: false,23 parent,24 base,25 proxy,
21 unmodified lines
47}4849function set(state, prop, value) {50 assertUnfinished(state)51 state.assigned[prop] = true // optimization; skip this if there is no listener52 if (!state.modified) {53 if (is(source(state)[prop], value)) return54 markChanged(state)55 prepareCopy(state)
52 unmodified lines
108109// this sounds very expensive, but actually it is not that expensive in practice110// as it will only visit proxies, and only do key-based change detection for objects for111// which it is not already know that they are changed (that is, only object for which no known key was changed)110function markChanges() {112function markChangesSweep() {113 // intentionally we process the proxies in reverse order;114 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore115 // reverse order of proxy creation approximates this116 for (let i = states.length - 1; i >= 0; i--) {
5 unmodified lines
122 }123 }124}125126function markChangesRecursively(object) {127 if (!object || typeof object !== "object") return128 const state = object[PROXY_STATE]129 if (!state) return130 const {proxy, base} = state131 if (Array.isArray(object)) {132 if (hasArrayChanges(state)) {133 markChanged(state)134 state.assigned.length = true135 if (proxy.length < base.length)136 for (let i = proxy.length; i < base.length; i++)137 state.assigned[i] = false138 else139 for (let i = base.length; i < proxy.length; i++)140 state.assigned[i] = true141 each(proxy, (index, child) => {142 if (!state.assigned[index]) markChangesRecursively(child)143 })144 }145 } else {146 const {added, removed} = diffKeys(base, proxy)147 if (added.length > 0 || removed.length > 0) markChanged(state)148 each(added, (_, key) => {149 state.assigned[key] = true150 })151 each(removed, (_, key) => {152 state.assigned[key] = false153 })154 each(proxy, (key, child) => {155 if (!state.assigned[key]) markChangesRecursively(child)156 })157 }158}159160function diffKeys(from, to) {161 // TODO: optimize162 const a = Object.keys(from)163 const b = Object.keys(to)164 return {165 added: b.filter(key => a.indexOf(key) === -1),166 removed: a.filter(key => b.indexOf(key) === -1)167 }168}169170function hasObjectChanges(state) {171 const baseKeys = Object.keys(state.base)172 const keys = Object.keys(state.proxy)173 return !shallowEqual(baseKeys, keys)
15 unmodified lines
189 // For all other cases, we don't have to compare, as they would have been picked up by the index setters190 return false191}192147export function produceEs5(baseState, producer) {193export function produceEs5(baseState, producer, patchListener) {194 if (isProxy(baseState)) {195 // See #100, don't nest producers196 const returnValue = producer.call(baseState, baseState)197 return returnValue === undefined ? baseState : returnValue198 }199 const prevStates = states200 states = []201 const patches = patchListener && []202 const inversePatches = patchListener && []203 try {204 // create proxy for root205 const rootProxy = createProxy(undefined, baseState)206 // execute the thunk
1 unmodified line
208 // and finalize the modified proxy209 each(states, (_, state) => {210 state.finalizing = true211 })164 // find and mark all changes (for parts not done yet)165 // TODO: store states by depth, to be able guarantee processing leaves first166 markChanges()212 let result213 // check whether the draft was modified and/or a value was returned214 if (returnValue !== undefined && returnValue !== rootProxy) {215 // something was returned, and it wasn't the proxy itself216 if (rootProxy[PROXY_STATE].modified)217 throw new Error(RETURNED_AND_MODIFIED_ERROR)218 result = finalize(returnValue)174 } else result = finalize(rootProxy)219 if (patches) {220 patches.push({op: "replace", path: [], value: result})221 inversePatches.push({op: "replace", path: [], value: baseState})222 }223 } else {224 if (patchListener) markChangesRecursively(rootProxy)225 markChangesSweep() // this one is more efficient if we don't need to know which attributes have changed226 result = finalize(rootProxy, [], patches, inversePatches)227 }228 // make sure all proxies become unusable229 each(states, (_, state) => {230 state.finished = true231 })232 patchListener && patchListener(patches, inversePatches)233 return result234 } finally {235 states = prevStates236 }
34 unmodified lines
modified:src/immer.d.ts+12 added-1 removed
8 unmodified lines
9 T extends ReadonlyArray<any> ? DraftArray<T[number]> :10 T extends object ? DraftObject<T> :11 T;1213export interface Patch {14 op: "replace" | "remove" | "add",15 path: (string|number)[]16 value?: any17}1819export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void2021export interface IProduce {22 /**23 * Immer takes a state, and runs a function against it.24 * That function can freely mutate the state, as it will create copies-on-write.
8 unmodified lines
33 * @returns The next state: a new state, or the current state if nothing was modified34 */35 <S = any>(36 currentState: S,29 recipe: (this: Draft<S>, draftState: Draft<S>) => void | S37 recipe: (this: Draft<S>, draftState: Draft<S>) => void | S,38 listener?: PatchListener39 ): S4041 // curried invocations with default initial state42 // 0 additional arguments
64 unmodified lines
107 * Manually override whether proxies should be used.108 * By default done by using feature detection109 */110export function setUseProxies(useProxies: boolean): void111112export function applyPatches<S>(state: S, patches: Patch[]): S
modified:src/immer.js+9 added-4 removed
1export {setAutoFreeze, setUseProxies} from "./common"23import {applyPatches as applyPatchesImpl} from "./patches"4import {isProxyable, getUseProxies} from "./common"5import {produceProxy} from "./proxy"6import {produceEs5} from "./es5"7
4 unmodified lines
12 *13 * @export14 * @param {any} baseState - the state to start with15 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified16 * @param {Function} patchListener - optional function that will be called with all the patches produces here17 * @returns {any} a new state, or the base state if nothing was modified18 */17export function produce(baseState, producer) {19export function produce(baseState, producer, patchListener) {20 // prettier-ignore19 if (arguments.length !== 1 && arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)21 if (arguments.length < 1 || arguments.length > 3) throw new Error("produce expects 1 to 3 arguments, got " + arguments.length)2223 // curried invocation24 if (typeof baseState === "function") {25 // prettier-ignore
19 unmodified lines
4546 // prettier-ignore47 {48 if (typeof producer !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")49 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")50 }5152 // if state is a primitive, don't bother proxying at all53 if (typeof baseState !== "object" || baseState === null) {
5 unmodified lines
59 throw new Error(60 `the first argument to an immer producer should be a primitive, plain object or array, got ${typeof baseState}: "${baseState}"`61 )62 return getUseProxies()60 ? produceProxy(baseState, producer)61 : produceEs5(baseState, producer)63 ? produceProxy(baseState, producer, patchListener)64 : produceEs5(baseState, producer, patchListener)65}6667export default produce6869export const applyPatches = produce(applyPatchesImpl)
modified:src/immer.js.flow+12 added-1 removed
1// @flow23export interface Patch {4 op: "replace" | "remove" | "add",5 path: (string|number)[],6 value?: any7}89export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void1011interface IProduce {12 /**13 * Immer takes a state, and runs a function against it.14 * That function can freely mutate the state, as it will create copies-on-write.
8 unmodified lines
23 * @returns The next state: a new state, or the current state if nothing was modified24 */25 <S>(26 currentState: S,19 recipe: (draftState: S) => S | void27 recipe: (draftState: S) => S | void,28 patchListener?: PatchListener29 ): S;30 // curried invocations with inital state31 <S, A, B, C>(32 recipe: (draftState: S, a: A, b: B, c: C) => S | void,
48 unmodified lines
81 * Manually override whether proxies should be used.82 * By default done by using feature detection83 */84declare export function setUseProxies(useProxies: boolean): void8586declare export function applyPatches<S>(state: S, patches: Patch[]): S
added:src/patches.js+144 added
1import {each} from "./common"23export function generatePatches(4 state,5 basepath,6 patches,7 inversePatches,8 baseValue,9 resultValue10) {11 if (patches)12 if (Array.isArray(baseValue))13 generateArrayPatches(14 state,15 basepath,16 patches,17 inversePatches,18 baseValue,19 resultValue20 )21 else22 generateObjectPatches(23 state,24 basepath,25 patches,26 inversePatches,27 baseValue,28 resultValue29 )30}3132export function generateArrayPatches(33 state,34 basepath,35 patches,36 inversePatches,37 baseValue,38 resultValue39) {40 const shared = Math.min(baseValue.length, resultValue.length)41 for (let i = 0; i < shared; i++) {42 if (state.assigned[i] && baseValue[i] !== resultValue[i]) {43 const path = basepath.concat(i)44 patches.push({op: "replace", path, value: resultValue[i]})45 inversePatches.push({op: "replace", path, value: baseValue[i]})46 }47 }48 if (shared < resultValue.length) {49 // stuff was added50 for (let i = shared; i < resultValue.length; i++) {51 const path = basepath.concat(i)52 patches.push({op: "add", path, value: resultValue[i]})53 }54 inversePatches.push({55 op: "replace",56 path: basepath.concat("length"),57 value: baseValue.length58 })59 } else if (shared < baseValue.length) {60 // stuff was removed61 patches.push({62 op: "replace",63 path: basepath.concat("length"),64 value: resultValue.length65 })66 for (let i = shared; i < baseValue.length; i++) {67 const path = basepath.concat(i)68 inversePatches.push({op: "add", path, value: baseValue[i]})69 }70 }71}7273function generateObjectPatches(74 state,75 basepath,76 patches,77 inversePatches,78 baseValue,79 resultValue80) {81 each(state.assigned, (key, assignedValue) => {82 const origValue = baseValue[key]83 const value = resultValue[key]84 const op = !assignedValue85 ? "remove"86 : key in baseValue ? "replace" : "add"87 if (origValue === baseValue && op === "replace") return88 const path = basepath.concat(key)89 patches.push(op === "remove" ? {op, path} : {op, path, value})90 inversePatches.push(91 op === "add"92 ? {op: "remove", path}93 : op === "remove"94 ? {op: "add", path, value: origValue}95 : {op: "replace", path, value: origValue}96 )97 })98}99100export function applyPatches(draft, patches) {101 for (let i = 0; i < patches.length; i++) {102 const patch = patches[i]103 if (patch.path.length === 0 && patch.op === "replace") {104 draft = patch.value105 } else {106 const path = patch.path.slice()107 const key = path.pop()108 const base = path.reduce((current, part) => {109 if (!current)110 throw new Error(111 "Cannot apply patch, path doesn't resolve: " +112 patch.path.join("/")113 )114 return current[part]115 }, draft)116 if (!base)117 throw new Error(118 "Cannot apply patch, path doesn't resolve: " +119 patch.path.join("/")120 )121 switch (patch.op) {122 case "replace":123 case "add":124 // TODO: add support is not extensive, it does not support insertion or `-` atm!125 base[key] = patch.value126 break127 case "remove":128 if (Array.isArray(base)) {129 if (key === base.length - 1) base.length -= 1130 else131 throw new Error(132 `Remove can only remove the last key of an array, index: ${key}, length: ${133 base.length134 }`135 )136 } else delete base[key]137 break138 default:139 throw new Error("Unsupported patch operation: " + patch.op)140 }141 }142 }143 return draft144}
modified:src/proxy.js+16 added-5 removed
40 unmodified lines
41})4243function createState(parent, base) {44 return {45 modified: false,45 modified: false, // this tree is modified (either this object or one of it's children)46 assigned: {}, // true: value was assigned to these props, false: was removed47 finalized: false,48 parent,49 base,50 copy: undefined,
23 unmodified lines
74 }75}7677function set(state, prop, value) {78 // TODO: optimize79 state.assigned[prop] = true80 if (!state.modified) {81 if (82 (prop in state.base && is(state.base[prop], value)) ||83 (has(state.proxies, prop) && state.proxies[prop] === value)
5 unmodified lines
89 return true90}9192function deleteProperty(state, prop) {93 state.assigned[prop] = false94 markChanged(state)95 delete state.copy[prop]96 return true97}
24 unmodified lines
122 }123}124125// creates a proxy for plain objects / arrays122function createProxy(parentState, base) {126function createProxy(parentState, base, key) {127 if (isProxy(base)) throw new Error("Immer bug. Plz report.")124 const state = createState(parentState, base)128 const state = createState(parentState, base, key)129 const proxy = Array.isArray(base)130 ? Proxy.revocable([state], arrayTraps)131 : Proxy.revocable(state, objectTraps)132 proxies.push(proxy)133 return proxy.proxy134}135132export function produceProxy(baseState, producer) {136export function produceProxy(baseState, producer, patchListener) {137 if (isProxy(baseState)) {138 // See #100, don't nest producers139 const returnValue = producer.call(baseState, baseState)140 return returnValue === undefined ? baseState : returnValue141 }142 const previousProxies = proxies143 proxies = []144 const patches = patchListener && []145 const inversePatches = patchListener && []146 try {147 // create proxy for root148 const rootProxy = createProxy(undefined, baseState)149 // execute the thunk
9 unmodified lines
159 // See #117160 // Should we just throw when returning a proxy which is not the root, but a subset of the original state?161 // Looks like a wrongly modeled reducer162 result = finalize(returnValue)163 if (patches) {164 patches.push({op: "replace", path: [], value: result})165 inversePatches.push({op: "replace", path: [], value: baseState})166 }167 } else {158 result = finalize(rootProxy)168 result = finalize(rootProxy, [], patches, inversePatches)169 }170 // revoke all proxies171 each(proxies, (_, p) => p.revoke())172 patchListener && patchListener(patches, inversePatches)173 return result174 } finally {175 proxies = previousProxies176 }
1 unmodified line
modified:changelog.md+4 added
1# Changelog23### 1.5.045* Added support for patches, through [#168](https://github.com/mweststrate/immer/pull/168). See the [patches](https://github.com/mweststrate/immer#patches) section for details67### 1.4.089* Improved TypeScript typings; if the base state is declared as `readonly`, the `draft` object will be upcasted to a writeable version. Fixes [#97](https://github.com/mweststrate/immer/issues/97) through [#161](https://github.com/mweststrate/immer/pull/161) by [@knpwrs](https://github.com/knpwrs)10* It is now possible to use both `import produce from "immer"` and `import {produce} from "immer"`. Implements [#136](https://github.com/mweststrate/immer/issues/136)
161 unmodified lines
modified:package.json+1 added-1 removed
9 unmodified lines
10 "types": "./dist/immer.d.ts",11 "scripts": {12 "watch": "jest --watch",13 "test": "jest",14 "test:perf": "NODE_ENV=production yarn-or-npm build && cd __preformance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js",14 "test:perf": "NODE_ENV=production yarn-or-npm build && cd __performance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js",15 "test:flow": "yarn-or-npm flow check",16 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage",17 "build": "rimraf dist/ && cross-env NODE_ENV=production rollup -c && cpx \"src/immer.{d.ts,js.flow}\" dist",18 "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write",
86 unmodified lines
modified:readme.md+76 added
218 unmodified lines
219 }220)221```222223## Patches224225During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer.226This is a very powerful tool if you want to fork your state temporarily, and replay the changes to the original.227To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used228to record the incremental updates and (inverse) apply them:229230```javascript231import produce, {applyPatches} from "immer"232233let state = {234 name: "Micheal",235 age: 32236}237238// Let's assume the user is in a wizard, and we don't know whether239// his changes should be end up in the base state ultimately or not...240let fork = state241// all the changes the user made in the wizard242let changes = []243// the inverse of all the changes made in the wizard244let inverseChanges = []245246fork = produce(247 fork,248 draft => {249 draft.age = 33250 },251 // The third argument to produce is a callback to which the patches will be fed252 (patches, inversePatches) => {253 changes.push(...patches)254 inverseChanges.push(...inversePatches)255 }256)257258// In the mean time, our original state is replaced, as, for example,259// some changes were received from the server260state = produce(state, draft => {261 draft.name = "Michel"262})263264// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!265state = applyPatches(state, changes)266267// state now contains the changes from both code paths!268expect(state).toEqual({269 name: "Michel", // changed by the server270 age: 33 // changed by the wizard271})272273// Finally, even after finishing the wizard, the user might change his mind and undo his changes...274state = applyPatches(state, inverseChanges)275expect(state).toEqual({276 name: "Michel", // Not reverted277 age: 32 // Reverted278})279```280281The generated patches are similar (but not the same) to the [RFC-6902 JSON patch standard](http://tools.ietf.org/html/rfc6902), except that the `path` property is an array, rather than a string.282This makes processing patches easier. If you want to normalize to the official specification, `patch.path = patch.path.join("/")` should do the trick. Anyway, this is what a bunch of patches and their inverse could look like:283284```json285[286 { "op": "replace", "path": ["profile"], "value": { "name": "Veria", age: 5 }},287 { "op": "remove", "path": ["tags", 3] }288]289```290291```json292[293 { "op": "replace", "path": ["profile"], "value": { "name": "Noa", age: 6 }},294 { "op": "add", "path": ["tags", 3], "value": "kiddo"},295]296```297298## Auto freezing299300Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default it is turned on during local development, and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.301
124 unmodified lines
426* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_427* [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_428* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_429* [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_430* [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_431* ... and [many more](https://www.npmjs.com/browse/depended/immer)432433## How does Immer work?434
111 unmodified lines