style: use tabs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Tabs allow for custom indentation per user
authored by use-tabs · committed by Alec Larson · parent 39b1050 · Browse files · 24 files·+3584 added−3619 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
24 files+3584 added−3619 removed
- tests:+2655 added−2684 removed
- other:+929 added−935 removed
Provenance
- Commit
a9c0fd0- Tree
28b9d92- Author
use-tabs <https://github.com/aleclarson/use-tabs>- Committer
Alec Larson <alec.stanford.larson@gmail.com>- Parent
39b1050
24 files changed+3584 added−3619 removed
modified:__tests__/base.js+1114 added-1120 removed
6 unmodified lines7 8 jest.setTimeout(1000)9 10 test("immer should have no dependencies", () => {11- expect(require("../package.json").dependencies).toBeUndefined()11+ expect(require("../package.json").dependencies).toBeUndefined()12 })13 14 runBaseTest("proxy (no freeze)", true, false)15 runBaseTest("proxy (autofreeze)", true, true)2 unmodified lines18 runBaseTest("es5 (autofreeze)", false, true)19 runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)20 21 function 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+ })27 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)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)32 33- 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)38 39- return immer40- }39+ return immer40+ }41 42- describe(`base functionality - ${name}`, () => {43- let baseState44- let origBaseState42+ describe(`base functionality - ${name}`, () => {43+ let baseState44+ let origBaseState45 46- beforeEach(() => {47- origBaseState = baseState = createBaseState()48- })46+ beforeEach(() => {47+ origBaseState = baseState = createBaseState()48+ })49 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- })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+ })57 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- })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+ })67 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- })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+ })78 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- })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+ })88 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- })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+ })97 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- })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+ })112 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- })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+ })122 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- })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+ })138 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- }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+ }149 150- // 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)153 154- // 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()159 160- // 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()163 164- // 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+ })171 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- })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+ })180 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- })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+ })188 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- })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+ })206 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- })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+ })215 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- })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+ })224 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- })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+ })233 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- })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+ })242 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- })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+ })251 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- })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+ })260 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- })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+ })271 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- })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+ })280 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- })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+ })289 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- })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+ })301 302- it("supports `immerable` symbol on constructor", () => {303- class One {}304- One[immerable] = true305- const baseState = new One()306- const nextState = produce(baseState, draft => {307- expect(draft).not.toBe(baseState)308- draft.foo = true309- })310- expect(nextState).not.toBe(baseState)311- expect(nextState.foo).toBeTruthy()312- })302+ it("supports `immerable` symbol on constructor", () => {303+ class One {}304+ One[immerable] = true305+ const baseState = new One()306+ const nextState = produce(baseState, draft => {307+ expect(draft).not.toBe(baseState)308+ draft.foo = true309+ })310+ expect(nextState).not.toBe(baseState)311+ expect(nextState.foo).toBeTruthy()312+ })313 314- it("preserves symbol properties", () => {315- const test = Symbol("test")316- const baseState = {[test]: true}317- const nextState = produce(baseState, s => {318- expect(s[test]).toBeTruthy()319- s.foo = true320- })321- expect(nextState).toEqual({322- [test]: true,323- foo: true324- })325- })314+ it("preserves symbol properties", () => {315+ const test = Symbol("test")316+ const baseState = {[test]: true}317+ const nextState = produce(baseState, s => {318+ expect(s[test]).toBeTruthy()319+ s.foo = true320+ })321+ expect(nextState).toEqual({322+ [test]: true,323+ foo: true324+ })325+ })326 327- it("preserves non-enumerable properties", () => {328- const baseState = {}329- // Non-enumerable object property330- Object.defineProperty(baseState, "foo", {331- value: {a: 1},332- enumerable: false333- })334- // Non-enumerable primitive property335- Object.defineProperty(baseState, "bar", {336- value: 1,337- enumerable: false338- })339- const nextState = produce(baseState, s => {340- expect(s.foo).toBeTruthy()341- expect(isEnumerable(s, "foo")).toBeFalsy()342- s.bar++343- expect(isEnumerable(s, "foo")).toBeFalsy()344- s.foo.a++345- expect(isEnumerable(s, "foo")).toBeFalsy()346- })347- expect(nextState.foo).toBeTruthy()348- expect(isEnumerable(nextState, "foo")).toBeFalsy()349- })327+ it("preserves non-enumerable properties", () => {328+ const baseState = {}329+ // Non-enumerable object property330+ Object.defineProperty(baseState, "foo", {331+ value: {a: 1},332+ enumerable: false333+ })334+ // Non-enumerable primitive property335+ Object.defineProperty(baseState, "bar", {336+ value: 1,337+ enumerable: false338+ })339+ const nextState = produce(baseState, s => {340+ expect(s.foo).toBeTruthy()341+ expect(isEnumerable(s, "foo")).toBeFalsy()342+ s.bar++343+ expect(isEnumerable(s, "foo")).toBeFalsy()344+ s.foo.a++345+ expect(isEnumerable(s, "foo")).toBeFalsy()346+ })347+ expect(nextState.foo).toBeTruthy()348+ expect(isEnumerable(nextState, "foo")).toBeFalsy()349+ })350 351- it("throws on computed properties", () => {352- const baseState = {}353- Object.defineProperty(baseState, "foo", {354- get: () => {},355- enumerable: true356- })357- expect(() => {358- produce(baseState, s => {359- // Proxies only throw once a change is made.360- if (useProxies) {361- s.modified = true362- }363- })364- }).toThrowErrorMatchingSnapshot()365- })351+ it("throws on computed properties", () => {352+ const baseState = {}353+ Object.defineProperty(baseState, "foo", {354+ get: () => {},355+ enumerable: true356+ })357+ expect(() => {358+ produce(baseState, s => {359+ // Proxies only throw once a change is made.360+ if (useProxies) {361+ s.modified = true362+ }363+ })364+ }).toThrowErrorMatchingSnapshot()365+ })366 367- it("allows inherited computed properties", () => {368- const proto = {}369- Object.defineProperty(proto, "foo", {370- get() {371- return this.bar372- },373- set(val) {374- this.bar = val375- }376- })377- const baseState = Object.create(proto)378- produce(baseState, s => {379- expect(s.bar).toBeUndefined()380- s.foo = {}381- expect(s.bar).toBeDefined()382- expect(s.foo).toBe(s.bar)383- })384- })367+ it("allows inherited computed properties", () => {368+ const proto = {}369+ Object.defineProperty(proto, "foo", {370+ get() {371+ return this.bar372+ },373+ set(val) {374+ this.bar = val375+ }376+ })377+ const baseState = Object.create(proto)378+ produce(baseState, s => {379+ expect(s.bar).toBeUndefined()380+ s.foo = {}381+ expect(s.bar).toBeDefined()382+ expect(s.foo).toBe(s.bar)383+ })384+ })385 386- it("supports a base state with multiple references to an object", () => {387- const obj = {}388- const res = produce({a: obj, b: obj}, d => {389- // Two drafts are created for each occurrence of an object in the base state.390- expect(d.a).not.toBe(d.b)391- d.a.z = true392- expect(d.b.z).toBeUndefined()393- })394- expect(res.b).toBe(obj)395- expect(res.a).not.toBe(res.b)396- expect(res.a.z).toBeTruthy()397- })386+ it("supports a base state with multiple references to an object", () => {387+ const obj = {}388+ const res = produce({a: obj, b: obj}, d => {389+ // Two drafts are created for each occurrence of an object in the base state.390+ expect(d.a).not.toBe(d.b)391+ d.a.z = true392+ expect(d.b.z).toBeUndefined()393+ })394+ expect(res.b).toBe(obj)395+ expect(res.a).not.toBe(res.b)396+ expect(res.a.z).toBeTruthy()397+ })398 399- // NOTE: Except the root draft.400- it("supports multiple references to any modified draft", () => {401- const next = produce({a: {b: 1}}, d => {402- d.a.b++403- d.b = d.a404- })405- expect(next.a).toBe(next.b)406- })399+ // NOTE: Except the root draft.400+ it("supports multiple references to any modified draft", () => {401+ const next = produce({a: {b: 1}}, d => {402+ d.a.b++403+ d.b = d.a404+ })405+ expect(next.a).toBe(next.b)406+ })407 408- it("can rename nested objects (no changes)", () => {409- const nextState = produce({obj: {}}, s => {410- s.foo = s.obj411- delete s.obj412- })413- expect(nextState).toEqual({foo: {}})414- })408+ it("can rename nested objects (no changes)", () => {409+ const nextState = produce({obj: {}}, s => {410+ s.foo = s.obj411+ delete s.obj412+ })413+ expect(nextState).toEqual({foo: {}})414+ })415 416- // Very similar to the test before, but the reused object has one417- // property changed, one added, and one removed.418- it("can rename nested objects (with changes)", () => {419- const nextState = produce({obj: {a: 1, b: 1}}, s => {420- s.obj.a = true // change421- delete s.obj.b // delete422- s.obj.c = true // add416+ // Very similar to the test before, but the reused object has one417+ // property changed, one added, and one removed.418+ it("can rename nested objects (with changes)", () => {419+ const nextState = produce({obj: {a: 1, b: 1}}, s => {420+ s.obj.a = true // change421+ delete s.obj.b // delete422+ s.obj.c = true // add423 424- s.foo = s.obj425- delete s.obj426- })427- expect(nextState).toEqual({foo: {a: true, c: true}})428- })424+ s.foo = s.obj425+ delete s.obj426+ })427+ expect(nextState).toEqual({foo: {a: true, c: true}})428+ })429 430- it("can nest a draft in a new object (no changes)", () => {431- const baseState = {obj: {}}432- const nextState = produce(baseState, s => {433- s.foo = {bar: s.obj}434- delete s.obj435- })436- expect(nextState.foo.bar).toBe(baseState.obj)437- })430+ it("can nest a draft in a new object (no changes)", () => {431+ const baseState = {obj: {}}432+ const nextState = produce(baseState, s => {433+ s.foo = {bar: s.obj}434+ delete s.obj435+ })436+ expect(nextState.foo.bar).toBe(baseState.obj)437+ })438 439- it("can nest a modified draft in a new object", () => {440- const nextState = produce({obj: {a: 1, b: 1}}, s => {441- s.obj.a = true // change442- delete s.obj.b // delete443- s.obj.c = true // add439+ it("can nest a modified draft in a new object", () => {440+ const nextState = produce({obj: {a: 1, b: 1}}, s => {441+ s.obj.a = true // change442+ delete s.obj.b // delete443+ s.obj.c = true // add444 445- s.foo = {bar: s.obj}446- delete s.obj447- })448- expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})449- })445+ s.foo = {bar: s.obj}446+ delete s.obj447+ })448+ expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})449+ })450 451- it("supports assigning undefined to an existing property", () => {452- const nextState = produce(baseState, s => {453- s.aProp = undefined454- })455- expect(nextState).not.toBe(baseState)456- expect(nextState.aProp).toBe(undefined)457- })451+ it("supports assigning undefined to an existing property", () => {452+ const nextState = produce(baseState, s => {453+ s.aProp = undefined454+ })455+ expect(nextState).not.toBe(baseState)456+ expect(nextState.aProp).toBe(undefined)457+ })458 459- it("supports assigning undefined to a new property", () => {460- const baseState = {}461- const nextState = produce(baseState, s => {462- s.aProp = undefined463- })464- expect(nextState).not.toBe(baseState)465- expect(nextState.aProp).toBe(undefined)466- })459+ it("supports assigning undefined to a new property", () => {460+ const baseState = {}461+ const nextState = produce(baseState, s => {462+ s.aProp = undefined463+ })464+ expect(nextState).not.toBe(baseState)465+ expect(nextState.aProp).toBe(undefined)466+ })467 468- // NOTE: ES5 drafts only protect existing properties when revoked.469- it("revokes the draft once produce returns", () => {470- const expectRevoked = (fn, shouldThrow = true) => {471- if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()472- else expect(fn).not.toThrow()473- }468+ // NOTE: ES5 drafts only protect existing properties when revoked.469+ it("revokes the draft once produce returns", () => {470+ const expectRevoked = (fn, shouldThrow = true) => {471+ if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()472+ else expect(fn).not.toThrow()473+ }474 475- // Test object drafts:476- let draft477- produce({a: 1, b: 1}, s => {478- draft = s479- delete s.b480- })475+ // Test object drafts:476+ let draft477+ produce({a: 1, b: 1}, s => {478+ draft = s479+ delete s.b480+ })481 482- // Access known property on object draft.483- expectRevoked(() => {484- draft.a485- })482+ // Access known property on object draft.483+ expectRevoked(() => {484+ draft.a485+ })486 487- // Assign known property on object draft.488- expectRevoked(() => {489- draft.a = true490- })487+ // Assign known property on object draft.488+ expectRevoked(() => {489+ draft.a = true490+ })491 492- // Access unknown property on object draft.493- expectRevoked(() => {494- draft.z495- }, useProxies)492+ // Access unknown property on object draft.493+ expectRevoked(() => {494+ draft.z495+ }, useProxies)496 497- // Assign unknown property on object draft.498- expectRevoked(() => {499- draft.z = true500- }, useProxies)497+ // Assign unknown property on object draft.498+ expectRevoked(() => {499+ draft.z = true500+ }, useProxies)501 502- // Test array drafts:503- produce([1, 2], s => {504- draft = s505- s.pop()506- })502+ // Test array drafts:503+ produce([1, 2], s => {504+ draft = s505+ s.pop()506+ })507 508- // Access known index of an array draft.509- expectRevoked(() => {510- draft[0]511- })508+ // Access known index of an array draft.509+ expectRevoked(() => {510+ draft[0]511+ })512 513- // Assign known index of an array draft.514- expectRevoked(() => {515- draft[0] = true516- })513+ // Assign known index of an array draft.514+ expectRevoked(() => {515+ draft[0] = true516+ })517 518- // Access unknown index of an array draft.519- expectRevoked(() => {520- draft[1]521- }, useProxies)518+ // Access unknown index of an array draft.519+ expectRevoked(() => {520+ draft[1]521+ }, useProxies)522 523- // Assign unknown index of an array draft.524- expectRevoked(() => {525- draft[1] = true526- }, useProxies)527- })523+ // Assign unknown index of an array draft.524+ expectRevoked(() => {525+ draft[1] = true526+ }, useProxies)527+ })528 529- it("can access a child draft that was created before the draft was modified", () => {530- produce({a: {}}, s => {531- const before = s.a532- s.b = 1533- expect(s.a).toBe(before)534- })535- })529+ it("can access a child draft that was created before the draft was modified", () => {530+ produce({a: {}}, s => {531+ const before = s.a532+ s.b = 1533+ expect(s.a).toBe(before)534+ })535+ })536 537- it("should reflect all changes made in the draft immediately", () => {538- produce(baseState, draft => {539- draft.anArray[0] = 5540- draft.anArray.unshift("test")541- expect(enumerableOnly(draft.anArray)).toEqual([542- "test",543- 5,544- 2,545- {c: 3},546- 1547- ])548- draft.stuffz = "coffee"549- expect(draft.stuffz).toBe("coffee")550- })551- })537+ it("should reflect all changes made in the draft immediately", () => {538+ produce(baseState, draft => {539+ draft.anArray[0] = 5540+ draft.anArray.unshift("test")541+ expect(enumerableOnly(draft.anArray)).toEqual(["test", 5, 2, {c: 3}, 1])542+ draft.stuffz = "coffee"543+ expect(draft.stuffz).toBe("coffee")544+ })545+ })546 553- if (useProxies)554- it("throws when Object.defineProperty() is used on drafts", () => {555- expect(() => {556- produce({}, draft => {557- Object.defineProperty(draft, "xx", {558- enumerable: true,559- writeable: true,560- value: 2561- })562- })563- }).toThrowErrorMatchingSnapshot()564- })547+ if (useProxies)548+ it("throws when Object.defineProperty() is used on drafts", () => {549+ expect(() => {550+ produce({}, draft => {551+ Object.defineProperty(draft, "xx", {552+ enumerable: true,553+ writeable: true,554+ value: 2555+ })556+ })557+ }).toThrowErrorMatchingSnapshot()558+ })559 566- it("should handle constructor correctly", () => {567- const baseState = {568- arr: new Array(),569- obj: new Object()570- }571- const result = produce(baseState, draft => {572- draft.arrConstructed = draft.arr.constructor(1)573- draft.objConstructed = draft.obj.constructor(1)574- })575- expect(result.arrConstructed).toEqual(new Array().constructor(1))576- expect(result.objConstructed).toEqual(new Object().constructor(1))577- })560+ it("should handle constructor correctly", () => {561+ const baseState = {562+ arr: new Array(),563+ obj: new Object()564+ }565+ const result = produce(baseState, draft => {566+ draft.arrConstructed = draft.arr.constructor(1)567+ draft.objConstructed = draft.obj.constructor(1)568+ })569+ expect(result.arrConstructed).toEqual(new Array().constructor(1))570+ expect(result.objConstructed).toEqual(new Object().constructor(1))571+ })572 579- it("should handle equality correctly - 1", () => {580- const baseState = {581- y: 3 / 0,582- z: NaN583- }584- const nextState = produce(baseState, draft => {585- draft.y = 4 / 0586- draft.z = NaN587- })588- expect(nextState).toBe(baseState)589- })573+ it("should handle equality correctly - 1", () => {574+ const baseState = {575+ y: 3 / 0,576+ z: NaN577+ }578+ const nextState = produce(baseState, draft => {579+ draft.y = 4 / 0580+ draft.z = NaN581+ })582+ expect(nextState).toBe(baseState)583+ })584 591- it("should handle equality correctly - 2", () => {592- const baseState = {593- x: -0594- }595- const nextState = produce(baseState, draft => {596- draft.x = +0597- })598- expect(nextState).not.toBe(baseState)599- expect(nextState).not.toEqual(baseState)600- })585+ it("should handle equality correctly - 2", () => {586+ const baseState = {587+ x: -0588+ }589+ const nextState = produce(baseState, draft => {590+ draft.x = +0591+ })592+ expect(nextState).not.toBe(baseState)593+ expect(nextState).not.toEqual(baseState)594+ })595 602- // AKA: recursive produce calls603- describe("nested producers", () => {604- describe("when base state is not a draft", () => {605- // This test ensures the global state used to manage proxies is606- // never left in a corrupted state by a nested `produce` call.607- it("never affects its parent producer implicitly", () => {608- const base = {obj: {a: 1}}609- const next = produce(base, draft => {610- // Notice how `base.obj` is passed, not `draft.obj`611- const obj2 = produce(base.obj, draft2 => {612- draft2.a = 0613- })614- expect(obj2.a).toBe(0)615- expect(draft.obj.a).toBe(1) // effects should not be visible outside616- })617- expect(next).toBe(base)618- })619- })596+ // AKA: recursive produce calls597+ describe("nested producers", () => {598+ describe("when base state is not a draft", () => {599+ // This test ensures the global state used to manage proxies is600+ // never left in a corrupted state by a nested `produce` call.601+ it("never affects its parent producer implicitly", () => {602+ const base = {obj: {a: 1}}603+ const next = produce(base, draft => {604+ // Notice how `base.obj` is passed, not `draft.obj`605+ const obj2 = produce(base.obj, draft2 => {606+ draft2.a = 0607+ })608+ expect(obj2.a).toBe(0)609+ expect(draft.obj.a).toBe(1) // effects should not be visible outside610+ })611+ expect(next).toBe(base)612+ })613+ })614 621- describe("when base state is a draft", () => {622- it("always wraps the draft in a new draft", () => {623- produce({}, parent => {624- produce(parent, child => {625- expect(child).not.toBe(parent)626- expect(isDraft(child)).toBeTruthy()627- expect(original(child)).toBe(parent)628- })629- })630- })615+ describe("when base state is a draft", () => {616+ it("always wraps the draft in a new draft", () => {617+ produce({}, parent => {618+ produce(parent, child => {619+ expect(child).not.toBe(parent)620+ expect(isDraft(child)).toBeTruthy()621+ expect(original(child)).toBe(parent)622+ })623+ })624+ })625 632- // Reported by: https://github.com/mweststrate/immer/issues/343633- it("ensures each property is drafted", () => {634- produce({a: {}, b: {}}, parent => {635- parent.a // Access "a" but not "b"636- produce(parent, child => {637- child.c = 1638- expect(isDraft(child.a)).toBeTruthy()639- expect(isDraft(child.b)).toBeTruthy()640- })641- })642- })626+ // Reported by: https://github.com/mweststrate/immer/issues/343627+ it("ensures each property is drafted", () => {628+ produce({a: {}, b: {}}, parent => {629+ parent.a // Access "a" but not "b"630+ produce(parent, child => {631+ child.c = 1632+ expect(isDraft(child.a)).toBeTruthy()633+ expect(isDraft(child.b)).toBeTruthy()634+ })635+ })636+ })637 644- it("preserves any pending changes", () => {645- produce({a: 1, b: 1, d: 1}, parent => {646- parent.b = 2647- parent.c = 2648- delete parent.d649- produce(parent, child => {650- expect(child.a).toBe(1) // unchanged651- expect(child.b).toBe(2) // changed652- expect(child.c).toBe(2) // added653- expect(child.d).toBeUndefined() // deleted654- })655- })656- })657- })638+ it("preserves any pending changes", () => {639+ produce({a: 1, b: 1, d: 1}, parent => {640+ parent.b = 2641+ parent.c = 2642+ delete parent.d643+ produce(parent, child => {644+ expect(child.a).toBe(1) // unchanged645+ expect(child.b).toBe(2) // changed646+ expect(child.c).toBe(2) // added647+ expect(child.d).toBeUndefined() // deleted648+ })649+ })650+ })651+ })652 659- describe("when base state contains a draft", () => {660- it("wraps unowned draft with its own draft", () => {661- produce({a: {}}, parent => {662- produce({a: parent.a}, child => {663- expect(child.a).not.toBe(parent.a)664- expect(isDraft(child.a)).toBeTruthy()665- expect(original(child.a)).toBe(parent.a)666- })667- })668- })653+ describe("when base state contains a draft", () => {654+ it("wraps unowned draft with its own draft", () => {655+ produce({a: {}}, parent => {656+ produce({a: parent.a}, child => {657+ expect(child.a).not.toBe(parent.a)658+ expect(isDraft(child.a)).toBeTruthy()659+ expect(original(child.a)).toBe(parent.a)660+ })661+ })662+ })663 670- it("returns unowned draft if no changes were made", () => {671- produce({a: {}}, parent => {672- const result = produce({a: parent.a}, () => {})673- expect(result.a).toBe(parent.a)674- })675- })664+ it("returns unowned draft if no changes were made", () => {665+ produce({a: {}}, parent => {666+ const result = produce({a: parent.a}, () => {})667+ expect(result.a).toBe(parent.a)668+ })669+ })670 677- it("clones the unowned draft when changes are made", () => {678- produce({a: {}}, parent => {679- const result = produce({a: parent.a}, child => {680- child.a.b = 1681- })682- expect(result.a).not.toBe(parent.a)683- expect(result.a.b).toBe(1)684- expect("b" in parent.a).toBeFalsy()685- })686- })671+ it("clones the unowned draft when changes are made", () => {672+ produce({a: {}}, parent => {673+ const result = produce({a: parent.a}, child => {674+ child.a.b = 1675+ })676+ expect(result.a).not.toBe(parent.a)677+ expect(result.a.b).toBe(1)678+ expect("b" in parent.a).toBeFalsy()679+ })680+ })681 688- // We cannot auto-freeze the result of a nested producer,689- // because it may contain a draft from a parent producer.690- it("never auto-freezes the result", () => {691- produce({a: {}}, parent => {692- const r = produce({a: parent.a}, child => {693- child.b = 1 // Ensure a copy is returned.694- })695- expect(Object.isFrozen(r)).toBeFalsy()696- })697- })698- })682+ // We cannot auto-freeze the result of a nested producer,683+ // because it may contain a draft from a parent producer.684+ it("never auto-freezes the result", () => {685+ produce({a: {}}, parent => {686+ const r = produce({a: parent.a}, child => {687+ child.b = 1 // Ensure a copy is returned.688+ })689+ expect(Object.isFrozen(r)).toBeFalsy()690+ })691+ })692+ })693 700- // "Upvalues" are variables from a parent scope.701- it("does not finalize upvalue drafts", () => {702- produce({a: {}, b: {}}, parent => {703- expect(produce({}, () => parent)).toBe(parent)704- parent.x // Ensure proxy not revoked.694+ // "Upvalues" are variables from a parent scope.695+ it("does not finalize upvalue drafts", () => {696+ produce({a: {}, b: {}}, parent => {697+ expect(produce({}, () => parent)).toBe(parent)698+ parent.x // Ensure proxy not revoked.699 706- expect(produce({}, () => [parent])[0]).toBe(parent)707- parent.x // Ensure proxy not revoked.700+ expect(produce({}, () => [parent])[0]).toBe(parent)701+ parent.x // Ensure proxy not revoked.702 709- expect(produce({}, () => parent.a)).toBe(parent.a)710- parent.a.x // Ensure proxy not revoked.703+ expect(produce({}, () => parent.a)).toBe(parent.a)704+ parent.a.x // Ensure proxy not revoked.705 712- // Modified parent test713- parent.c = 1714- expect(produce({}, () => [parent.b])[0]).toBe(parent.b)715- parent.b.x // Ensure proxy not revoked.716- })717- })706+ // Modified parent test707+ parent.c = 1708+ expect(produce({}, () => [parent.b])[0]).toBe(parent.b)709+ parent.b.x // Ensure proxy not revoked.710+ })711+ })712 719- it("works with interweaved Immer instances", () => {720- const options = {useProxies, autoFreeze}721- const one = createPatchedImmer(options)722- const two = createPatchedImmer(options)713+ it("works with interweaved Immer instances", () => {714+ const options = {useProxies, autoFreeze}715+ const one = createPatchedImmer(options)716+ const two = createPatchedImmer(options)717 724- const base = {}725- const result = one.produce(base, s1 =>726- two.produce({s1}, s2 => {727- expect(original(s2.s1)).toBe(s1)728- s2.n = 1729- s2.s1 = one.produce({s2}, s3 => {730- expect(original(s3.s2)).toBe(s2)731- expect(original(s3.s2.s1)).toBe(s2.s1)732- return s3.s2.s1733- })734- })735- )736- expect(result.n).toBe(1)737- expect(result.s1).toBe(base)738- })739- })718+ const base = {}719+ const result = one.produce(base, s1 =>720+ two.produce({s1}, s2 => {721+ expect(original(s2.s1)).toBe(s1)722+ s2.n = 1723+ s2.s1 = one.produce({s2}, s3 => {724+ expect(original(s3.s2)).toBe(s2)725+ expect(original(s3.s2.s1)).toBe(s2.s1)726+ return s3.s2.s1727+ })728+ })729+ )730+ expect(result.n).toBe(1)731+ expect(result.s1).toBe(base)732+ })733+ })734 741- if (useProxies)742- it("throws when Object.setPrototypeOf() is used on a draft", () => {743- produce({}, draft => {744- expect(() =>745- Object.setPrototypeOf(draft, Array)746- ).toThrowErrorMatchingSnapshot()747- })748- })735+ if (useProxies)736+ it("throws when Object.setPrototypeOf() is used on a draft", () => {737+ produce({}, draft => {738+ expect(() =>739+ Object.setPrototypeOf(draft, Array)740+ ).toThrowErrorMatchingSnapshot()741+ })742+ })743 750- it("supports the 'in' operator", () => {751- produce(baseState, draft => {752- // Known property753- expect("anArray" in draft).toBe(true)754- expect(Reflect.has(draft, "anArray")).toBe(true)744+ it("supports the 'in' operator", () => {745+ produce(baseState, draft => {746+ // Known property747+ expect("anArray" in draft).toBe(true)748+ expect(Reflect.has(draft, "anArray")).toBe(true)749 756- // Unknown property757- expect("bla" in draft).toBe(false)758- expect(Reflect.has(draft, "bla")).toBe(false)750+ // Unknown property751+ expect("bla" in draft).toBe(false)752+ expect(Reflect.has(draft, "bla")).toBe(false)753 760- // Known index761- expect(0 in draft.anArray).toBe(true)762- expect("0" in draft.anArray).toBe(true)763- expect(Reflect.has(draft.anArray, 0)).toBe(true)764- expect(Reflect.has(draft.anArray, "0")).toBe(true)754+ // Known index755+ expect(0 in draft.anArray).toBe(true)756+ expect("0" in draft.anArray).toBe(true)757+ expect(Reflect.has(draft.anArray, 0)).toBe(true)758+ expect(Reflect.has(draft.anArray, "0")).toBe(true)759 766- // Unknown index767- expect(17 in draft.anArray).toBe(false)768- expect("17" in draft.anArray).toBe(false)769- expect(Reflect.has(draft.anArray, 17)).toBe(false)770- expect(Reflect.has(draft.anArray, "17")).toBe(false)771- })772- })760+ // Unknown index761+ expect(17 in draft.anArray).toBe(false)762+ expect("17" in draft.anArray).toBe(false)763+ expect(Reflect.has(draft.anArray, 17)).toBe(false)764+ expect(Reflect.has(draft.anArray, "17")).toBe(false)765+ })766+ })767 774- it("'this' should not be bound anymore - 1", () => {775- const base = {x: 3}776- const next1 = produce(base, function() {777- expect(this).toBe(undefined)778- })779- })768+ it("'this' should not be bound anymore - 1", () => {769+ const base = {x: 3}770+ const next1 = produce(base, function() {771+ expect(this).toBe(undefined)772+ })773+ })774 781- it("'this' should not be bound anymore - 2", () => {782- const incrementor = produce(function() {783- expect(this).toBe(undefined)784- })785- incrementor()786- })775+ it("'this' should not be bound anymore - 2", () => {776+ const incrementor = produce(function() {777+ expect(this).toBe(undefined)778+ })779+ incrementor()780+ })781 788- it("should be possible to use dynamic bound this", () => {789- const world = {790- counter: {count: 1},791- inc: produce(function(draft) {792- expect(this).toBe(world)793- draft.counter.count = this.counter.count + 1794- })795- }782+ it("should be possible to use dynamic bound this", () => {783+ const world = {784+ counter: {count: 1},785+ inc: produce(function(draft) {786+ expect(this).toBe(world)787+ draft.counter.count = this.counter.count + 1788+ })789+ }790 797- expect(world.inc(world).counter.count).toBe(2)798- })791+ expect(world.inc(world).counter.count).toBe(2)792+ })793 800- // See here: https://github.com/mweststrate/immer/issues/89801- it("supports the spread operator", () => {802- const base = {foo: {x: 0, y: 0}, bar: [0, 0]}803- const result = produce(base, draft => {804- draft.foo = {x: 1, ...draft.foo, y: 1}805- draft.bar = [1, ...draft.bar, 1]806- })807- expect(result).toEqual({808- foo: {x: 0, y: 1},809- bar: [1, 0, 0, 1]810- })811- })794+ // See here: https://github.com/mweststrate/immer/issues/89795+ it("supports the spread operator", () => {796+ const base = {foo: {x: 0, y: 0}, bar: [0, 0]}797+ const result = produce(base, draft => {798+ draft.foo = {x: 1, ...draft.foo, y: 1}799+ draft.bar = [1, ...draft.bar, 1]800+ })801+ expect(result).toEqual({802+ foo: {x: 0, y: 1},803+ bar: [1, 0, 0, 1]804+ })805+ })806 813- it("processes with lodash.set", () => {814- const base = [{id: 1, a: 1}]815- const result = produce(base, draft => {816- lodash.set(draft, "[0].a", 2)817- })818- expect(base[0].a).toEqual(1)819- expect(result[0].a).toEqual(2)820- })807+ it("processes with lodash.set", () => {808+ const base = [{id: 1, a: 1}]809+ const result = produce(base, draft => {810+ lodash.set(draft, "[0].a", 2)811+ })812+ expect(base[0].a).toEqual(1)813+ expect(result[0].a).toEqual(2)814+ })815 822- it("processes with lodash.find", () => {823- const base = [{id: 1, a: 1}]824- const result = produce(base, draft => {825- const obj1 = lodash.find(draft, {id: 1})826- lodash.set(obj1, "a", 2)827- })828- expect(base[0].a).toEqual(1)829- expect(result[0].a).toEqual(2)830- })816+ it("processes with lodash.find", () => {817+ const base = [{id: 1, a: 1}]818+ const result = produce(base, draft => {819+ const obj1 = lodash.find(draft, {id: 1})820+ lodash.set(obj1, "a", 2)821+ })822+ expect(base[0].a).toEqual(1)823+ expect(result[0].a).toEqual(2)824+ })825 832- describe("recipe functions", () => {833- it("can return a new object", () => {834- const base = {x: 3}835- const res = produce(base, d => {836- return {x: d.x + 1}837- })838- expect(res).not.toBe(base)839- expect(res).toEqual({x: 4})840- })826+ describe("recipe functions", () => {827+ it("can return a new object", () => {828+ const base = {x: 3}829+ const res = produce(base, d => {830+ return {x: d.x + 1}831+ })832+ expect(res).not.toBe(base)833+ expect(res).toEqual({x: 4})834+ })835 842- it("can return the draft", () => {843- const base = {x: 3}844- const res = produce(base, d => {845- d.x = 4846- return d847- })848- expect(res).not.toBe(base)849- expect(res).toEqual({x: 4})850- })836+ it("can return the draft", () => {837+ const base = {x: 3}838+ const res = produce(base, d => {839+ d.x = 4840+ return d841+ })842+ expect(res).not.toBe(base)843+ expect(res).toEqual({x: 4})844+ })845 852- it("can return an unmodified child draft", () => {853- const base = {a: {}}854- const res = produce(base, d => {855- return d.a856- })857- expect(res).toBe(base.a)858- })846+ it("can return an unmodified child draft", () => {847+ const base = {a: {}}848+ const res = produce(base, d => {849+ return d.a850+ })851+ expect(res).toBe(base.a)852+ })853 860- // TODO: Avoid throwing if only the child draft was modified.861- it("cannot return a modified child draft", () => {862- const base = {a: {}}863- expect(() => {864- produce(base, d => {865- d.a.b = 1866- return d.a867- })868- }).toThrowErrorMatchingSnapshot()869- })854+ // TODO: Avoid throwing if only the child draft was modified.855+ it("cannot return a modified child draft", () => {856+ const base = {a: {}}857+ expect(() => {858+ produce(base, d => {859+ d.a.b = 1860+ return d.a861+ })862+ }).toThrowErrorMatchingSnapshot()863+ })864 871- it("can return a frozen object", () => {872- const res = deepFreeze([{x: 3}])873- expect(produce({}, () => res)).toBe(res)874- })865+ it("can return a frozen object", () => {866+ const res = deepFreeze([{x: 3}])867+ expect(produce({}, () => res)).toBe(res)868+ })869 876- it("can return an object with two references to another object", () => {877- const next = produce({}, d => {878- const obj = {}879- return {obj, arr: [obj]}880- })881- expect(next.obj).toBe(next.arr[0])882- })870+ it("can return an object with two references to another object", () => {871+ const next = produce({}, d => {872+ const obj = {}873+ return {obj, arr: [obj]}874+ })875+ expect(next.obj).toBe(next.arr[0])876+ })877 884- it("can return an object with two references to an unmodified draft", () => {885- const base = {a: {}}886- const next = produce(base, d => {887- return [d.a, d.a]888- })889- expect(next[0]).toBe(base.a)890- expect(next[0]).toBe(next[1])891- })878+ it("can return an object with two references to an unmodified draft", () => {879+ const base = {a: {}}880+ const next = produce(base, d => {881+ return [d.a, d.a]882+ })883+ expect(next[0]).toBe(base.a)884+ expect(next[0]).toBe(next[1])885+ })886 893- it("cannot return an object that references itself", () => {894- const res = {}895- res.self = res896- expect(() => {897- produce(res, () => res.self)898- }).toThrowErrorMatchingSnapshot()899- })900- })887+ it("cannot return an object that references itself", () => {888+ const res = {}889+ res.self = res890+ expect(() => {891+ produce(res, () => res.self)892+ }).toThrowErrorMatchingSnapshot()893+ })894+ })895 902- describe("async recipe function", () => {903- it("can modify the draft", () => {904- const base = {a: 0, b: 0}905- return produce(base, async d => {906- d.a = 1907- await Promise.resolve()908- d.b = 1909- }).then(res => {910- expect(res).not.toBe(base)911- expect(res).toEqual({a: 1, b: 1})912- })913- })896+ describe("async recipe function", () => {897+ it("can modify the draft", () => {898+ const base = {a: 0, b: 0}899+ return produce(base, async d => {900+ d.a = 1901+ await Promise.resolve()902+ d.b = 1903+ }).then(res => {904+ expect(res).not.toBe(base)905+ expect(res).toEqual({a: 1, b: 1})906+ })907+ })908 915- it("works with rejected promises", () => {916- let draft917- const base = {a: 0, b: 0}918- const err = new Error("passed")919- return produce(base, d => {920- draft = d921- draft.b = 1922- return Promise.reject(err)923- }).then(924- () => {925- throw "failed"926- },927- e => {928- expect(e).toBe(err)929- expect(() => draft.a).toThrowErrorMatchingSnapshot()930- }931- )932- })909+ it("works with rejected promises", () => {910+ let draft911+ const base = {a: 0, b: 0}912+ const err = new Error("passed")913+ return produce(base, d => {914+ draft = d915+ draft.b = 1916+ return Promise.reject(err)917+ }).then(918+ () => {919+ throw "failed"920+ },921+ e => {922+ expect(e).toBe(err)923+ expect(() => draft.a).toThrowErrorMatchingSnapshot()924+ }925+ )926+ })927 934- it("supports recursive produce calls after await", () => {935- const base = {obj: {k: 1}}936- return produce(base, d => {937- const obj = d.obj938- delete d.obj939- return Promise.resolve().then(() => {940- d.a = produce({}, d => {941- d.b = obj // Assign a draft owned by the parent scope.942- })928+ it("supports recursive produce calls after await", () => {929+ const base = {obj: {k: 1}}930+ return produce(base, d => {931+ const obj = d.obj932+ delete d.obj933+ return Promise.resolve().then(() => {934+ d.a = produce({}, d => {935+ d.b = obj // Assign a draft owned by the parent scope.936+ })937 944- // Auto-freezing is prevented when an unowned draft exists.945- expect(Object.isFrozen(d.a)).toBeFalsy()938+ // Auto-freezing is prevented when an unowned draft exists.939+ expect(Object.isFrozen(d.a)).toBeFalsy()940 947- // Ensure `obj` is not revoked.948- obj.c = 1949- })950- }).then(res => {951- expect(res).not.toBe(base)952- expect(res).toEqual({953- a: {b: {k: 1, c: 1}}954- })955- })956- })957- })941+ // Ensure `obj` is not revoked.942+ obj.c = 1943+ })944+ }).then(res => {945+ expect(res).not.toBe(base)946+ expect(res).toEqual({947+ a: {b: {k: 1, c: 1}}948+ })949+ })950+ })951+ })952 959- it("throws when the draft is modified and another object is returned", () => {960- const base = {x: 3}961- expect(() => {962- produce(base, draft => {963- draft.x = 4964- return {x: 5}965- })966- }).toThrowErrorMatchingSnapshot()967- })953+ it("throws when the draft is modified and another object is returned", () => {954+ const base = {x: 3}955+ expect(() => {956+ produce(base, draft => {957+ draft.x = 4958+ return {x: 5}959+ })960+ }).toThrowErrorMatchingSnapshot()961+ })962 969- it("should fix #117 - 1", () => {970- const reducer = (state, action) =>971- produce(state, draft => {972- switch (action.type) {973- case "SET_STARTING_DOTS":974- return draft.availableStartingDots.map(a => a)975- default:976- break977- }978- })979- const base = {980- availableStartingDots: [981- {dots: 4, count: 1},982- {dots: 3, count: 2},983- {dots: 2, count: 3},984- {dots: 1, count: 4}985- ]986- }987- const next = reducer(base, {type: "SET_STARTING_DOTS"})988- expect(next).toEqual(base.availableStartingDots)989- expect(next).not.toBe(base.availableStartingDots)990- })963+ it("should fix #117 - 1", () => {964+ const reducer = (state, action) =>965+ produce(state, draft => {966+ switch (action.type) {967+ case "SET_STARTING_DOTS":968+ return draft.availableStartingDots.map(a => a)969+ default:970+ break971+ }972+ })973+ const base = {974+ availableStartingDots: [975+ {dots: 4, count: 1},976+ {dots: 3, count: 2},977+ {dots: 2, count: 3},978+ {dots: 1, count: 4}979+ ]980+ }981+ const next = reducer(base, {type: "SET_STARTING_DOTS"})982+ expect(next).toEqual(base.availableStartingDots)983+ expect(next).not.toBe(base.availableStartingDots)984+ })985 992- it("should fix #117 - 2", () => {993- const reducer = (state, action) =>994- produce(state, draft => {995- switch (action.type) {996- case "SET_STARTING_DOTS":997- return {998- dots: draft.availableStartingDots.map(a => a)999- }1000- default:1001- break1002- }1003- })1004- const base = {1005- availableStartingDots: [1006- {dots: 4, count: 1},1007- {dots: 3, count: 2},1008- {dots: 2, count: 3},1009- {dots: 1, count: 4}1010- ]1011- }1012- const next = reducer(base, {type: "SET_STARTING_DOTS"})1013- expect(next).toEqual({dots: base.availableStartingDots})1014- })986+ it("should fix #117 - 2", () => {987+ const reducer = (state, action) =>988+ produce(state, draft => {989+ switch (action.type) {990+ case "SET_STARTING_DOTS":991+ return {992+ dots: draft.availableStartingDots.map(a => a)993+ }994+ default:995+ break996+ }997+ })998+ const base = {999+ availableStartingDots: [1000+ {dots: 4, count: 1},1001+ {dots: 3, count: 2},1002+ {dots: 2, count: 3},1003+ {dots: 1, count: 4}1004+ ]1005+ }1006+ const next = reducer(base, {type: "SET_STARTING_DOTS"})1007+ expect(next).toEqual({dots: base.availableStartingDots})1008+ })1009 1016- it("cannot always detect noop assignments - 0", () => {1017- const baseState = {x: {y: 3}}1018- const nextState = produce(baseState, d => {1019- const a = d.x1020- d.x = a1021- })1022- expect(nextState).toBe(baseState)1023- })1010+ it("cannot always detect noop assignments - 0", () => {1011+ const baseState = {x: {y: 3}}1012+ const nextState = produce(baseState, d => {1013+ const a = d.x1014+ d.x = a1015+ })1016+ expect(nextState).toBe(baseState)1017+ })1018 1025- it("cannot always detect noop assignments - 1", () => {1026- const baseState = {x: {y: 3}}1027- const nextState = produce(baseState, d => {1028- const a = d.x1029- d.x = 41030- d.x = a1031- })1032- // Ideally, this should actually be the same instances1033- // but this would be pretty expensive to detect,1034- // so we don't atm1035- expect(nextState).not.toBe(baseState)1036- })1019+ it("cannot always detect noop assignments - 1", () => {1020+ const baseState = {x: {y: 3}}1021+ const nextState = produce(baseState, d => {1022+ const a = d.x1023+ d.x = 41024+ d.x = a1025+ })1026+ // Ideally, this should actually be the same instances1027+ // but this would be pretty expensive to detect,1028+ // so we don't atm1029+ expect(nextState).not.toBe(baseState)1030+ })1031 1038- it("cannot always detect noop assignments - 2", () => {1039- const baseState = {x: {y: 3}}1040- const nextState = produce(baseState, d => {1041- const a = d.x1042- const stuff = a.y + 31043- d.x = 41044- d.x = a1045- })1046- // Ideally, this should actually be the same instances1047- // but this would be pretty expensive to detect,1048- // so we don't atm1049- expect(nextState).not.toBe(baseState)1050- })1032+ it("cannot always detect noop assignments - 2", () => {1033+ const baseState = {x: {y: 3}}1034+ const nextState = produce(baseState, d => {1035+ const a = d.x1036+ const stuff = a.y + 31037+ d.x = 41038+ d.x = a1039+ })1040+ // Ideally, this should actually be the same instances1041+ // but this would be pretty expensive to detect,1042+ // so we don't atm1043+ expect(nextState).not.toBe(baseState)1044+ })1045 1052- it("cannot always detect noop assignments - 3", () => {1053- const baseState = {x: 3}1054- const nextState = produce(baseState, d => {1055- d.x = 31056- })1057- expect(nextState).toBe(baseState)1058- })1046+ it("cannot always detect noop assignments - 3", () => {1047+ const baseState = {x: 3}1048+ const nextState = produce(baseState, d => {1049+ d.x = 31050+ })1051+ expect(nextState).toBe(baseState)1052+ })1053 1060- it("cannot always detect noop assignments - 4", () => {1061- const baseState = {x: 3}1062- const nextState = produce(baseState, d => {1063- d.x = 41064- d.x = 31065- })1066- // Ideally, this should actually be the same instances1067- // but this would be pretty expensive to detect,1068- // so we don't atm1069- expect(nextState).not.toBe(baseState)1070- })1054+ it("cannot always detect noop assignments - 4", () => {1055+ const baseState = {x: 3}1056+ const nextState = produce(baseState, d => {1057+ d.x = 41058+ d.x = 31059+ })1060+ // Ideally, this should actually be the same instances1061+ // but this would be pretty expensive to detect,1062+ // so we don't atm1063+ expect(nextState).not.toBe(baseState)1064+ })1065 1072- it("cannot produce undefined by returning undefined", () => {1073- const base = 31074- expect(produce(base, () => 4)).toBe(4)1075- expect(produce(base, () => null)).toBe(null)1076- expect(produce(base, () => undefined)).toBe(3)1077- expect(produce(base, () => {})).toBe(3)1078- expect(produce(base, () => nothing)).toBe(undefined)1066+ it("cannot produce undefined by returning undefined", () => {1067+ const base = 31068+ expect(produce(base, () => 4)).toBe(4)1069+ expect(produce(base, () => null)).toBe(null)1070+ expect(produce(base, () => undefined)).toBe(3)1071+ expect(produce(base, () => {})).toBe(3)1072+ expect(produce(base, () => nothing)).toBe(undefined)1073 1080- expect(produce({}, () => undefined)).toEqual({})1081- expect(produce({}, () => nothing)).toBe(undefined)1082- expect(produce(3, () => nothing)).toBe(undefined)1074+ expect(produce({}, () => undefined)).toEqual({})1075+ expect(produce({}, () => nothing)).toBe(undefined)1076+ expect(produce(3, () => nothing)).toBe(undefined)1077 1084- expect(produce(() => undefined)({})).toEqual({})1085- expect(produce(() => nothing)({})).toBe(undefined)1086- expect(produce(() => nothing)(3)).toBe(undefined)1087- })1078+ expect(produce(() => undefined)({})).toEqual({})1079+ expect(produce(() => nothing)({})).toBe(undefined)1080+ expect(produce(() => nothing)(3)).toBe(undefined)1081+ })1082 1089- describe("base state type", () => {1090- testObjectTypes(produce)1091- testLiteralTypes(produce)1092- })1083+ describe("base state type", () => {1084+ testObjectTypes(produce)1085+ testLiteralTypes(produce)1086+ })1087 1094- afterEach(() => {1095- expect(baseState).toBe(origBaseState)1096- expect(baseState).toEqual(createBaseState())1097- })1088+ afterEach(() => {1089+ expect(baseState).toBe(origBaseState)1090+ expect(baseState).toEqual(createBaseState())1091+ })1092 1099- class Foo {}1100- function createBaseState() {1101- const data = {1102- anInstance: new Foo(),1103- anArray: [3, 2, {c: 3}, 1],1104- aProp: "hi",1105- anObject: {1106- nested: {1107- yummie: true1108- },1109- coffee: false1110- }1111- }1112- return autoFreeze ? deepFreeze(data) : data1113- }1114- })1093+ class Foo {}1094+ function createBaseState() {1095+ const data = {1096+ anInstance: new Foo(),1097+ anArray: [3, 2, {c: 3}, 1],1098+ aProp: "hi",1099+ anObject: {1100+ nested: {1101+ yummie: true1102+ },1103+ coffee: false1104+ }1105+ }1106+ return autoFreeze ? deepFreeze(data) : data1107+ }1108+ })1109 1116- describe(`isDraft - ${name}`, () => {1117- it("returns true for object drafts", () => {1118- produce({}, state => {1119- expect(isDraft(state)).toBeTruthy()1120- })1121- })1122- it("returns true for array drafts", () => {1123- produce([], state => {1124- expect(isDraft(state)).toBeTruthy()1125- })1126- })1127- it("returns true for objects nested in object drafts", () => {1128- produce({a: {b: {}}}, state => {1129- expect(isDraft(state.a)).toBeTruthy()1130- expect(isDraft(state.a.b)).toBeTruthy()1131- })1132- })1133- it("returns false for new objects added to a draft", () => {1134- produce({}, state => {1135- state.a = {}1136- expect(isDraft(state.a)).toBeFalsy()1137- })1138- })1139- it("returns false for objects returned by the producer", () => {1140- const object = produce(null, Object.create)1141- expect(isDraft(object)).toBeFalsy()1142- })1143- it("returns false for arrays returned by the producer", () => {1144- const array = produce(null, _ => [])1145- expect(isDraft(array)).toBeFalsy()1146- })1147- it("returns false for object drafts returned by the producer", () => {1148- const object = produce({}, state => state)1149- expect(isDraft(object)).toBeFalsy()1150- })1151- it("returns false for array drafts returned by the producer", () => {1152- const array = produce([], state => state)1153- expect(isDraft(array)).toBeFalsy()1154- })1155- })1110+ describe(`isDraft - ${name}`, () => {1111+ it("returns true for object drafts", () => {1112+ produce({}, state => {1113+ expect(isDraft(state)).toBeTruthy()1114+ })1115+ })1116+ it("returns true for array drafts", () => {1117+ produce([], state => {1118+ expect(isDraft(state)).toBeTruthy()1119+ })1120+ })1121+ it("returns true for objects nested in object drafts", () => {1122+ produce({a: {b: {}}}, state => {1123+ expect(isDraft(state.a)).toBeTruthy()1124+ expect(isDraft(state.a.b)).toBeTruthy()1125+ })1126+ })1127+ it("returns false for new objects added to a draft", () => {1128+ produce({}, state => {1129+ state.a = {}1130+ expect(isDraft(state.a)).toBeFalsy()1131+ })1132+ })1133+ it("returns false for objects returned by the producer", () => {1134+ const object = produce(null, Object.create)1135+ expect(isDraft(object)).toBeFalsy()1136+ })1137+ it("returns false for arrays returned by the producer", () => {1138+ const array = produce(null, _ => [])1139+ expect(isDraft(array)).toBeFalsy()1140+ })1141+ it("returns false for object drafts returned by the producer", () => {1142+ const object = produce({}, state => state)1143+ expect(isDraft(object)).toBeFalsy()1144+ })1145+ it("returns false for array drafts returned by the producer", () => {1146+ const array = produce([], state => state)1147+ expect(isDraft(array)).toBeFalsy()1148+ })1149+ })1150 }1151 1152 function testObjectTypes(produce) {1159- class Foo {1160- constructor(foo) {1161- this.foo = foo1162- this[immerable] = true1163- }1164- }1165- const values = {1166- "empty object": {},1167- "plain object": {a: 1, b: 2},1168- "object (no prototype)": Object.create(null),1169- "empty array": [],1170- "plain array": [1, 2],1171- "class instance (draftable)": new Foo(1)1172- }1173- for (const name in values) {1174- const value = values[name]1175- const copy = shallowCopy(value)1176- testObjectType(name, value)1177- testObjectType(name + " (frozen)", Object.freeze(copy))1178- }1179- function testObjectType(name, base) {1180- describe(name, () => {1181- it("creates a draft", () => {1182- produce(base, draft => {1183- expect(draft).not.toBe(base)1184- expect(shallowCopy(draft, true)).toEqual(base)1185- })1186- })1153+ class Foo {1154+ constructor(foo) {1155+ this.foo = foo1156+ this[immerable] = true1157+ }1158+ }1159+ const values = {1160+ "empty object": {},1161+ "plain object": {a: 1, b: 2},1162+ "object (no prototype)": Object.create(null),1163+ "empty array": [],1164+ "plain array": [1, 2],1165+ "class instance (draftable)": new Foo(1)1166+ }1167+ for (const name in values) {1168+ const value = values[name]1169+ const copy = shallowCopy(value)1170+ testObjectType(name, value)1171+ testObjectType(name + " (frozen)", Object.freeze(copy))1172+ }1173+ function testObjectType(name, base) {1174+ describe(name, () => {1175+ it("creates a draft", () => {1176+ produce(base, draft => {1177+ expect(draft).not.toBe(base)1178+ expect(shallowCopy(draft, true)).toEqual(base)1179+ })1180+ })1181 1188- it("preserves the prototype", () => {1189- const proto = Object.getPrototypeOf(base)1190- produce(base, draft => {1191- expect(Object.getPrototypeOf(draft)).toBe(proto)1192- })1193- })1182+ it("preserves the prototype", () => {1183+ const proto = Object.getPrototypeOf(base)1184+ produce(base, draft => {1185+ expect(Object.getPrototypeOf(draft)).toBe(proto)1186+ })1187+ })1188 1195- it("returns the base state when no changes are made", () => {1196- expect(produce(base, () => {})).toBe(base)1197- })1189+ it("returns the base state when no changes are made", () => {1190+ expect(produce(base, () => {})).toBe(base)1191+ })1192 1199- it("returns a copy when changes are made", () => {1200- const random = Math.random()1201- const result = produce(base, draft => {1202- draft[0] = random1203- })1204- expect(result).not.toBe(base)1205- expect(result.constructor).toBe(base.constructor)1206- expect(result[0]).toBe(random)1207- })1208- })1209- }1193+ it("returns a copy when changes are made", () => {1194+ const random = Math.random()1195+ const result = produce(base, draft => {1196+ draft[0] = random1197+ })1198+ expect(result).not.toBe(base)1199+ expect(result.constructor).toBe(base.constructor)1200+ expect(result[0]).toBe(random)1201+ })1202+ })1203+ }1204 }1205 1206 function testLiteralTypes(produce) {1213- class Foo {}1214- const values = {1215- "falsy number": 0,1216- "truthy number": 1,1217- "negative number": -1,1218- NaN: NaN,1219- infinity: 1 / 0,1220- true: true,1221- false: false,1222- "empty string": "",1223- "truthy string": "1",1224- null: null,1225- undefined: undefined,1207+ class Foo {}1208+ const values = {1209+ "falsy number": 0,1210+ "truthy number": 1,1211+ "negative number": -1,1212+ NaN: NaN,1213+ infinity: 1 / 0,1214+ true: true,1215+ false: false,1216+ "empty string": "",1217+ "truthy string": "1",1218+ null: null,1219+ undefined: undefined,1220 1227- /**1228- * These objects are treated as literals because Immer1229- * does not know how to draft them.1230- */1231- function: () => {},1232- "regexp object": /.+/g,1233- "boxed number": new Number(0),1234- "boxed string": new String(""),1235- "boxed boolean": new Boolean(),1236- "date object": new Date(),1237- "class instance (not draftable)": new Foo()1238- }1239- for (const name in values) {1240- describe(name, () => {1241- const value = values[name]1221+ /**1222+ * These objects are treated as literals because Immer1223+ * does not know how to draft them.1224+ */1225+ function: () => {},1226+ "regexp object": /.+/g,1227+ "boxed number": new Number(0),1228+ "boxed string": new String(""),1229+ "boxed boolean": new Boolean(),1230+ "date object": new Date(),1231+ "class instance (not draftable)": new Foo()1232+ }1233+ for (const name in values) {1234+ describe(name, () => {1235+ const value = values[name]1236 1243- it("does not create a draft", () => {1244- produce(value, draft => {1245- expect(draft).toBe(value)1246- })1247- })1237+ it("does not create a draft", () => {1238+ produce(value, draft => {1239+ expect(draft).toBe(value)1240+ })1241+ })1242 1249- it("returns the base state when no changes are made", () => {1250- expect(produce(value, () => {})).toBe(value)1251- })1243+ it("returns the base state when no changes are made", () => {1244+ expect(produce(value, () => {})).toBe(value)1245+ })1246 1253- if (value && typeof value == "object") {1254- it("does not return a copy when changes are made", () => {1255- expect(1256- produce(value, draft => {1257- draft.foo = true1258- })1259- ).toBe(value)1260- })1261- }1262- })1263- }1247+ if (value && typeof value == "object") {1248+ it("does not return a copy when changes are made", () => {1249+ expect(1250+ produce(value, draft => {1251+ draft.foo = true1252+ })1253+ ).toBe(value)1254+ })1255+ }1256+ })1257+ }1258 }1259 1260 function enumerableOnly(x) {1267- const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1268- each(copy, (prop, value) => {1269- if (value && typeof value === "object") {1270- copy[prop] = enumerableOnly(value)1271- }1272- })1273- return copy1261+ const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1262+ each(copy, (prop, value) => {1263+ if (value && typeof value === "object") {1264+ copy[prop] = enumerableOnly(value)1265+ }1266+ })1267+ return copy1268 }modified:__tests__/curry.js+54 added-60 removed
3 unmodified lines45678989101112131415161718111213141516172021222324181920212223262728293031323324252627283536373839404129303132333435364344453738394047484950515253414243444546474855565758495051525360615455566364656657585960616869707172737475767762636465666768697071723 unmodified linesrunTests("proxy", true)runTests("es5", false)
function runTests(name, useProxies) { describe("curry - " + name, () => { setUseProxies(useProxies) describe("curry - " + name, () => { setUseProxies(useProxies)
it("should check arguments", () => { expect(() => produce()).toThrowErrorMatchingSnapshot() expect(() => produce({})).toThrowErrorMatchingSnapshot() expect(() => produce({}, {})).toThrowErrorMatchingSnapshot() expect(() => produce({}, () => {}, []) ).toThrowErrorMatchingSnapshot() }) it("should check arguments", () => { expect(() => produce()).toThrowErrorMatchingSnapshot() expect(() => produce({})).toThrowErrorMatchingSnapshot() expect(() => produce({}, {})).toThrowErrorMatchingSnapshot() expect(() => produce({}, () => {}, [])).toThrowErrorMatchingSnapshot() })
it("should support currying", () => { const state = [{}, {}, {}] const mapper = produce((item, index) => { item.index = index }) it("should support currying", () => { const state = [{}, {}, {}] const mapper = produce((item, index) => { item.index = index })
expect(state.map(mapper)).not.toBe(state) expect(state.map(mapper)).toEqual([ {index: 0}, {index: 1}, {index: 2} ]) expect(state).toEqual([{}, {}, {}]) }) expect(state.map(mapper)).not.toBe(state) expect(state.map(mapper)).toEqual([{index: 0}, {index: 1}, {index: 2}]) expect(state).toEqual([{}, {}, {}]) })
it("should support returning new states from curring", () => { const reducer = produce((item, index) => { if (!item) { return {hello: "world"} } item.index = index }) it("should support returning new states from curring", () => { const reducer = produce((item, index) => { if (!item) { return {hello: "world"} } item.index = index })
expect(reducer(undefined, 3)).toEqual({hello: "world"}) expect(reducer({}, 3)).toEqual({index: 3}) }) expect(reducer(undefined, 3)).toEqual({hello: "world"}) expect(reducer({}, 3)).toEqual({index: 3}) })
it("should support passing an initial state as second argument", () => { const reducer = produce( (item, index) => { item.index = index }, {hello: "world"} ) it("should support passing an initial state as second argument", () => { const reducer = produce( (item, index) => { item.index = index }, {hello: "world"} )
expect(reducer(undefined, 3)).toEqual({hello: "world", index: 3}) expect(reducer({}, 3)).toEqual({index: 3}) expect(reducer()).toEqual({hello: "world", index: undefined}) }) expect(reducer(undefined, 3)).toEqual({hello: "world", index: 3}) expect(reducer({}, 3)).toEqual({index: 3}) expect(reducer()).toEqual({hello: "world", index: undefined}) })
it("can has fun with change detection", () => { const spread = produce(Object.assign) it("can has fun with change detection", () => { const spread = produce(Object.assign)
const base = { x: 1, y: 1 } const base = { x: 1, y: 1 }
expect({...base}).not.toBe(base) expect(spread(base, {})).toBe(base) expect(spread(base, {y: 1})).toBe(base) expect(spread(base, {...base})).toBe(base) expect(spread(base, {...base, y: 2})).not.toBe(base) expect(spread(base, {...base, y: 2})).toEqual({x: 1, y: 2}) expect(spread(base, {z: 3})).toEqual({x: 1, y: 1, z: 3}) expect(spread(base, {y: 1})).toBe(base) }) }) expect({...base}).not.toBe(base) expect(spread(base, {})).toBe(base) expect(spread(base, {y: 1})).toBe(base) expect(spread(base, {...base})).toBe(base) expect(spread(base, {...base, y: 2})).not.toBe(base) expect(spread(base, {...base, y: 2})).toEqual({x: 1, y: 2}) expect(spread(base, {z: 3})).toEqual({x: 1, y: 1, z: 3}) expect(spread(base, {y: 1})).toBe(base) }) })}modified:__tests__/draft.ts+143 added-143 removed
5 unmodified lines6 declare const fromDraft: <T>(draft: Draft<T>) => T7 8 // DraftArray<T>9 {10- // NOTE: As of 3.2.2, everything fails without "extends any"11- ;<Value extends any>(val: ReadonlyArray<Value>) => {12- val = _ as Draft<typeof val>13- let elem: Value = _ as Draft<Value>14- }10+ // NOTE: As of 3.2.2, everything fails without "extends any"11+ ;<Value extends any>(val: ReadonlyArray<Value>) => {12+ val = _ as Draft<typeof val>13+ let elem: Value = _ as Draft<Value>14+ }15 }16 17 // Tuple18 {19- let val: [1, 2] = _20- assert(toDraft(val), val)21- assert(fromDraft(toDraft(val)), val)19+ let val: [1, 2] = _20+ assert(toDraft(val), val)21+ assert(fromDraft(toDraft(val)), val)22 }23 24 // Tuple (nested in a tuple)25 {26- let val: [[1, 2]] = _27- assert(toDraft(val), val)28- assert(fromDraft(toDraft(val)), val)26+ let val: [[1, 2]] = _27+ assert(toDraft(val), val)28+ assert(fromDraft(toDraft(val)), val)29 }30 31 // Tuple (nested in two mutable arrays)32 {33- let val: [1, 2][][] = _34- let draft: typeof val = _35- val = assert(toDraft(val), draft)36- assert(fromDraft(draft), val)33+ let val: [1, 2][][] = _34+ let draft: typeof val = _35+ val = assert(toDraft(val), draft)36+ assert(fromDraft(draft), val)37 }38 39 // Tuple (nested in two readonly arrays)40 {41- let val: ReadonlyArray<ReadonlyArray<[1, 2]>> = _42- let draft: [1, 2][][] = _43- val = assert(toDraft(val), draft)41+ let val: ReadonlyArray<ReadonlyArray<[1, 2]>> = _42+ let draft: [1, 2][][] = _43+ val = assert(toDraft(val), draft)44 }45 46 // Readonly tuple47 {48- // TODO: Uncomment this when readonly tuples are supported.49- // More info: https://stackoverflow.com/a/53822074/222855950- // let val: Readonly<[1, 2]> = _51- // let draft: [1, 2] = _52- // draft = assert(toDraft(val), draft)53- // val = fromDraft(draft)48+ // TODO: Uncomment this when readonly tuples are supported.49+ // More info: https://stackoverflow.com/a/53822074/222855950+ // let val: Readonly<[1, 2]> = _51+ // let draft: [1, 2] = _52+ // draft = assert(toDraft(val), draft)53+ // val = fromDraft(draft)54 }55 56 // Mutable array57 {58- let val: string[] = _59- assert(toDraft(val), val)60- assert(fromDraft(toDraft(val)), val)58+ let val: string[] = _59+ assert(toDraft(val), val)60+ assert(fromDraft(toDraft(val)), val)61 }62 63 // Mutable array (nested in tuple)64 {65- let val: [string[]] = _66- assert(toDraft(val), val)67- assert(fromDraft(toDraft(val)), val)65+ let val: [string[]] = _66+ assert(toDraft(val), val)67+ assert(fromDraft(toDraft(val)), val)68 }69 70 // Readonly array71 {72- let val: ReadonlyArray<string> = _73- let draft: string[] = _74- val = assert(toDraft(val), draft)75- fromDraft(draft)72+ let val: ReadonlyArray<string> = _73+ let draft: string[] = _74+ val = assert(toDraft(val), draft)75+ fromDraft(draft)76 }77 78 // Readonly array (nested in readonly object)79 {80- let val: {readonly a: ReadonlyArray<string>} = _81- let draft: {a: string[]} = _82- val = assert(toDraft(val), draft)83- fromDraft(draft)80+ let val: {readonly a: ReadonlyArray<string>} = _81+ let draft: {a: string[]} = _82+ val = assert(toDraft(val), draft)83+ fromDraft(draft)84 }85 86 // Mutable object87 {88- let val: {a: 1} = _89- assert(toDraft(val), val)90- assert(fromDraft(toDraft(val)), val)88+ let val: {a: 1} = _89+ assert(toDraft(val), val)90+ assert(fromDraft(toDraft(val)), val)91 }92 93 // Mutable object (nested in mutable object)94 {95- let val: {a: {b: 1}} = _96- assert(toDraft(val), val)97- assert(fromDraft(toDraft(val)), val)95+ let val: {a: {b: 1}} = _96+ assert(toDraft(val), val)97+ assert(fromDraft(toDraft(val)), val)98 }99 100 // Interface101 {102- interface Foo {103- a: {b: number}104- }105- let val: Foo = _106- assert(toDraft(val), val)107- assert(fromDraft(toDraft(val)), val)102+ interface Foo {103+ a: {b: number}104+ }105+ let val: Foo = _106+ assert(toDraft(val), val)107+ assert(fromDraft(toDraft(val)), val)108 }109 110 // Interface (nested in interface)111 {112- interface Foo {113- a: {b: number}114- }115- interface Bar {116- foo: Foo117- }118- let val: Bar = _119- assert(toDraft(val), val)120- assert(fromDraft(toDraft(val)), val)112+ interface Foo {113+ a: {b: number}114+ }115+ interface Bar {116+ foo: Foo117+ }118+ let val: Bar = _119+ assert(toDraft(val), val)120+ assert(fromDraft(toDraft(val)), val)121 }122 123 // Readonly object124 {125- let val: {readonly a: 1} = _126- let draft: {a: 1} = _127- val = assert(toDraft(val), draft)125+ let val: {readonly a: 1} = _126+ let draft: {a: 1} = _127+ val = assert(toDraft(val), draft)128 }129 130 // Readonly object (nested in tuple)131 {132- let val: [{readonly a: 1}] = _133- let draft: [{a: 1}] = _134- val = assert(toDraft(val), draft)132+ let val: [{readonly a: 1}] = _133+ let draft: [{a: 1}] = _134+ val = assert(toDraft(val), draft)135 }136 137 // Loose function138 {139- let val: Function = _140- assert(toDraft(val), val)141- assert(fromDraft(toDraft(val)), val)139+ let val: Function = _140+ assert(toDraft(val), val)141+ assert(fromDraft(toDraft(val)), val)142 }143 144 // Strict function145 {146- let val: () => void = _147- assert(toDraft(val), val)148- assert(fromDraft(toDraft(val)), val)146+ let val: () => void = _147+ assert(toDraft(val), val)148+ assert(fromDraft(toDraft(val)), val)149 }150 151 // Class type (mutable)152 {153- class Foo {154- private test: any155- constructor(public bar: string) {}156- }157- let val: Foo = _158- // TODO: Uncomment this when plain object types can be distinguished from class types.159- // More info here: https://github.com/Microsoft/TypeScript/issues/29063160- // assert(toDraft(val), val)161- // assert(fromDraft(toDraft(val)), val)153+ class Foo {154+ private test: any155+ constructor(public bar: string) {}156+ }157+ let val: Foo = _158+ // TODO: Uncomment this when plain object types can be distinguished from class types.159+ // More info here: https://github.com/Microsoft/TypeScript/issues/29063160+ // assert(toDraft(val), val)161+ // assert(fromDraft(toDraft(val)), val)162 }163 164 // Class type (readonly)165 {166- class Foo {167- private test: any168- constructor(readonly bar: string) {}169- }170- let val: Foo = _171- // TODO: Uncomment this when plain object types can be distinguished from class types.172- // More info here: https://github.com/Microsoft/TypeScript/issues/29063173- // assert(toDraft(val), val)174- // assert(fromDraft(toDraft(val)), val)166+ class Foo {167+ private test: any168+ constructor(readonly bar: string) {}169+ }170+ let val: Foo = _171+ // TODO: Uncomment this when plain object types can be distinguished from class types.172+ // More info here: https://github.com/Microsoft/TypeScript/issues/29063173+ // assert(toDraft(val), val)174+ // assert(fromDraft(toDraft(val)), val)175 }176 177 // Map instance178 {179- let val: Map<any, any> = _180- assert(toDraft(val), val)181- assert(fromDraft(toDraft(val)), val)179+ let val: Map<any, any> = _180+ assert(toDraft(val), val)181+ assert(fromDraft(toDraft(val)), val)182 183- // Weak maps184- let weak: WeakMap<any, any> = _185- assert(toDraft(weak), weak)186- assert(fromDraft(toDraft(weak)), weak)183+ // Weak maps184+ let weak: WeakMap<any, any> = _185+ assert(toDraft(weak), weak)186+ assert(fromDraft(toDraft(weak)), weak)187 }188 189 // Set instance190 {191- let val: Set<any> = _192- assert(toDraft(val), val)193- assert(fromDraft(toDraft(val)), val)191+ let val: Set<any> = _192+ assert(toDraft(val), val)193+ assert(fromDraft(toDraft(val)), val)194 195- // Weak sets196- let weak: WeakSet<any> = _197- assert(toDraft(weak), weak)198- assert(fromDraft(toDraft(weak)), weak)195+ // Weak sets196+ let weak: WeakSet<any> = _197+ assert(toDraft(weak), weak)198+ assert(fromDraft(toDraft(weak)), weak)199 }200 201 // Promise object202 {203- let val: Promise<any> = _204- assert(toDraft(val), val)205- assert(fromDraft(toDraft(val)), val)203+ let val: Promise<any> = _204+ assert(toDraft(val), val)205+ assert(fromDraft(toDraft(val)), val)206 }207 208 // Date instance209 {210- let val: Date = _211- assert(toDraft(val), val)212- assert(fromDraft(toDraft(val)), val)210+ let val: Date = _211+ assert(toDraft(val), val)212+ assert(fromDraft(toDraft(val)), val)213 }214 215 // RegExp instance216 {217- let val: RegExp = _218- assert(toDraft(val), val)219- assert(fromDraft(toDraft(val)), val)217+ let val: RegExp = _218+ assert(toDraft(val), val)219+ assert(fromDraft(toDraft(val)), val)220 }221 222 // Boxed primitive223 {224- let val: Boolean = _225- assert(toDraft(val), val)226- assert(fromDraft(toDraft(val)), val)224+ let val: Boolean = _225+ assert(toDraft(val), val)226+ assert(fromDraft(toDraft(val)), val)227 }228 229 // String literal230 {231- let val: string = _232- assert(toDraft(val), val)233- assert(fromDraft(toDraft(val)), val)231+ let val: string = _232+ assert(toDraft(val), val)233+ assert(fromDraft(toDraft(val)), val)234 }235 236 // Any237 {238- let val: any = _239- assert(toDraft(val), val)240- assert(fromDraft(toDraft(val)), val)238+ let val: any = _239+ assert(toDraft(val), val)240+ assert(fromDraft(toDraft(val)), val)241 }242 243 // Never244 {245- let val: never = _ as never246- assert(toDraft(val), val)247- assert(fromDraft(toDraft(val)), val)245+ let val: never = _ as never246+ assert(toDraft(val), val)247+ assert(fromDraft(toDraft(val)), val)248 }249 250 // Unknown251 {252- let val: unknown = _253- assert(toDraft(val), val)254- assert(fromDraft(toDraft(val)), val)252+ let val: unknown = _253+ assert(toDraft(val), val)254+ assert(fromDraft(toDraft(val)), val)255 }256 257 // Numeral258 {259- let val: 1 = _260- assert(toDraft(val), val)261- assert(fromDraft(toDraft(val)), val)259+ let val: 1 = _260+ assert(toDraft(val), val)261+ assert(fromDraft(toDraft(val)), val)262 }263 264 // Union of numerals265 {266- let val: 1 | 2 | 3 = _267- assert(toDraft(val), val)268- assert(fromDraft(toDraft(val)), val)266+ let val: 1 | 2 | 3 = _267+ assert(toDraft(val), val)268+ assert(fromDraft(toDraft(val)), val)269 }270 271 // Union of tuple, array, object272 {273- let val: [0] | ReadonlyArray<string> | Readonly<{a: 1}> = _274- let draft: [0] | string[] | {a: 1} = _275- val = assert(toDraft(val), draft)273+ let val: [0] | ReadonlyArray<string> | Readonly<{a: 1}> = _274+ let draft: [0] | string[] | {a: 1} = _275+ val = assert(toDraft(val), draft)276 }277 278 // Generic type279 {280- // NOTE: "extends any" only helps a little.281- const $ = <T extends any>(val: ReadonlyArray<T>) => {282- let draft: Draft<typeof val> = _283- val = assert(toDraft(val), draft)284- // $ExpectError: [ts] Argument of type 'DraftArray<T>' is not assignable to parameter of type 'Draft<T>'. [2345]285- // assert(fromDraft(draft), draft)286- }280+ // NOTE: "extends any" only helps a little.281+ const $ = <T extends any>(val: ReadonlyArray<T>) => {282+ let draft: Draft<typeof val> = _283+ val = assert(toDraft(val), draft)284+ // $ExpectError: [ts] Argument of type 'DraftArray<T>' is not assignable to parameter of type 'Draft<T>'. [2345]285+ // assert(fromDraft(draft), draft)286+ }287 }modified:__tests__/frozen.js+111 added-111 removed
5 unmodified lines6 runTests("proxy", true)7 runTests("es5", false)8 9 function 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)13 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- })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+ })24 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- })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+ })33 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- })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+ })43 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- })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+ })54 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- })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+ })62 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- })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+ })69 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- })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+ })76 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- })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+ })83 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- })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+ })90 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- })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+ })99 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- })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+ })109 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- })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+ })121 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- })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+202 added-202 removed
4 unmodified lines5 describe("hooks (proxy) -", () => createHookTests(true))6 describe("hooks (es5) -", () => createHookTests(false))7 8 function createHookTests(useProxies) {9- let produce, onAssign, onDelete, onCopy9+ let produce, onAssign, onDelete, onCopy10 11- beforeEach(() => {12- ;({produce, onAssign, onDelete, onCopy} = new Immer({13- autoFreeze: true,14- useProxies,15- onAssign: defuseProxies(jest.fn().mockName("onAssign")),16- onDelete: defuseProxies(jest.fn().mockName("onDelete")),17- onCopy: defuseProxies(jest.fn().mockName("onCopy"))18- }))19- })11+ beforeEach(() => {12+ ;({produce, onAssign, onDelete, onCopy} = new Immer({13+ autoFreeze: true,14+ useProxies,15+ onAssign: defuseProxies(jest.fn().mockName("onAssign")),16+ onDelete: defuseProxies(jest.fn().mockName("onDelete")),17+ onCopy: defuseProxies(jest.fn().mockName("onCopy"))18+ }))19+ })20 21- describe("onAssign()", () => {22- useSharedTests(() => onAssign)23- describe("when draft is an object", () => {24- test("assign", () => {25- produce({a: 0, b: 0, c: 0}, s => {26- s.a++27- s.c++28- })29- expectCalls(onAssign)30- })31- test("assign (no change)", () => {32- produce({a: 0}, s => {33- s.a = 034- })35- expect(onAssign).not.toBeCalled()36- })37- test("delete", () => {38- produce({a: 1}, s => {39- delete s.a40- })41- expect(onAssign).not.toBeCalled()42- })43- test("nested assignments", () => {44- produce({a: {b: {c: 1, d: 1, e: 1}}}, s => {45- const {b} = s.a46- b.c = 247- delete b.d48- b.e = 1 // no-op49- })50- expectCalls(onAssign)51- })52- })53- describe("when draft is an array", () => {54- test("assign", () => {55- produce([1], s => {56- s[0] = 057- })58- expectCalls(onAssign)59- })60- test("push", () => {61- produce([], s => {62- s.push(4)63- })64- expectCalls(onAssign)65- })66- test("pop", () => {67- produce([1], s => {68- s.pop()69- })70- expect(onAssign).not.toBeCalled()71- })72- test("unshift", () => {73- produce([1], s => {74- s.unshift(0)75- })76- expectCalls(onAssign)77- })78- test("length = 0", () => {79- produce([1], s => {80- s.length = 081- })82- expect(onAssign).not.toBeCalled()83- })84- test("splice (length += 1)", () => {85- produce([1, 2, 3], s => {86- s.splice(1, 1, 0, 0)87- })88- expectCalls(onAssign)89- })90- test("splice (length += 0)", () => {91- produce([1, 2, 3], s => {92- s.splice(1, 1, 0)93- })94- expectCalls(onAssign)95- })96- test("splice (length -= 1)", () => {97- produce([1, 2, 3], s => {98- s.splice(0, 2, 6)99- })100- expectCalls(onAssign)101- })102- })103- describe("when a draft is moved into a new object", () => {104- it("is called in the right order", () => {105- const calls = []106- onAssign.mockImplementation((_, prop) => {107- calls.push(prop)108- })109- produce({a: {b: 1, c: {}}}, s => {110- s.a.b = 0111- s.a.c.d = 1112- s.x = {y: {z: s.a}}113- delete s.a114- })115- // Sibling properties use enumeration order, which means new116- // properties come last among their siblings. The deepest117- // properties always come first in their ancestor chain.118- expect(calls).toEqual(["b", "d", "c", "x"])119- })120- })121- })21+ describe("onAssign()", () => {22+ useSharedTests(() => onAssign)23+ describe("when draft is an object", () => {24+ test("assign", () => {25+ produce({a: 0, b: 0, c: 0}, s => {26+ s.a++27+ s.c++28+ })29+ expectCalls(onAssign)30+ })31+ test("assign (no change)", () => {32+ produce({a: 0}, s => {33+ s.a = 034+ })35+ expect(onAssign).not.toBeCalled()36+ })37+ test("delete", () => {38+ produce({a: 1}, s => {39+ delete s.a40+ })41+ expect(onAssign).not.toBeCalled()42+ })43+ test("nested assignments", () => {44+ produce({a: {b: {c: 1, d: 1, e: 1}}}, s => {45+ const {b} = s.a46+ b.c = 247+ delete b.d48+ b.e = 1 // no-op49+ })50+ expectCalls(onAssign)51+ })52+ })53+ describe("when draft is an array", () => {54+ test("assign", () => {55+ produce([1], s => {56+ s[0] = 057+ })58+ expectCalls(onAssign)59+ })60+ test("push", () => {61+ produce([], s => {62+ s.push(4)63+ })64+ expectCalls(onAssign)65+ })66+ test("pop", () => {67+ produce([1], s => {68+ s.pop()69+ })70+ expect(onAssign).not.toBeCalled()71+ })72+ test("unshift", () => {73+ produce([1], s => {74+ s.unshift(0)75+ })76+ expectCalls(onAssign)77+ })78+ test("length = 0", () => {79+ produce([1], s => {80+ s.length = 081+ })82+ expect(onAssign).not.toBeCalled()83+ })84+ test("splice (length += 1)", () => {85+ produce([1, 2, 3], s => {86+ s.splice(1, 1, 0, 0)87+ })88+ expectCalls(onAssign)89+ })90+ test("splice (length += 0)", () => {91+ produce([1, 2, 3], s => {92+ s.splice(1, 1, 0)93+ })94+ expectCalls(onAssign)95+ })96+ test("splice (length -= 1)", () => {97+ produce([1, 2, 3], s => {98+ s.splice(0, 2, 6)99+ })100+ expectCalls(onAssign)101+ })102+ })103+ describe("when a draft is moved into a new object", () => {104+ it("is called in the right order", () => {105+ const calls = []106+ onAssign.mockImplementation((_, prop) => {107+ calls.push(prop)108+ })109+ produce({a: {b: 1, c: {}}}, s => {110+ s.a.b = 0111+ s.a.c.d = 1112+ s.x = {y: {z: s.a}}113+ delete s.a114+ })115+ // Sibling properties use enumeration order, which means new116+ // properties come last among their siblings. The deepest117+ // properties always come first in their ancestor chain.118+ expect(calls).toEqual(["b", "d", "c", "x"])119+ })120+ })121+ })122 123- describe("onDelete()", () => {124- useSharedTests(() => onDelete)125- describe("when draft is an object -", () => {126- test("delete", () => {127- produce({a: 1, b: 1, c: 1}, s => {128- delete s.a129- delete s.c130- })131- expectCalls(onDelete)132- })133- test("delete (no change)", () => {134- produce({}, s => {135- delete s.a136- })137- expect(onDelete).not.toBeCalled()138- })139- test("nested deletions", () => {140- produce({a: {b: {c: 1}}}, s => {141- delete s.a.b.c142- })143- expectCalls(onDelete)144- })145- })146- describe("when draft is an array -", () => {147- test("pop", () => {148- produce([1], s => {149- s.pop()150- })151- expectCalls(onDelete)152- })153- test("length = 0", () => {154- produce([1], s => {155- s.length = 0156- })157- expectCalls(onDelete)158- })159- test("splice (length -= 1)", () => {160- produce([1, 2, 3], s => {161- s.splice(0, 2, 6)162- })163- expectCalls(onDelete)164- })165- })166- })123+ describe("onDelete()", () => {124+ useSharedTests(() => onDelete)125+ describe("when draft is an object -", () => {126+ test("delete", () => {127+ produce({a: 1, b: 1, c: 1}, s => {128+ delete s.a129+ delete s.c130+ })131+ expectCalls(onDelete)132+ })133+ test("delete (no change)", () => {134+ produce({}, s => {135+ delete s.a136+ })137+ expect(onDelete).not.toBeCalled()138+ })139+ test("nested deletions", () => {140+ produce({a: {b: {c: 1}}}, s => {141+ delete s.a.b.c142+ })143+ expectCalls(onDelete)144+ })145+ })146+ describe("when draft is an array -", () => {147+ test("pop", () => {148+ produce([1], s => {149+ s.pop()150+ })151+ expectCalls(onDelete)152+ })153+ test("length = 0", () => {154+ produce([1], s => {155+ s.length = 0156+ })157+ expectCalls(onDelete)158+ })159+ test("splice (length -= 1)", () => {160+ produce([1, 2, 3], s => {161+ s.splice(0, 2, 6)162+ })163+ expectCalls(onDelete)164+ })165+ })166+ })167 168- describe("onCopy()", () => {169- useSharedTests(() => onCopy)170- it("is called in the right order", () => {171- const calls = []172- onCopy.mockImplementation(s => {173- calls.push(s.base)174- })175- const base = {a: {b: {c: 1}}}176- produce(base, s => {177- delete s.a.b.c178- })179- expect(calls).toShallowEqual([base.a.b, base.a, base])180- })181- })168+ describe("onCopy()", () => {169+ useSharedTests(() => onCopy)170+ it("is called in the right order", () => {171+ const calls = []172+ onCopy.mockImplementation(s => {173+ calls.push(s.base)174+ })175+ const base = {a: {b: {c: 1}}}176+ produce(base, s => {177+ delete s.a.b.c178+ })179+ expect(calls).toShallowEqual([base.a.b, base.a, base])180+ })181+ })182 183- function useSharedTests(getHook) {184- it("is called before the parent is frozen", () => {185- const hook = getHook()186- hook.mockImplementation(s => {187- // Parent object must not be frozen.188- expect(Object.isFrozen(s.base)).toBeFalsy()189- })190- produce({a: {b: {c: 0}}}, s => {191- if (hook == onDelete) delete s.a.b.c192- else s.a.b.c = 1193- })194- expect(hook).toHaveBeenCalledTimes(hook == onDelete ? 1 : 3)195- })196- }183+ function useSharedTests(getHook) {184+ it("is called before the parent is frozen", () => {185+ const hook = getHook()186+ hook.mockImplementation(s => {187+ // Parent object must not be frozen.188+ expect(Object.isFrozen(s.base)).toBeFalsy()189+ })190+ produce({a: {b: {c: 0}}}, s => {191+ if (hook == onDelete) delete s.a.b.c192+ else s.a.b.c = 1193+ })194+ expect(hook).toHaveBeenCalledTimes(hook == onDelete ? 1 : 3)195+ })196+ }197 }198 199 // Produce a snapshot of the hook arguments (minus any draft state).200 function expectCalls(hook) {201- expect(202- hook.mock.calls.map(call => {203- return call.slice(1)204- })205- ).toMatchSnapshot()201+ expect(202+ hook.mock.calls.map(call => {203+ return call.slice(1)204+ })205+ ).toMatchSnapshot()206 }207 208 // For defusing draft proxies.209 function defuseProxies(fn) {210- return Object.assign((...args) => {211- expect(args[0].finalized).toBeTruthy()212- args[0].draft = args[0].drafts = null213- fn(...args)214- }, fn)210+ return Object.assign((...args) => {211+ expect(args[0].finalized).toBeTruthy()212+ args[0].draft = args[0].drafts = null213+ fn(...args)214+ }, fn)215 }216 217 expect.extend({218- toShallowEqual(received, expected) {219- const match = matchers.toBe(received, expected)220- return match.pass || !received || typeof received !== "object"221- ? match222- : !Array.isArray(expected) ||223- (Array.isArray(received) && received.length === expected.length)224- ? matchers.toEqual(received, expected)225- : match226- }218+ toShallowEqual(received, expected) {219+ const match = matchers.toBe(received, expected)220+ return match.pass || !received || typeof received !== "object"221+ ? match222+ : !Array.isArray(expected) ||223+ (Array.isArray(received) && received.length === expected.length)224+ ? matchers.toEqual(received, expected)225+ : match226+ }227 })modified:__tests__/immutable.ts+18 added-18 removed
12345676789101112131213141516171819181920212223242524252627282930313031323334353637363738394041424342434445464748494849505152535455545556import {assert, _} from "spec.ts"import {Immutable} from "../dist/immer.js"
// array in tuple{ let val = _ as Immutable<[string[], 1]> assert(val, _ as readonly [ReadonlyArray<string>, 1]) let val = _ as Immutable<[string[], 1]> assert(val, _ as readonly [ReadonlyArray<string>, 1])}
// tuple in array{ let val = _ as Immutable<[string, 1][]> assert(val, _ as ReadonlyArray<readonly [string, 1]>) let val = _ as Immutable<[string, 1][]> assert(val, _ as ReadonlyArray<readonly [string, 1]>)}
// tuple in tuple{ let val = _ as Immutable<[[string, 1], 1]> assert(val, _ as readonly [readonly [string, 1], 1]) let val = _ as Immutable<[[string, 1], 1]> assert(val, _ as readonly [readonly [string, 1], 1])}
// array in array{ let val = _ as Immutable<string[][]> assert(val, _ as ReadonlyArray<ReadonlyArray<string>>) let val = _ as Immutable<string[][]> assert(val, _ as ReadonlyArray<ReadonlyArray<string>>)}
// tuple in object{ let val = _ as Immutable<{a: [string, 1]}> assert(val, _ as {readonly a: readonly [string, 1]}) let val = _ as Immutable<{a: [string, 1]}> assert(val, _ as {readonly a: readonly [string, 1]})}
// object in tuple{ let val = _ as Immutable<[{a: string}, 1]> assert(val, _ as readonly [{readonly a: string}, 1]) let val = _ as Immutable<[{a: string}, 1]> assert(val, _ as readonly [{readonly a: string}, 1])}
// array in object{ let val = _ as Immutable<{a: string[]}> assert(val, _ as {readonly a: ReadonlyArray<string>}) let val = _ as Immutable<{a: string[]}> assert(val, _ as {readonly a: ReadonlyArray<string>})}
// object in array{ let val = _ as Immutable<Array<{a: string}>> assert(val, _ as ReadonlyArray<{readonly a: string}>) let val = _ as Immutable<Array<{a: string}>> assert(val, _ as ReadonlyArray<{readonly a: string}>)}
// object in object{ let val = _ as Immutable<{a: {b: string}}> assert(val, _ as {readonly a: {readonly b: string}}) let val = _ as Immutable<{a: {b: string}}> assert(val, _ as {readonly a: {readonly b: string}})}modified:__tests__/manual.js+104 added-104 removed
1 "use strict"2 import {3- setUseProxies,4- createDraft,5- finishDraft,6- produce,7- isDraft3+ setUseProxies,4+ createDraft,5+ finishDraft,6+ produce,7+ isDraft8 } from "../src/index"9 10 runTests("proxy", true)11 runTests("es5", false)12 13 function runTests(name, useProxies) {14- describe("manual - " + name, () => {15- setUseProxies(useProxies)14+ describe("manual - " + name, () => {15+ setUseProxies(useProxies)16 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- })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+ })23 24- it("should support manual drafts", () => {25- const state = [{}, {}, {}]24+ it("should support manual drafts", () => {25+ const state = [{}, {}, {}]26 27- 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+ })31 32- const result = finishDraft(draft)32+ const result = finishDraft(draft)33 34- 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+ })38 39- it("cannot modify after finish", () => {40- const state = {a: 1}39+ it("cannot modify after finish", () => {40+ const state = {a: 1}41 42- 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+ })49 50- it("should support patches drafts", () => {51- const state = {a: 1}50+ it("should support patches drafts", () => {51+ const state = {a: 1}52 53- const draft = createDraft(state)54- draft.a = 255- draft.b = 353+ const draft = createDraft(state)54+ draft.a = 255+ draft.b = 356 57- const listener = jest.fn()58- const result = finishDraft(draft, listener)57+ const listener = jest.fn()58+ const result = finishDraft(draft, listener)59 60- 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+ })64 65- 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}67 68- const draft = createDraft(state)69- draft.a = 268+ const draft = createDraft(state)69+ draft.a = 270 71- const draft2 = createDraft(state)72- draft2.b = 371+ const draft2 = createDraft(state)72+ draft2.b = 373 74- const result = finishDraft(draft)74+ const result = finishDraft(draft)75 76- expect(result).not.toBe(state)77- expect(result).toEqual({a: 2})76+ expect(result).not.toBe(state)77+ expect(result).toEqual({a: 2})78 79- 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+ })84 85- it("combines with produce - 1", () => {86- const state = {a: 1}85+ it("combines with produce - 1", () => {86+ const state = {a: 1}87 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- })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+ })98 99- it("combines with produce - 2", () => {100- const state = {a: 1}99+ it("combines with produce - 2", () => {100+ const state = {a: 1}101 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- })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+ })122 123- 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+ })128 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- })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
1234556789107891011"use strict"import produce from "../src/index"
describe("null functionality", () => { const baseState = null const baseState = null
it("should return the original without modifications", () => { const nextState = produce(baseState, () => {}) expect(nextState).toBe(baseState) }) it("should return the original without modifications", () => { const nextState = produce(baseState, () => {}) expect(nextState).toBe(baseState) })})modified:__tests__/original.js+37 added-37 removed
1 "use strict"2 import produce, {original, setUseProxies} from "../src/index"3 4 describe("original", () => {5- const baseState = {6- a: [],7- b: {}8- }5+ const baseState = {6+ a: [],7+ b: {}8+ }9 10- it("should return the original from the draft", () => {11- setUseProxies(true)10+ it("should return the original from the draft", () => {11+ setUseProxies(true)12 13- produce(baseState, draftState => {14- expect(original(draftState)).toBe(baseState)15- expect(original(draftState.a)).toBe(baseState.a)16- expect(original(draftState.b)).toBe(baseState.b)17- })13+ produce(baseState, draftState => {14+ expect(original(draftState)).toBe(baseState)15+ expect(original(draftState.a)).toBe(baseState.a)16+ expect(original(draftState.b)).toBe(baseState.b)17+ })18 19- setUseProxies(false)19+ setUseProxies(false)20 21- produce(baseState, draftState => {22- expect(original(draftState)).toBe(baseState)23- expect(original(draftState.a)).toBe(baseState.a)24- expect(original(draftState.b)).toBe(baseState.b)25- })26- })21+ produce(baseState, draftState => {22+ expect(original(draftState)).toBe(baseState)23+ expect(original(draftState.a)).toBe(baseState.a)24+ expect(original(draftState.b)).toBe(baseState.b)25+ })26+ })27 28- it("should return the original from the proxy", () => {29- produce(baseState, draftState => {30- expect(original(draftState)).toBe(baseState)31- expect(original(draftState.a)).toBe(baseState.a)32- expect(original(draftState.b)).toBe(baseState.b)33- })34- })28+ it("should return the original from the proxy", () => {29+ produce(baseState, draftState => {30+ expect(original(draftState)).toBe(baseState)31+ expect(original(draftState.a)).toBe(baseState.a)32+ expect(original(draftState.b)).toBe(baseState.b)33+ })34+ })35 36- it("should return undefined for new values on the draft", () => {37- produce(baseState, draftState => {38- draftState.c = {}39- draftState.d = 340- expect(original(draftState.c)).toBeUndefined()41- expect(original(draftState.d)).toBeUndefined()42- })43- })36+ it("should return undefined for new values on the draft", () => {37+ produce(baseState, draftState => {38+ draftState.c = {}39+ draftState.d = 340+ expect(original(draftState.c)).toBeUndefined()41+ expect(original(draftState.d)).toBeUndefined()42+ })43+ })44 45- it("should return undefined for an object that is not proxied", () => {46- expect(original({})).toBeUndefined()47- expect(original(3)).toBeUndefined()48- })45+ it("should return undefined for an object that is not proxied", () => {46+ expect(original({})).toBeUndefined()47+ expect(original(3)).toBeUndefined()48+ })49 })modified:__tests__/patch.js+324 added-330 removed
2 unmodified lines3 4 jest.setTimeout(1000)5 6 function 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- })7+ function runPatchTestHelper() {8+ let recordedPatches9+ let recordedInversePatches10+ const res = produce(base, producer, (p, i) => {11+ recordedPatches = p12+ recordedInversePatches = i13+ })14 15- test("produces the correct patches", () => {16- expect(recordedPatches).toEqual(patches)17- if (inversePathes)18- expect(recordedInversePatches).toEqual(inversePathes)19- })15+ test("produces the correct patches", () => {16+ expect(recordedPatches).toEqual(patches)17+ if (inversePathes) expect(recordedInversePatches).toEqual(inversePathes)18+ })19 21- test("patches are replayable", () => {22- expect(applyPatches(base, recordedPatches)).toEqual(res)23- })20+ test("patches are replayable", () => {21+ expect(applyPatches(base, recordedPatches)).toEqual(res)22+ })23 25- test("patches can be reversed", () => {26- expect(applyPatches(res, recordedInversePatches)).toEqual(base)27- })28- }24+ test("patches can be reversed", () => {25+ expect(applyPatches(res, recordedInversePatches)).toEqual(base)26+ })27+ }28 30- describe(`proxy`, () => {31- setUseProxies(true)32- runPatchTestHelper()33- })29+ describe(`proxy`, () => {30+ setUseProxies(true)31+ runPatchTestHelper()32+ })33 35- describe(`es5`, () => {36- setUseProxies(false)37- runPatchTestHelper()38- })34+ describe(`es5`, () => {35+ setUseProxies(false)36+ runPatchTestHelper()37+ })38 }39 40 describe("applyPatches", () => {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, [54- {op: "replace", path: ["a"], value: 2}55- ])56- expect(result).not.toBe(base)57- expect(result.a).toBe(2)58- expect(base.a).toBe(1)59- })60- it('throws when `op` is not "add", "replace", nor "remove"', () => {61- expect(() => {62- const patch = {op: "copy", from: [0], path: [1]}63- applyPatches([2], [patch])64- }).toThrowErrorMatchingSnapshot()65- })66- it("throws when `path` cannot be resolved", () => {67- // missing parent68- expect(() => {69- const patch = {op: "add", path: ["a", "b"], value: 1}70- applyPatches({}, [patch])71- }).toThrowErrorMatchingSnapshot()41+ it("mutates the base state when it is a draft", () => {42+ produce({a: 1}, draft => {43+ const result = applyPatches(draft, [44+ {op: "replace", path: ["a"], value: 2}45+ ])46+ expect(result).toBe(draft)47+ expect(draft.a).toBe(2)48+ })49+ })50+ it("produces a copy of the base state when not a draft", () => {51+ const base = {a: 1}52+ const result = applyPatches(base, [{op: "replace", path: ["a"], value: 2}])53+ expect(result).not.toBe(base)54+ expect(result.a).toBe(2)55+ expect(base.a).toBe(1)56+ })57+ it('throws when `op` is not "add", "replace", nor "remove"', () => {58+ expect(() => {59+ const patch = {op: "copy", from: [0], path: [1]}60+ applyPatches([2], [patch])61+ }).toThrowErrorMatchingSnapshot()62+ })63+ it("throws when `path` cannot be resolved", () => {64+ // missing parent65+ expect(() => {66+ const patch = {op: "add", path: ["a", "b"], value: 1}67+ applyPatches({}, [patch])68+ }).toThrowErrorMatchingSnapshot()69 73- // missing grand-parent74- expect(() => {75- const patch = {op: "add", path: ["a", "b", "c"], value: 1}76- applyPatches({}, [patch])77- }).toThrowErrorMatchingSnapshot()78- })70+ // missing grand-parent71+ expect(() => {72+ const patch = {op: "add", path: ["a", "b", "c"], value: 1}73+ applyPatches({}, [patch])74+ }).toThrowErrorMatchingSnapshot()75+ })76 })77 78 describe("simple assignment - 1", () => {82- runPatchTest(83- {x: 3},84- d => {85- d.x++86- },87- [{op: "replace", path: ["x"], value: 4}]88- )79+ runPatchTest(80+ {x: 3},81+ d => {82+ d.x++83+ },84+ [{op: "replace", path: ["x"], value: 4}]85+ )86 })87 88 describe("simple assignment - 2", () => {92- runPatchTest(93- {x: {y: 4}},94- d => {95- d.x.y++96- },97- [{op: "replace", path: ["x", "y"], value: 5}]98- )89+ runPatchTest(90+ {x: {y: 4}},91+ d => {92+ d.x.y++93+ },94+ [{op: "replace", path: ["x", "y"], value: 5}]95+ )96 })97 98 describe("simple assignment - 3", () => {102- runPatchTest(103- {x: [{y: 4}]},104- d => {105- d.x[0].y++106- },107- [{op: "replace", path: ["x", 0, "y"], value: 5}]108- )99+ runPatchTest(100+ {x: [{y: 4}]},101+ d => {102+ d.x[0].y++103+ },104+ [{op: "replace", path: ["x", 0, "y"], value: 5}]105+ )106 })107 108 describe("delete 1", () => {112- runPatchTest(113- {x: {y: 4}},114- d => {115- delete d.x116- },117- [{op: "remove", path: ["x"]}]118- )109+ runPatchTest(110+ {x: {y: 4}},111+ d => {112+ delete d.x113+ },114+ [{op: "remove", path: ["x"]}]115+ )116 })117 118 describe("renaming properties", () => {122- describe("nested object (no changes)", () => {123- runPatchTest(124- {a: {b: 1}},125- d => {126- d.x = d.a127- delete d.a128- },129- [130- {op: "add", path: ["x"], value: {b: 1}},131- {op: "remove", path: ["a"]}132- ]133- )134- })119+ describe("nested object (no changes)", () => {120+ runPatchTest(121+ {a: {b: 1}},122+ d => {123+ d.x = d.a124+ delete d.a125+ },126+ [{op: "add", path: ["x"], value: {b: 1}}, {op: "remove", path: ["a"]}]127+ )128+ })129 136- describe("nested object (with changes)", () => {137- runPatchTest(138- {a: {b: 1, c: 1}},139- d => {140- let a = d.a141- a.b = 2 // change142- delete a.c // delete143- a.y = 2 // add130+ describe("nested object (with changes)", () => {131+ runPatchTest(132+ {a: {b: 1, c: 1}},133+ d => {134+ let a = d.a135+ a.b = 2 // change136+ delete a.c // delete137+ a.y = 2 // add138 145- // rename146- d.x = a147- delete d.a148- },149- [150- {op: "add", path: ["x"], value: {b: 2, y: 2}},151- {op: "remove", path: ["a"]}152- ]153- )154- })139+ // rename140+ d.x = a141+ delete d.a142+ },143+ [144+ {op: "add", path: ["x"], value: {b: 2, y: 2}},145+ {op: "remove", path: ["a"]}146+ ]147+ )148+ })149 156- describe("deeply nested object (with changes)", () => {157- runPatchTest(158- {a: {b: {c: 1, d: 1}}},159- d => {160- let b = d.a.b161- b.c = 2 // change162- delete b.d // delete163- b.y = 2 // add150+ describe("deeply nested object (with changes)", () => {151+ runPatchTest(152+ {a: {b: {c: 1, d: 1}}},153+ d => {154+ let b = d.a.b155+ b.c = 2 // change156+ delete b.d // delete157+ b.y = 2 // add158 165- // rename166- d.a.x = b167- delete d.a.b168- },169- [170- {op: "add", path: ["a", "x"], value: {c: 2, y: 2}},171- {op: "remove", path: ["a", "b"]}172- ]173- )174- })159+ // rename160+ d.a.x = b161+ delete d.a.b162+ },163+ [164+ {op: "add", path: ["a", "x"], value: {c: 2, y: 2}},165+ {op: "remove", path: ["a", "b"]}166+ ]167+ )168+ })169 })170 171 describe("minimum amount of changes", () => {178- runPatchTest(179- {x: 3, y: {a: 4}, z: 3},180- d => {181- d.y.a = 4182- d.y.b = 5183- Object.assign(d, {x: 4, y: {a: 2}})184- },185- [186- {op: "replace", path: ["x"], value: 4},187- {op: "replace", path: ["y"], value: {a: 2}}188- ]189- )172+ runPatchTest(173+ {x: 3, y: {a: 4}, z: 3},174+ d => {175+ d.y.a = 4176+ d.y.b = 5177+ Object.assign(d, {x: 4, y: {a: 2}})178+ },179+ [180+ {op: "replace", path: ["x"], value: 4},181+ {op: "replace", path: ["y"], value: {a: 2}}182+ ]183+ )184 })185 186 describe("arrays - prepend", () => {193- runPatchTest(194- {x: [1, 2, 3]},195- d => {196- d.x.unshift(4)197- },198- [{op: "add", path: ["x", 0], value: 4}]199- )187+ runPatchTest(188+ {x: [1, 2, 3]},189+ d => {190+ d.x.unshift(4)191+ },192+ [{op: "add", path: ["x", 0], value: 4}]193+ )194 })195 196 describe("arrays - multiple prepend", () => {203- runPatchTest(204- {x: [1, 2, 3]},205- d => {206- d.x.unshift(4)207- d.x.unshift(5)208- },209- [210- {op: "add", path: ["x", 0], value: 5},211- {op: "add", path: ["x", 1], value: 4}212- ]213- )197+ runPatchTest(198+ {x: [1, 2, 3]},199+ d => {200+ d.x.unshift(4)201+ d.x.unshift(5)202+ },203+ [204+ {op: "add", path: ["x", 0], value: 5},205+ {op: "add", path: ["x", 1], value: 4}206+ ]207+ )208 })209 210 describe("arrays - splice middle", () => {217- runPatchTest(218- {x: [1, 2, 3]},219- d => {220- d.x.splice(1, 1)221- },222- [{op: "remove", path: ["x", 1]}]223- )211+ runPatchTest(212+ {x: [1, 2, 3]},213+ d => {214+ d.x.splice(1, 1)215+ },216+ [{op: "remove", path: ["x", 1]}]217+ )218 })219 220 describe("arrays - multiple splice", () => {227- runPatchTest(228- [0, 1, 2, 3, 4, 5, 0],229- d => {230- d.splice(4, 2, 3)231- d.splice(1, 2, 3)232- },233- [234- {op: "replace", path: [1], value: 3},235- {op: "replace", path: [2], value: 3},236- {op: "remove", path: [5]},237- {op: "remove", path: [4]}238- ]239- )221+ runPatchTest(222+ [0, 1, 2, 3, 4, 5, 0],223+ d => {224+ d.splice(4, 2, 3)225+ d.splice(1, 2, 3)226+ },227+ [228+ {op: "replace", path: [1], value: 3},229+ {op: "replace", path: [2], value: 3},230+ {op: "remove", path: [5]},231+ {op: "remove", path: [4]}232+ ]233+ )234 })235 236 describe("arrays - modify and shrink", () => {243- runPatchTest(244- {x: [1, 2, 3]},245- d => {246- d.x[0] = 4247- d.x.length = 2248- },249- [250- {op: "replace", path: ["x", 0], value: 4},251- {op: "replace", path: ["x", "length"], value: 2}252- ]253- )237+ runPatchTest(238+ {x: [1, 2, 3]},239+ d => {240+ d.x[0] = 4241+ d.x.length = 2242+ },243+ [244+ {op: "replace", path: ["x", 0], value: 4},245+ {op: "replace", path: ["x", "length"], value: 2}246+ ]247+ )248 })249 250 describe("arrays - prepend then splice middle", () => {257- runPatchTest(258- {x: [1, 2, 3]},259- d => {260- d.x.unshift(4)261- d.x.splice(2, 1)262- },263- [264- {op: "replace", path: ["x", 0], value: 4},265- {op: "replace", path: ["x", 1], value: 1}266- ]267- )251+ runPatchTest(252+ {x: [1, 2, 3]},253+ d => {254+ d.x.unshift(4)255+ d.x.splice(2, 1)256+ },257+ [258+ {op: "replace", path: ["x", 0], value: 4},259+ {op: "replace", path: ["x", 1], value: 1}260+ ]261+ )262 })263 264 describe("arrays - splice middle then prepend", () => {271- runPatchTest(272- {x: [1, 2, 3]},273- d => {274- d.x.splice(1, 1)275- d.x.unshift(4)276- },277- [278- {op: "replace", path: ["x", 0], value: 4},279- {op: "replace", path: ["x", 1], value: 1}280- ]281- )265+ runPatchTest(266+ {x: [1, 2, 3]},267+ d => {268+ d.x.splice(1, 1)269+ d.x.unshift(4)270+ },271+ [272+ {op: "replace", path: ["x", 0], value: 4},273+ {op: "replace", path: ["x", 1], value: 1}274+ ]275+ )276 })277 278 describe("arrays - truncate", () => {285- runPatchTest(286- {x: [1, 2, 3]},287- d => {288- d.x.length -= 2289- },290- [{op: "replace", path: ["x", "length"], value: 1}],291- [292- {op: "add", path: ["x", 1], value: 2},293- {op: "add", path: ["x", 2], value: 3}294- ]295- )279+ runPatchTest(280+ {x: [1, 2, 3]},281+ d => {282+ d.x.length -= 2283+ },284+ [{op: "replace", path: ["x", "length"], value: 1}],285+ [286+ {op: "add", path: ["x", 1], value: 2},287+ {op: "add", path: ["x", 2], value: 3}288+ ]289+ )290 })291 292 describe("arrays - pop twice", () => {299- runPatchTest(300- {x: [1, 2, 3]},301- d => {302- d.x.pop()303- d.x.pop()304- },305- [{op: "replace", path: ["x", "length"], value: 1}]306- )293+ runPatchTest(294+ {x: [1, 2, 3]},295+ d => {296+ d.x.pop()297+ d.x.pop()298+ },299+ [{op: "replace", path: ["x", "length"], value: 1}]300+ )301 })302 303 describe("arrays - push multiple", () => {310- runPatchTest(311- {x: [1, 2, 3]},312- d => {313- d.x.push(4, 5)314- },315- [316- {op: "add", path: ["x", 3], value: 4},317- {op: "add", path: ["x", 4], value: 5}318- ],319- [{op: "replace", path: ["x", "length"], value: 3}]320- )304+ runPatchTest(305+ {x: [1, 2, 3]},306+ d => {307+ d.x.push(4, 5)308+ },309+ [310+ {op: "add", path: ["x", 3], value: 4},311+ {op: "add", path: ["x", 4], value: 5}312+ ],313+ [{op: "replace", path: ["x", "length"], value: 3}]314+ )315 })316 317 describe("arrays - splice (expand)", () => {324- runPatchTest(325- {x: [1, 2, 3]},326- d => {327- d.x.splice(1, 1, 4, 5, 6)328- },329- [330- {op: "replace", path: ["x", 1], value: 4},331- {op: "add", path: ["x", 2], value: 5},332- {op: "add", path: ["x", 3], value: 6}333- ],334- [335- {op: "replace", path: ["x", 1], value: 2},336- {op: "remove", path: ["x", 3]},337- {op: "remove", path: ["x", 2]}338- ]339- )318+ runPatchTest(319+ {x: [1, 2, 3]},320+ d => {321+ d.x.splice(1, 1, 4, 5, 6)322+ },323+ [324+ {op: "replace", path: ["x", 1], value: 4},325+ {op: "add", path: ["x", 2], value: 5},326+ {op: "add", path: ["x", 3], value: 6}327+ ],328+ [329+ {op: "replace", path: ["x", 1], value: 2},330+ {op: "remove", path: ["x", 3]},331+ {op: "remove", path: ["x", 2]}332+ ]333+ )334 })335 336 describe("arrays - splice (shrink)", () => {343- runPatchTest(344- {x: [1, 2, 3, 4, 5]},345- d => {346- d.x.splice(1, 3, 6)347- },348- [349- {op: "replace", path: ["x", 1], value: 6},350- {op: "remove", path: ["x", 3]},351- {op: "remove", path: ["x", 2]}352- ],353- [354- {op: "replace", path: ["x", 1], value: 2},355- {op: "add", path: ["x", 2], value: 3},356- {op: "add", path: ["x", 3], value: 4}357- ]358- )337+ runPatchTest(338+ {x: [1, 2, 3, 4, 5]},339+ d => {340+ d.x.splice(1, 3, 6)341+ },342+ [343+ {op: "replace", path: ["x", 1], value: 6},344+ {op: "remove", path: ["x", 3]},345+ {op: "remove", path: ["x", 2]}346+ ],347+ [348+ {op: "replace", path: ["x", 1], value: 2},349+ {op: "add", path: ["x", 2], value: 3},350+ {op: "add", path: ["x", 3], value: 4}351+ ]352+ )353 })354 355 describe("simple replacement", () => {362- runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])356+ runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])357 })358 359 describe("same value replacement - 1", () => {366- runPatchTest(367- {x: {y: 3}},368- d => {369- const a = d.x370- d.x = a371- },372- []373- )360+ runPatchTest(361+ {x: {y: 3}},362+ d => {363+ const a = d.x364+ d.x = a365+ },366+ []367+ )368 })369 370 describe("same value replacement - 2", () => {377- runPatchTest(378- {x: {y: 3}},379- d => {380- const a = d.x381- d.x = 4382- d.x = a383- },384- []385- )371+ runPatchTest(372+ {x: {y: 3}},373+ d => {374+ const a = d.x375+ d.x = 4376+ d.x = a377+ },378+ []379+ )380 })381 382 describe("same value replacement - 3", () => {389- runPatchTest(390- {x: 3},391- d => {392- d.x = 3393- },394- []395- )383+ runPatchTest(384+ {x: 3},385+ d => {386+ d.x = 3387+ },388+ []389+ )390 })391 392 describe("same value replacement - 4", () => {399- runPatchTest(400- {x: 3},401- d => {402- d.x = 4403- d.x = 3404- },405- []406- )393+ runPatchTest(394+ {x: 3},395+ d => {396+ d.x = 4397+ d.x = 3398+ },399+ []400+ )401 })402 403 describe("simple delete", () => {410- runPatchTest(411- {x: 2},412- d => {413- delete d.x414- },415- [416- {417- op: "remove",418- path: ["x"]419- }420- ]421- )404+ runPatchTest(405+ {x: 2},406+ d => {407+ delete d.x408+ },409+ [410+ {411+ op: "remove",412+ path: ["x"]413+ }414+ ]415+ )416 })modified:__tests__/polyfills.js+42 added-42 removed
13 unmodified lines14 Object.assign = assign15 Reflect.ownKeys = ownKeys16 17 describe("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 })32 33 describe("Object.assign", () => {34- const {assign} = common34+ const {assign} = common35 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- })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+ })44 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- })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 })54 55 describe("Reflect.ownKeys", () => {56- const {ownKeys} = common56+ const {ownKeys} = common57 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- })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+ })64 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- })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__/produce.ts+310 added-310 removed
1 import {assert, _} from "spec.ts"2 import produce, {3- produce as produce2,4- applyPatches,5- Patch,6- nothing,7- Draft,8- Immutable3+ produce as produce2,4+ applyPatches,5+ Patch,6+ nothing,7+ Draft,8+ Immutable9 } from "../dist/immer.js"10 11 interface State {12- readonly num: number13- readonly foo?: string14- bar: string15- readonly baz: {16- readonly x: number17- readonly y: number18- }19- readonly arr: ReadonlyArray<{readonly value: string}>20- readonly arr2: {readonly value: string}[]12+ readonly num: number13+ readonly foo?: string14+ bar: string15+ readonly baz: {16+ readonly x: number17+ readonly y: number18+ }19+ readonly arr: ReadonlyArray<{readonly value: string}>20+ readonly arr2: {readonly value: string}[]21 }22 23 const state: State = {24- num: 0,25- bar: "foo",26- baz: {27- x: 1,28- y: 229- },30- arr: [{value: "asdf"}],31- arr2: [{value: "asdf"}]24+ num: 0,25+ bar: "foo",26+ baz: {27+ x: 1,28+ y: 229+ },30+ arr: [{value: "asdf"}],31+ arr2: [{value: "asdf"}]32 }33 34 const expectedState: State = {35- num: 1,36- foo: "bar",37- bar: "foo",38- baz: {39- x: 2,40- y: 341- },42- arr: [{value: "foo"}, {value: "asf"}],43- arr2: [{value: "foo"}, {value: "asf"}]35+ num: 1,36+ foo: "bar",37+ bar: "foo",38+ baz: {39+ x: 2,40+ y: 341+ },42+ arr: [{value: "foo"}, {value: "asf"}],43+ arr2: [{value: "foo"}, {value: "asf"}]44 }45 46 it("can update readonly state via standard api", () => {47- const newState = produce<State>(state, draft => {48- draft.num++49- draft.foo = "bar"50- draft.bar = "foo"51- draft.baz.x++52- draft.baz.y++53- draft.arr[0].value = "foo"54- draft.arr.push({value: "asf"})55- draft.arr2[0].value = "foo"56- draft.arr2.push({value: "asf"})57- })58- assert(newState, state)47+ const newState = produce<State>(state, draft => {48+ draft.num++49+ draft.foo = "bar"50+ draft.bar = "foo"51+ draft.baz.x++52+ draft.baz.y++53+ draft.arr[0].value = "foo"54+ draft.arr.push({value: "asf"})55+ draft.arr2[0].value = "foo"56+ draft.arr2.push({value: "asf"})57+ })58+ assert(newState, state)59 })60 61 // NOTE: only when the function type is inferred62 it("can infer state type from default state", () => {63- type State = {readonly a: number}64- type Recipe = <S extends State>(state?: S | undefined) => S63+ type State = {readonly a: number}64+ type Recipe = <S extends State>(state?: S | undefined) => S65 66- let foo = produce((_: any) => {}, _ as State)67- assert(foo, _ as Recipe)66+ let foo = produce((_: any) => {}, _ as State)67+ assert(foo, _ as Recipe)68 })69 70 it("can infer state type from recipe function", () => {71- type State = {readonly a: string} | {readonly b: string}72- type Recipe = <S extends State>(state: S) => S71+ type State = {readonly a: string} | {readonly b: string}72+ type Recipe = <S extends State>(state: S) => S73 74- let foo = produce((_: Draft<State>) => {})75- assert(foo, _ as Recipe)74+ let foo = produce((_: Draft<State>) => {})75+ assert(foo, _ as Recipe)76 })77 78 it("can infer state type from recipe function with arguments", () => {79- type State = {readonly a: string} | {readonly b: string}80- type Recipe = <S extends State>(state: S, x: number) => S79+ type State = {readonly a: string} | {readonly b: string}80+ type Recipe = <S extends State>(state: S, x: number) => S81 82- let foo = produce((draft: Draft<State>, x: number) => {})83- assert(foo, _ as Recipe)82+ let foo = produce((draft: Draft<State>, x: number) => {})83+ assert(foo, _ as Recipe)84 })85 86 it("can infer state type from recipe function with arguments and initial state", () => {87- type State = {readonly a: string} | {readonly b: string}88- type Recipe = <S extends State>(state: S | undefined, x: number) => S87+ type State = {readonly a: string} | {readonly b: string}88+ type Recipe = <S extends State>(state: S | undefined, x: number) => S89 90- let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)91- assert(foo, _ as Recipe)90+ let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)91+ assert(foo, _ as Recipe)92 })93 94 it("cannot infer state type when the function type and default state are missing", () => {95- type Recipe = <S extends any>(state: S) => S96- const foo = produce((_: any) => {})97- assert(foo, _ as Recipe)95+ type Recipe = <S extends any>(state: S) => S96+ const foo = produce((_: any) => {})97+ assert(foo, _ as Recipe)98 })99 100 it("can update readonly state via curried api", () => {101- const newState = produce((draft: Draft<State>) => {102- draft.num++103- draft.foo = "bar"104- draft.bar = "foo"105- draft.baz.x++106- draft.baz.y++107- draft.arr[0].value = "foo"108- draft.arr.push({value: "asf"})109- draft.arr2[0].value = "foo"110- draft.arr2.push({value: "asf"})111- })(state)112- expect(newState).not.toBe(state)113- expect(newState).toEqual(expectedState)101+ const newState = produce((draft: Draft<State>) => {102+ draft.num++103+ draft.foo = "bar"104+ draft.bar = "foo"105+ draft.baz.x++106+ draft.baz.y++107+ draft.arr[0].value = "foo"108+ draft.arr.push({value: "asf"})109+ draft.arr2[0].value = "foo"110+ draft.arr2.push({value: "asf"})111+ })(state)112+ expect(newState).not.toBe(state)113+ expect(newState).toEqual(expectedState)114 })115 116 it("can update use the non-default export", () => {117- const newState = produce2((draft: Draft<State>) => {118- draft.num++119- draft.foo = "bar"120- draft.bar = "foo"121- draft.baz.x++122- draft.baz.y++123- draft.arr[0].value = "foo"124- draft.arr.push({value: "asf"})125- draft.arr2[0].value = "foo"126- draft.arr2.push({value: "asf"})127- })(state)128- expect(newState).not.toBe(state)129- expect(newState).toEqual(expectedState)117+ const newState = produce2((draft: Draft<State>) => {118+ draft.num++119+ draft.foo = "bar"120+ draft.bar = "foo"121+ draft.baz.x++122+ draft.baz.y++123+ draft.arr[0].value = "foo"124+ draft.arr.push({value: "asf"})125+ draft.arr2[0].value = "foo"126+ draft.arr2.push({value: "asf"})127+ })(state)128+ expect(newState).not.toBe(state)129+ expect(newState).toEqual(expectedState)130 })131 132 it("can apply patches", () => {133- let patches: Patch[] = []134- produce(135- {x: 3},136- d => {137- d.x++138- },139- p => {140- patches = p141- }142- )133+ let patches: Patch[] = []134+ produce(135+ {x: 3},136+ d => {137+ d.x++138+ },139+ p => {140+ patches = p141+ }142+ )143 144- expect(applyPatches({}, patches)).toEqual({x: 4})144+ expect(applyPatches({}, patches)).toEqual({x: 4})145 })146 147 describe("curried producer", () => {148- it("supports rest parameters", () => {149- type State = {readonly a: 1}148+ it("supports rest parameters", () => {149+ type State = {readonly a: 1}150 151- // No initial state:152- {153- type Recipe = <S extends State>(state: S, a: number, b: number) => S154- let foo = produce((s: State, a: number, b: number) => {})155- assert(foo, _ as Recipe)156- foo(_ as State, 1, 2)157- }151+ // No initial state:152+ {153+ type Recipe = <S extends State>(state: S, a: number, b: number) => S154+ let foo = produce((s: State, a: number, b: number) => {})155+ assert(foo, _ as Recipe)156+ foo(_ as State, 1, 2)157+ }158 159- // Using argument parameters:160- {161- type Recipe = <S extends State>(state: S, ...rest: number[]) => S162- let woo = produce((state: Draft<State>, ...args: number[]) => {})163- assert(woo, _ as Recipe)164- woo(_ as State, 1, 2)165- }159+ // Using argument parameters:160+ {161+ type Recipe = <S extends State>(state: S, ...rest: number[]) => S162+ let woo = produce((state: Draft<State>, ...args: number[]) => {})163+ assert(woo, _ as Recipe)164+ woo(_ as State, 1, 2)165+ }166 167- // With initial state:168- {169- type Recipe = <S extends State>(170- state?: S | undefined,171- ...rest: number[]172- ) => S173- let bar = produce(174- (state: Draft<State>, ...args: number[]) => {},175- _ as State176- )177- assert(bar, _ as Recipe)178- bar(_ as State, 1, 2)179- bar(_ as State)180- bar()181- }167+ // With initial state:168+ {169+ type Recipe = <S extends State>(170+ state?: S | undefined,171+ ...rest: number[]172+ ) => S173+ let bar = produce(174+ (state: Draft<State>, ...args: number[]) => {},175+ _ as State176+ )177+ assert(bar, _ as Recipe)178+ bar(_ as State, 1, 2)179+ bar(_ as State)180+ bar()181+ }182 183- // When args is a tuple:184- {185- type Recipe = <S extends State>(186- state: S | undefined,187- first: string,188- ...rest: number[]189- ) => S190- let tup = produce(191- (state: Draft<State>, ...args: [string, ...number[]]) => {},192- _ as State193- )194- assert(tup, _ as Recipe)195- tup({a: 1}, "", 2)196- tup(undefined, "", 2)197- }198- })183+ // When args is a tuple:184+ {185+ type Recipe = <S extends State>(186+ state: S | undefined,187+ first: string,188+ ...rest: number[]189+ ) => S190+ let tup = produce(191+ (state: Draft<State>, ...args: [string, ...number[]]) => {},192+ _ as State193+ )194+ assert(tup, _ as Recipe)195+ tup({a: 1}, "", 2)196+ tup(undefined, "", 2)197+ }198+ })199 200- it("can be passed a readonly array", () => {201- // No initial state:202- {203- let foo = produce((state: string[]) => {})204- assert(foo, _ as <S extends readonly string[]>(state: S) => S)205- foo([] as ReadonlyArray<string>)206- }200+ it("can be passed a readonly array", () => {201+ // No initial state:202+ {203+ let foo = produce((state: string[]) => {})204+ assert(foo, _ as <S extends readonly string[]>(state: S) => S)205+ foo([] as ReadonlyArray<string>)206+ }207 208- // With initial state:209- {210- let bar = produce(() => {}, [] as ReadonlyArray<string>)211- assert(bar, _ as <S extends readonly string[]>(212- state?: S | undefined213- ) => S)214- bar([] as ReadonlyArray<string>)215- bar(undefined)216- bar()217- }218- })208+ // With initial state:209+ {210+ let bar = produce(() => {}, [] as ReadonlyArray<string>)211+ assert(bar, _ as <S extends readonly string[]>(212+ state?: S | undefined213+ ) => S)214+ bar([] as ReadonlyArray<string>)215+ bar(undefined)216+ bar()217+ }218+ })219 })220 221 it("works with return type of: number", () => {222- let base = _ as {a: number}223- let result = produce(base, () => 1)224- assert(result, _ as number)222+ let base = _ as {a: number}223+ let result = produce(base, () => 1)224+ assert(result, _ as number)225 })226 227 it("works with return type of: number | undefined", () => {228- let base = _ as {a: number}229- let result = produce(base, draft => {230- return draft.a < 0 ? 0 : undefined231- })232- assert(result, _ as {a: number} | number)228+ let base = _ as {a: number}229+ let result = produce(base, draft => {230+ return draft.a < 0 ? 0 : undefined231+ })232+ assert(result, _ as {a: number} | number)233 })234 235 it("can return an object type that is identical to the base type", () => {236- let base = _ as {a: number}237- let result = produce(base, draft => {238- return draft.a < 0 ? {a: 0} : undefined239- })240- // TODO: Can we resolve the weird union of identical object types?241- assert(result, _ as {a: number} | {a: number})236+ let base = _ as {a: number}237+ let result = produce(base, draft => {238+ return draft.a < 0 ? {a: 0} : undefined239+ })240+ // TODO: Can we resolve the weird union of identical object types?241+ assert(result, _ as {a: number} | {a: number})242 })243 244 it("can return an object type that is _not_ assignable to the base type", () => {245- let base = _ as {a: number}246- let result = produce(base, draft => {247- return draft.a < 0 ? {a: true} : undefined248- })249- assert(result, _ as {a: number} | {a: boolean})245+ let base = _ as {a: number}246+ let result = produce(base, draft => {247+ return draft.a < 0 ? {a: true} : undefined248+ })249+ assert(result, _ as {a: number} | {a: boolean})250 })251 252 it("does not enforce immutability at the type level", () => {253- let result = produce([] as any[], draft => {254- draft.push(1)255- })256- assert(result, _ as any[])253+ let result = produce([] as any[], draft => {254+ draft.push(1)255+ })256+ assert(result, _ as any[])257 })258 259 it("can produce an undefined value", () => {260- let base = _ as {readonly a: number}260+ let base = _ as {readonly a: number}261 262- // Return only nothing.263- let result = produce(base, _ => nothing)264- assert(result, undefined)262+ // Return only nothing.263+ let result = produce(base, _ => nothing)264+ assert(result, undefined)265 266- // Return maybe nothing.267- let result2 = produce(base, draft => {268- if (draft.a > 0) return nothing269- })270- assert(result2, _ as typeof base | undefined)266+ // Return maybe nothing.267+ let result2 = produce(base, draft => {268+ if (draft.a > 0) return nothing269+ })270+ assert(result2, _ as typeof base | undefined)271 })272 273 it("can return the draft itself", () => {274- let base = _ as {readonly a: number}275- let result = produce(base, draft => draft)274+ let base = _ as {readonly a: number}275+ let result = produce(base, draft => draft)276 277- // Currently, the `readonly` modifier is lost.278- assert(result, _ as {a: number})277+ // Currently, the `readonly` modifier is lost.278+ assert(result, _ as {a: number})279 })280 281 it("can return a promise", () => {282- type Base = {readonly a: number}283- let base = _ as Base282+ type Base = {readonly a: number}283+ let base = _ as Base284 285- // Return a promise only.286- let res1 = produce(base, draft => {287- return Promise.resolve(draft.a > 0 ? null : undefined)288- })289- assert(res1, _ as Promise<Base | null>)285+ // Return a promise only.286+ let res1 = produce(base, draft => {287+ return Promise.resolve(draft.a > 0 ? null : undefined)288+ })289+ assert(res1, _ as Promise<Base | null>)290 291- // Return a promise or undefined.292- let res2 = produce(base, draft => {293- if (draft.a > 0) return Promise.resolve()294- })295- assert(res2, _ as Base | Promise<Base>)291+ // Return a promise or undefined.292+ let res2 = produce(base, draft => {293+ if (draft.a > 0) return Promise.resolve()294+ })295+ assert(res2, _ as Base | Promise<Base>)296 })297 298 it("works with `void` hack", () => {299- let base = _ as {readonly a: number}300- let copy = produce(base, s => void s.a++)301- assert(copy, base)299+ let base = _ as {readonly a: number}300+ let copy = produce(base, s => void s.a++)301+ assert(copy, base)302 })303 304 it("works with generic parameters", () => {305- let insert = <T>(array: readonly T[], index: number, elem: T) => {306- // Need explicit cast on draft as T[] is wider than readonly T[]307- return produce(array, (draft: T[]) => {308- draft.push(elem)309- draft.splice(index, 0, elem)310- draft.concat([elem])311- })312- }313- let val: {readonly a: ReadonlyArray<number>} = 0 as any314- let arr: ReadonlyArray<typeof val> = 0 as any315- insert(arr, 0, val)305+ let insert = <T>(array: readonly T[], index: number, elem: T) => {306+ // Need explicit cast on draft as T[] is wider than readonly T[]307+ return produce(array, (draft: T[]) => {308+ draft.push(elem)309+ draft.splice(index, 0, elem)310+ draft.concat([elem])311+ })312+ }313+ let val: {readonly a: ReadonlyArray<number>} = 0 as any314+ let arr: ReadonlyArray<typeof val> = 0 as any315+ insert(arr, 0, val)316 })317 318 it("can work with non-readonly base types", () => {319- const state = {320- price: 10,321- todos: [322- {323- title: "test",324- done: false325- }326- ]327- }328- type State = typeof state319+ const state = {320+ price: 10,321+ todos: [322+ {323+ title: "test",324+ done: false325+ }326+ ]327+ }328+ type State = typeof state329 330- const newState: State = produce(state, draft => {331- draft.price += 5332- draft.todos.push({333- title: "hi",334- done: true335- })336- })330+ const newState: State = produce(state, draft => {331+ draft.price += 5332+ draft.todos.push({333+ title: "hi",334+ done: true335+ })336+ })337 338- const reducer = (draft: State) => {339- draft.price += 5340- draft.todos.push({341- title: "hi",342- done: true343- })344- }338+ const reducer = (draft: State) => {339+ draft.price += 5340+ draft.todos.push({341+ title: "hi",342+ done: true343+ })344+ }345 346- // base case for with-initial-state347- const newState4 = produce(reducer, state)(state)348- assert(newState4, _ as State)349- // no argument case, in that case, immutable version recipe first arg will be inferred350- const newState5 = produce(reducer, state)()351- assert(newState5, _ as Immutable<State>)352- // we can force the return type of the reducer by passing the generic argument353- const newState3 = produce(reducer, state)<State>()354- assert(newState3, _ as State)346+ // base case for with-initial-state347+ const newState4 = produce(reducer, state)(state)348+ assert(newState4, _ as State)349+ // no argument case, in that case, immutable version recipe first arg will be inferred350+ const newState5 = produce(reducer, state)()351+ assert(newState5, _ as Immutable<State>)352+ // we can force the return type of the reducer by passing the generic argument353+ const newState3 = produce(reducer, state)<State>()354+ assert(newState3, _ as State)355 })356 357 it("can work with readonly base types", () => {358- type State = {359- readonly price: number360- readonly todos: readonly {361- readonly title: string362- readonly done: boolean363- }[]364- }358+ type State = {359+ readonly price: number360+ readonly todos: readonly {361+ readonly title: string362+ readonly done: boolean363+ }[]364+ }365 366- const state: State = {367- price: 10,368- todos: [369- {370- title: "test",371- done: false372- }373- ]374- }366+ const state: State = {367+ price: 10,368+ todos: [369+ {370+ title: "test",371+ done: false372+ }373+ ]374+ }375 376- const newState: State = produce(state, draft => {377- draft.price + 5378- draft.todos.push({379- title: "hi",380- done: true381- })382- })376+ const newState: State = produce(state, draft => {377+ draft.price + 5378+ draft.todos.push({379+ title: "hi",380+ done: true381+ })382+ })383 384- const reducer = (draft: Draft<State>) => {385- draft.price += 5386- draft.todos.push({387- title: "hi",388- done: true389- })390- }391- const newState2: State = produce(reducer)(state)392- assert(newState2, _ as State)384+ const reducer = (draft: Draft<State>) => {385+ draft.price += 5386+ draft.todos.push({387+ title: "hi",388+ done: true389+ })390+ }391+ const newState2: State = produce(reducer)(state)392+ assert(newState2, _ as State)393 394- // base case for with-initial-state395- const newState4 = produce(reducer, state)(state)396- assert(newState4, _ as State)397- // no argument case, in that case, immutable version recipe first arg will be inferred398- const newState5 = produce(reducer, state)()399- assert(newState5, _ as Immutable<State>)400- // we can force the return type of the reducer by passing the generic argument401- const newState3 = produce(reducer, state)<State>()402- assert(newState3, _ as State)394+ // base case for with-initial-state395+ const newState4 = produce(reducer, state)(state)396+ assert(newState4, _ as State)397+ // no argument case, in that case, immutable version recipe first arg will be inferred398+ const newState5 = produce(reducer, state)()399+ assert(newState5, _ as Immutable<State>)400+ // we can force the return type of the reducer by passing the generic argument401+ const newState3 = produce(reducer, state)<State>()402+ assert(newState3, _ as State)403 })404 405 it("works with generic array", () => {406- const append = <T>(queue: T[], item: T) =>407- // T[] is needed here v. Too bad.408- produce(queue, (queueDraft: T[]) => {409- queueDraft.push(item)410- })406+ const append = <T>(queue: T[], item: T) =>407+ // T[] is needed here v. Too bad.408+ produce(queue, (queueDraft: T[]) => {409+ queueDraft.push(item)410+ })411 412- const queueBefore = [1, 2, 3]412+ const queueBefore = [1, 2, 3]413 414- const queueAfter = append(queueBefore, 4)414+ const queueAfter = append(queueBefore, 4)415 416- expect(queueAfter).toEqual([1, 2, 3, 4])417- expect(queueBefore).toEqual([1, 2, 3])416+ expect(queueAfter).toEqual([1, 2, 3, 4])417+ expect(queueBefore).toEqual([1, 2, 3])418 })modified:__tests__/readme.js+141 added-141 removed
1 "use strict"2 import produce, {applyPatches, immerable} from "../src/index"3 4 describe("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+ ]16 17- 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+ })21 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)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)26 27- // 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)30 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- })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+ })36 37- it("patches", () => {38- let state = {39- name: "Micheal",40- age: 3241- }37+ it("patches", () => {38+ let state = {39+ name: "Micheal",40+ age: 3241+ }42 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 = []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 = []50 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- )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+ )62 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- })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+ })67 68- // 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)70 71- // 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+ })76 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- })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+ })84 85- 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+ }90 91- const nextState = produce(state, draft => {92- draft.title = draft.title.toUpperCase() // let immer do it's job93- // don't use the operations onSet, as that mutates the instance!94- // draft.tokenSet.add("c1342")91+ const nextState = produce(state, draft => {92+ draft.title = draft.title.toUpperCase() // let immer do it's job93+ // don't use the operations onSet, as that mutates the instance!94+ // draft.tokenSet.add("c1342")95 96- // instead: clone the set (once!)97- const newSet = new Set(draft.tokenSet)98- // mutate it once99- newSet.add("c1342")100- // update the draft with the new set101- draft.tokenSet = newSet102- })96+ // instead: clone the set (once!)97+ const newSet = new Set(draft.tokenSet)98+ // mutate it once99+ newSet.add("c1342")100+ // update the draft with the new set101+ draft.tokenSet = newSet102+ })103 104- expect(state).toEqual({title: "hello", tokenSet: new Set()})105- expect(nextState).toEqual({106- title: "HELLO",107- tokenSet: new Set(["c1342"])108- })109- })104+ expect(state).toEqual({title: "hello", tokenSet: new Set()})105+ expect(nextState).toEqual({106+ title: "HELLO",107+ tokenSet: new Set(["c1342"])108+ })109+ })110 111- it("can deep udpate map", () => {112- const state = {113- users: new Map([["michel", {name: "miche"}]])114- }111+ it("can deep udpate map", () => {112+ const state = {113+ users: new Map([["michel", {name: "miche"}]])114+ }115 116- const nextState = produce(state, draft => {117- const newUsers = new Map(draft.users)118- // mutate the new map and set a _new_ user object119- // but leverage produce again to deeply update it's contents120- newUsers.set(121- "michel",122- produce(draft.users.get("michel"), draft => {123- draft.name = "michel"124- })125- )126- draft.users = newUsers127- })116+ const nextState = produce(state, draft => {117+ const newUsers = new Map(draft.users)118+ // mutate the new map and set a _new_ user object119+ // but leverage produce again to deeply update it's contents120+ newUsers.set(121+ "michel",122+ produce(draft.users.get("michel"), draft => {123+ draft.name = "michel"124+ })125+ )126+ draft.users = newUsers127+ })128 129- expect(state).toEqual({users: new Map([["michel", {name: "miche"}]])})130- expect(nextState).toEqual({131- users: new Map([["michel", {name: "michel"}]])132- })133- })129+ expect(state).toEqual({users: new Map([["michel", {name: "miche"}]])})130+ expect(nextState).toEqual({131+ users: new Map([["michel", {name: "michel"}]])132+ })133+ })134 135- it("supports immerable", () => {136- class Clock {137- constructor(hours = 0, minutes = 0) {138- this.hours = hours139- this.minutes = minutes140- }135+ it("supports immerable", () => {136+ class Clock {137+ constructor(hours = 0, minutes = 0) {138+ this.hours = hours139+ this.minutes = minutes140+ }141 142- increment(hours, minutes = 0) {143- return produce(this, d => {144- d.hours += hours145- d.minutes += minutes146- })147- }142+ increment(hours, minutes = 0) {143+ return produce(this, d => {144+ d.hours += hours145+ d.minutes += minutes146+ })147+ }148 149- toString() {150- return `${("" + this.hours).padStart(2, 0)}:${(151- "" + this.minutes152- ).padStart(2, 0)}`153- }154- }155- Clock[immerable] = true149+ toString() {150+ return `${("" + this.hours).padStart(2, 0)}:${(151+ "" + this.minutes152+ ).padStart(2, 0)}`153+ }154+ }155+ Clock[immerable] = true156 157- const midnight = new Clock()158- const lunch = midnight.increment(12, 30)157+ const midnight = new Clock()158+ const lunch = midnight.increment(12, 30)159 160- expect(midnight).not.toBe(lunch)161- expect(lunch).toBeInstanceOf(Clock)162- expect(midnight.toString()).toBe("00:00")163- expect(lunch.toString()).toBe("12:30")160+ expect(midnight).not.toBe(lunch)161+ expect(lunch).toBeInstanceOf(Clock)162+ expect(midnight.toString()).toBe("00:00")163+ expect(lunch.toString()).toBe("12:30")164 165- const diner = lunch.increment(6)165+ const diner = lunch.increment(6)166 167- expect(diner).not.toBe(lunch)168- expect(lunch).toBeInstanceOf(Clock)169- expect(diner.toString()).toBe("18:30")170- })167+ expect(diner).not.toBe(lunch)168+ expect(lunch).toBeInstanceOf(Clock)169+ expect(diner.toString()).toBe("18:30")170+ })171 })modified:__tests__/test-data.json+45 added-56 removed
1- {2- "_id": "5a5e59f1bc9132a90101f521",3- "index": 0,4- "guid": "8dc96fdb-0526-4bc4-a0ef-fb08e6c06e77",5- "isActive": true,6- "balance": "$3,359.66",7- "picture": "http://placehold.it/32x32",8- "age": 40,9- "eyeColor": "blue",10- "name": "Samantha Richardson",11- "gender": "female",12- "company": "COWTOWN",13- "email": "samantharichardson@cowtown.com",14- "phone": "+1 (847) 556-2336",15- "address": "419 Bergen Street, Emison, Nebraska, 554",16- "about": "Enim magna ut do esse voluptate et commodo anim laborum proident aute. Nulla non sit in incididunt minim velit. Laboris et tempor enim cillum ex adipisicing excepteur. Dolore consectetur eiusmod eu ad eu. Veniam qui sunt est reprehenderit et ut occaecat eiusmod pariatur aliquip officia ipsum.\r\n",17- "registered": "2017-07-09T02:30:48 -02:00",18- "latitude": -38.375287,19- "longitude": -27.090184,20- "tags": [21- "ex",22- "cillum",23- "cillum",24- "Lorem",25- "fugiat",26- "dolore",27- "nulla",28- "anim",29- "aliqua",30- "sint"31- ],32- "friends": [33- {34- "id": 0,35- "name": "Adrian Dunlap"36- },37- {38- "id": 1,39- "name": "Salinas Copeland"40- },41- {42- "id": 2,43- "name": "Doreen Emerson"44- },45- {46- "id": 3,47- "name": "Willis Long"48- },49- {50- "id": 4,51- "name": "Josefina Garza"52- }53- ],54- "greeting": "Hello, Samantha Richardson! You have 8 unread messages.",55- "favoriteFruit": "banana"56- }1+{2+ "_id": "5a5e59f1bc9132a90101f521",3+ "index": 0,4+ "guid": "8dc96fdb-0526-4bc4-a0ef-fb08e6c06e77",5+ "isActive": true,6+ "balance": "$3,359.66",7+ "picture": "http://placehold.it/32x32",8+ "age": 40,9+ "eyeColor": "blue",10+ "name": "Samantha Richardson",11+ "gender": "female",12+ "company": "COWTOWN",13+ "email": "samantharichardson@cowtown.com",14+ "phone": "+1 (847) 556-2336",15+ "address": "419 Bergen Street, Emison, Nebraska, 554",16+ "about": "Enim magna ut do esse voluptate et commodo anim laborum proident aute. Nulla non sit in incididunt minim velit. Laboris et tempor enim cillum ex adipisicing excepteur. Dolore consectetur eiusmod eu ad eu. Veniam qui sunt est reprehenderit et ut occaecat eiusmod pariatur aliquip officia ipsum.\r\n",17+ "registered": "2017-07-09T02:30:48 -02:00",18+ "latitude": -38.375287,19+ "longitude": -27.090184,20+ "tags": ["ex", "cillum", "cillum", "Lorem", "fugiat", "dolore", "nulla", "anim", "aliqua", "sint"],21+ "friends": [22+ {23+ "id": 0,24+ "name": "Adrian Dunlap"25+ },26+ {27+ "id": 1,28+ "name": "Salinas Copeland"29+ },30+ {31+ "id": 2,32+ "name": "Doreen Emerson"33+ },34+ {35+ "id": 3,36+ "name": "Willis Long"37+ },38+ {39+ "id": 4,40+ "name": "Josefina Garza"41+ }42+ ],43+ "greeting": "Hello, Samantha Richardson! You have 8 unread messages.",44+ "favoriteFruit": "banana"45+}modified:__tests__/tsconfig.json+5 added-5 removed
1 {2- "include": ["*", "../dist"],3- "compilerOptions": {4- "lib": ["es2015"],5- "strict": true6- }2+ "include": ["*", "../dist"],3+ "compilerOptions": {4+ "lib": ["es2015"],5+ "strict": true6+ }7 }modified:src/common.js+75 added-75 removed
1 export 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}5 6 export const DRAFTABLE =7- typeof Symbol !== "undefined" && Symbol.for8- ? Symbol.for("immer-draftable")9- : "__$immer_draftable"7+ typeof Symbol !== "undefined" && Symbol.for8+ ? Symbol.for("immer-draftable")9+ : "__$immer_draftable"10 11 export const DRAFT_STATE =12- typeof Symbol !== "undefined" && Symbol.for13- ? Symbol.for("immer-state")14- : "__$immer_state"12+ typeof Symbol !== "undefined" && Symbol.for13+ ? Symbol.for("immer-state")14+ : "__$immer_state"15 16 export function isDraft(value) {17- return !!value && !!value[DRAFT_STATE]17+ return !!value && !!value[DRAFT_STATE]18 }19 20 export function isDraftable(value) {21- if (!value || typeof value !== "object") return false22- if (Array.isArray(value)) return true23- const proto = Object.getPrototypeOf(value)24- if (!proto || proto === Object.prototype) return true25- return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]21+ if (!value || typeof value !== "object") return false22+ if (Array.isArray(value)) return true23+ const proto = Object.getPrototypeOf(value)24+ if (!proto || proto === Object.prototype) return true25+ return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]26 }27 28 export function original(value) {29- if (value && value[DRAFT_STATE]) {30- return value[DRAFT_STATE].base31- }32- // otherwise return undefined29+ if (value && value[DRAFT_STATE]) {30+ return value[DRAFT_STATE].base31+ }32+ // otherwise return undefined33 }34 35 export const assign =36- Object.assign ||37- function assign(target, value) {38- for (let key in value) {39- if (has(value, key)) {40- target[key] = value[key]41- }42- }43- return target44- }36+ Object.assign ||37+ function assign(target, value) {38+ for (let key in value) {39+ if (has(value, key)) {40+ target[key] = value[key]41+ }42+ }43+ return target44+ }45 46 export const ownKeys =47- typeof Reflect !== "undefined" && Reflect.ownKeys48- ? Reflect.ownKeys49- : typeof Object.getOwnPropertySymbols !== "undefined"50- ? obj =>51- Object.getOwnPropertyNames(obj).concat(52- Object.getOwnPropertySymbols(obj)53- )54- : Object.getOwnPropertyNames47+ typeof Reflect !== "undefined" && Reflect.ownKeys48+ ? Reflect.ownKeys49+ : typeof Object.getOwnPropertySymbols !== "undefined"50+ ? obj =>51+ Object.getOwnPropertyNames(obj).concat(52+ Object.getOwnPropertySymbols(obj)53+ )54+ : Object.getOwnPropertyNames55 56 export function shallowCopy(base, invokeGetters = false) {57- if (Array.isArray(base)) return base.slice()58- const clone = Object.create(Object.getPrototypeOf(base))59- ownKeys(base).forEach(key => {60- if (key === DRAFT_STATE) {61- return // Never copy over draft state.62- }63- const desc = Object.getOwnPropertyDescriptor(base, key)64- let {value} = desc65- if (desc.get) {66- if (!invokeGetters) {67- throw new Error("Immer drafts cannot have computed properties")68- }69- value = desc.get.call(base)70- }71- if (desc.enumerable) {72- clone[key] = value73- } else {74- Object.defineProperty(clone, key, {75- value,76- writable: true,77- configurable: true78- })79- }80- })81- return clone57+ if (Array.isArray(base)) return base.slice()58+ const clone = Object.create(Object.getPrototypeOf(base))59+ ownKeys(base).forEach(key => {60+ if (key === DRAFT_STATE) {61+ return // Never copy over draft state.62+ }63+ const desc = Object.getOwnPropertyDescriptor(base, key)64+ let {value} = desc65+ if (desc.get) {66+ if (!invokeGetters) {67+ throw new Error("Immer drafts cannot have computed properties")68+ }69+ value = desc.get.call(base)70+ }71+ if (desc.enumerable) {72+ clone[key] = value73+ } else {74+ Object.defineProperty(clone, key, {75+ value,76+ writable: true,77+ configurable: true78+ })79+ }80+ })81+ return clone82 }83 84 export function each(value, cb) {85- if (Array.isArray(value)) {86- for (let i = 0; i < value.length; i++) cb(i, value[i], value)87- } else {88- ownKeys(value).forEach(key => cb(key, value[key], value))89- }85+ if (Array.isArray(value)) {86+ for (let i = 0; i < value.length; i++) cb(i, value[i], value)87+ } else {88+ ownKeys(value).forEach(key => cb(key, value[key], value))89+ }90 }91 92 export function isEnumerable(base, prop) {93- const desc = Object.getOwnPropertyDescriptor(base, prop)94- return !!desc && desc.enumerable93+ const desc = Object.getOwnPropertyDescriptor(base, prop)94+ return !!desc && desc.enumerable95 }96 97 export function has(thing, prop) {98- return Object.prototype.hasOwnProperty.call(thing, prop)98+ return Object.prototype.hasOwnProperty.call(thing, prop)99 }100 101 export function is(x, y) {102- // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js103- if (x === y) {104- return x !== 0 || 1 / x === 1 / y105- } else {106- return x !== x && y !== y107- }102+ // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js103+ if (x === y) {104+ return x !== 0 || 1 / x === 1 / y105+ } else {106+ return x !== x && y !== y107+ }108 }modified:src/es5.js+198 added-198 removed
1 "use strict"2 import {3- each,4- has,5- is,6- isDraft,7- isDraftable,8- isEnumerable,9- shallowCopy,10- DRAFT_STATE3+ each,4+ has,5+ is,6+ isDraft,7+ isDraftable,8+ isEnumerable,9+ shallowCopy,10+ DRAFT_STATE11 } from "./common"12 import {ImmerScope} from "./scope"13 14 // property descriptors are recycled to make sure we don't create a get and set closure per property,15 // but share them all instead16 const descriptors = {}17 18 export function willFinalize(scope, result, isReplaced) {19- scope.drafts.forEach(draft => {20- draft[DRAFT_STATE].finalizing = true21- })22- if (!isReplaced) {23- if (scope.patches) {24- markChangesRecursively(scope.drafts[0])25- }26- // This is faster when we don't care about which attributes changed.27- markChangesSweep(scope.drafts)28- }29- // When a child draft is returned, look for changes.30- else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {31- markChangesSweep(scope.drafts)32- }19+ scope.drafts.forEach(draft => {20+ draft[DRAFT_STATE].finalizing = true21+ })22+ if (!isReplaced) {23+ if (scope.patches) {24+ markChangesRecursively(scope.drafts[0])25+ }26+ // This is faster when we don't care about which attributes changed.27+ markChangesSweep(scope.drafts)28+ }29+ // When a child draft is returned, look for changes.30+ else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {31+ markChangesSweep(scope.drafts)32+ }33 }34 35 export function createProxy(base, parent) {36- const isArray = Array.isArray(base)37- const draft = clonePotentialDraft(base)38- each(draft, prop => {39- proxyProperty(draft, prop, isArray || isEnumerable(base, prop))40- })36+ const isArray = Array.isArray(base)37+ const draft = clonePotentialDraft(base)38+ each(draft, prop => {39+ proxyProperty(draft, prop, isArray || isEnumerable(base, prop))40+ })41 42- // See "proxy.js" for property documentation.43- const scope = parent ? parent.scope : ImmerScope.current44- const state = {45- scope,46- modified: false,47- finalizing: false, // es5 only48- finalized: false,49- assigned: {},50- parent,51- base,52- draft,53- copy: null,54- revoke,55- revoked: false // es5 only56- }42+ // See "proxy.js" for property documentation.43+ const scope = parent ? parent.scope : ImmerScope.current44+ const state = {45+ scope,46+ modified: false,47+ finalizing: false, // es5 only48+ finalized: false,49+ assigned: {},50+ parent,51+ base,52+ draft,53+ copy: null,54+ revoke,55+ revoked: false // es5 only56+ }57 58- createHiddenProperty(draft, DRAFT_STATE, state)59- scope.drafts.push(draft)60- return draft58+ createHiddenProperty(draft, DRAFT_STATE, state)59+ scope.drafts.push(draft)60+ return draft61 }62 63 function revoke() {64- this.revoked = true64+ this.revoked = true65 }66 67 function source(state) {68- return state.copy || state.base68+ return state.copy || state.base69 }70 71 // Access a property without creating an Immer draft.72 function peek(draft, prop) {73- const state = draft[DRAFT_STATE]74- if (state && !state.finalizing) {75- state.finalizing = true76- const value = draft[prop]77- state.finalizing = false78- return value79- }80- return draft[prop]73+ const state = draft[DRAFT_STATE]74+ if (state && !state.finalizing) {75+ state.finalizing = true76+ const value = draft[prop]77+ state.finalizing = false78+ return value79+ }80+ return draft[prop]81 }82 83 function get(state, prop) {84- assertUnrevoked(state)85- const value = peek(source(state), prop)86- if (state.finalizing) return value87- // Create a draft if the value is unmodified.88- if (value === peek(state.base, prop) && isDraftable(value)) {89- prepareCopy(state)90- return (state.copy[prop] = createProxy(value, state))91- }92- return value84+ assertUnrevoked(state)85+ const value = peek(source(state), prop)86+ if (state.finalizing) return value87+ // Create a draft if the value is unmodified.88+ if (value === peek(state.base, prop) && isDraftable(value)) {89+ prepareCopy(state)90+ return (state.copy[prop] = createProxy(value, state))91+ }92+ return value93 }94 95 function set(state, prop, value) {96- assertUnrevoked(state)97- state.assigned[prop] = true98- if (!state.modified) {99- if (is(value, peek(source(state), prop))) return100- markChanged(state)101- prepareCopy(state)102- }103- state.copy[prop] = value96+ assertUnrevoked(state)97+ state.assigned[prop] = true98+ if (!state.modified) {99+ if (is(value, peek(source(state), prop))) return100+ markChanged(state)101+ prepareCopy(state)102+ }103+ state.copy[prop] = value104 }105 106 function markChanged(state) {107- if (!state.modified) {108- state.modified = true109- if (state.parent) markChanged(state.parent)110- }107+ if (!state.modified) {108+ state.modified = true109+ if (state.parent) markChanged(state.parent)110+ }111 }112 113 function prepareCopy(state) {114- if (!state.copy) state.copy = clonePotentialDraft(state.base)114+ if (!state.copy) state.copy = clonePotentialDraft(state.base)115 }116 117 function clonePotentialDraft(base) {118- const state = base && base[DRAFT_STATE]119- if (state) {120- state.finalizing = true121- const draft = shallowCopy(state.draft, true)122- state.finalizing = false123- return draft124- }125- return shallowCopy(base)118+ const state = base && base[DRAFT_STATE]119+ if (state) {120+ state.finalizing = true121+ const draft = shallowCopy(state.draft, true)122+ state.finalizing = false123+ return draft124+ }125+ return shallowCopy(base)126 }127 128 function proxyProperty(draft, prop, enumerable) {129- let desc = descriptors[prop]130- if (desc) {131- desc.enumerable = enumerable132- } else {133- descriptors[prop] = desc = {134- configurable: true,135- enumerable,136- get() {137- return get(this[DRAFT_STATE], prop)138- },139- set(value) {140- set(this[DRAFT_STATE], prop, value)141- }142- }143- }144- Object.defineProperty(draft, prop, desc)129+ let desc = descriptors[prop]130+ if (desc) {131+ desc.enumerable = enumerable132+ } else {133+ descriptors[prop] = desc = {134+ configurable: true,135+ enumerable,136+ get() {137+ return get(this[DRAFT_STATE], prop)138+ },139+ set(value) {140+ set(this[DRAFT_STATE], prop, value)141+ }142+ }143+ }144+ Object.defineProperty(draft, prop, desc)145 }146 147 function assertUnrevoked(state) {148- if (state.revoked === true)149- throw new Error(150- "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +151- JSON.stringify(source(state))152- )148+ if (state.revoked === true)149+ throw new Error(150+ "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +151+ JSON.stringify(source(state))152+ )153 }154 155 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.156 function markChangesSweep(drafts) {157- // The natural order of drafts in the `scope` array is based on when they158- // were accessed. By processing drafts in reverse natural order, we have a159- // better chance of processing leaf nodes first. When a leaf node is known to160- // have changed, we can avoid any traversal of its ancestor nodes.161- for (let i = drafts.length - 1; i >= 0; i--) {162- const state = drafts[i][DRAFT_STATE]163- if (!state.modified) {164- if (Array.isArray(state.base)) {165- if (hasArrayChanges(state)) markChanged(state)166- } else if (hasObjectChanges(state)) markChanged(state)167- }168- }157+ // The natural order of drafts in the `scope` array is based on when they158+ // were accessed. By processing drafts in reverse natural order, we have a159+ // better chance of processing leaf nodes first. When a leaf node is known to160+ // have changed, we can avoid any traversal of its ancestor nodes.161+ for (let i = drafts.length - 1; i >= 0; i--) {162+ const state = drafts[i][DRAFT_STATE]163+ if (!state.modified) {164+ if (Array.isArray(state.base)) {165+ if (hasArrayChanges(state)) markChanged(state)166+ } else if (hasObjectChanges(state)) markChanged(state)167+ }168+ }169 }170 171 function markChangesRecursively(object) {172- if (!object || typeof object !== "object") return173- const state = object[DRAFT_STATE]174- if (!state) return175- const {base, draft, assigned} = state176- if (!Array.isArray(object)) {177- // Look for added keys.178- Object.keys(draft).forEach(key => {179- // The `undefined` check is a fast path for pre-existing keys.180- if (base[key] === undefined && !has(base, key)) {181- assigned[key] = true182- markChanged(state)183- } else if (!assigned[key]) {184- // Only untouched properties trigger recursion.185- markChangesRecursively(draft[key])186- }187- })188- // Look for removed keys.189- Object.keys(base).forEach(key => {190- // The `undefined` check is a fast path for pre-existing keys.191- if (draft[key] === undefined && !has(draft, key)) {192- assigned[key] = false193- markChanged(state)194- }195- })196- } else if (hasArrayChanges(state)) {197- markChanged(state)198- assigned.length = true199- if (draft.length < base.length) {200- for (let i = draft.length; i < base.length; i++) assigned[i] = false201- } else {202- for (let i = base.length; i < draft.length; i++) assigned[i] = true203- }204- for (let i = 0; i < draft.length; i++) {205- // Only untouched indices trigger recursion.206- if (assigned[i] === undefined) markChangesRecursively(draft[i])207- }208- }172+ if (!object || typeof object !== "object") return173+ const state = object[DRAFT_STATE]174+ if (!state) return175+ const {base, draft, assigned} = state176+ if (!Array.isArray(object)) {177+ // Look for added keys.178+ Object.keys(draft).forEach(key => {179+ // The `undefined` check is a fast path for pre-existing keys.180+ if (base[key] === undefined && !has(base, key)) {181+ assigned[key] = true182+ markChanged(state)183+ } else if (!assigned[key]) {184+ // Only untouched properties trigger recursion.185+ markChangesRecursively(draft[key])186+ }187+ })188+ // Look for removed keys.189+ Object.keys(base).forEach(key => {190+ // The `undefined` check is a fast path for pre-existing keys.191+ if (draft[key] === undefined && !has(draft, key)) {192+ assigned[key] = false193+ markChanged(state)194+ }195+ })196+ } else if (hasArrayChanges(state)) {197+ markChanged(state)198+ assigned.length = true199+ if (draft.length < base.length) {200+ for (let i = draft.length; i < base.length; i++) assigned[i] = false201+ } else {202+ for (let i = base.length; i < draft.length; i++) assigned[i] = true203+ }204+ for (let i = 0; i < draft.length; i++) {205+ // Only untouched indices trigger recursion.206+ if (assigned[i] === undefined) markChangesRecursively(draft[i])207+ }208+ }209 }210 211 function hasObjectChanges(state) {212- const {base, draft} = state212+ const {base, draft} = state213 214- // Search for added keys and changed keys. Start at the back, because215- // non-numeric keys are ordered by time of definition on the object.216- const keys = Object.keys(draft)217- for (let i = keys.length - 1; i >= 0; i--) {218- const key = keys[i]219- const baseValue = base[key]220- // The `undefined` check is a fast path for pre-existing keys.221- if (baseValue === undefined && !has(base, key)) {222- return true223- }224- // Once a base key is deleted, future changes go undetected, because its225- // descriptor is erased. This branch detects any missed changes.226- else {227- const value = draft[key]228- const state = value && value[DRAFT_STATE]229- if (state ? state.base !== baseValue : !is(value, baseValue)) {230- return true231- }232- }233- }214+ // Search for added keys and changed keys. Start at the back, because215+ // non-numeric keys are ordered by time of definition on the object.216+ const keys = Object.keys(draft)217+ for (let i = keys.length - 1; i >= 0; i--) {218+ const key = keys[i]219+ const baseValue = base[key]220+ // The `undefined` check is a fast path for pre-existing keys.221+ if (baseValue === undefined && !has(base, key)) {222+ return true223+ }224+ // Once a base key is deleted, future changes go undetected, because its225+ // descriptor is erased. This branch detects any missed changes.226+ else {227+ const value = draft[key]228+ const state = value && value[DRAFT_STATE]229+ if (state ? state.base !== baseValue : !is(value, baseValue)) {230+ return true231+ }232+ }233+ }234 235- // At this point, no keys were added or changed.236- // Compare key count to determine if keys were deleted.237- return keys.length !== Object.keys(base).length235+ // At this point, no keys were added or changed.236+ // Compare key count to determine if keys were deleted.237+ return keys.length !== Object.keys(base).length238 }239 240 function hasArrayChanges(state) {241- const {draft} = state242- if (draft.length !== state.base.length) return true243- // See #116244- // If we first shorten the length, our array interceptors will be removed.245- // If after that new items are added, result in the same original length,246- // those last items will have no intercepting property.247- // So if there is no own descriptor on the last position, we know that items were removed and added248- // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check249- // the last one250- const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)251- // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)252- if (descriptor && !descriptor.get) return true253- // For all other cases, we don't have to compare, as they would have been picked up by the index setters254- return false241+ const {draft} = state242+ if (draft.length !== state.base.length) return true243+ // See #116244+ // If we first shorten the length, our array interceptors will be removed.245+ // If after that new items are added, result in the same original length,246+ // those last items will have no intercepting property.247+ // So if there is no own descriptor on the last position, we know that items were removed and added248+ // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check249+ // the last one250+ const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)251+ // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)252+ if (descriptor && !descriptor.get) return true253+ // For all other cases, we don't have to compare, as they would have been picked up by the index setters254+ return false255 }256 257 function createHiddenProperty(target, prop, value) {258- Object.defineProperty(target, prop, {259- value: value,260- enumerable: false,261- writable: true262- })258+ Object.defineProperty(target, prop, {259+ value: value,260+ enumerable: false,261+ writable: true262+ })263 }modified:src/immer.d.ts+124 added-124 removed
1 type Tail<T extends any[]> = ((...t: T) => any) extends ((2- _: any,3- ...tail: infer TT2+ _: any,3+ ...tail: infer TT4 ) => any)5- ? TT6- : []5+ ? TT6+ : []7 8 /** Object types that should never be mapped */9 type AtomicObject =10- | Function11- | Map<any, any>12- | WeakMap<any, any>13- | Set<any>14- | WeakSet<any>15- | Promise<any>16- | Date17- | RegExp18- | Boolean19- | Number20- | String10+ | Function11+ | Map<any, any>12+ | WeakMap<any, any>13+ | Set<any>14+ | WeakSet<any>15+ | Promise<any>16+ | Date17+ | RegExp18+ | Boolean19+ | Number20+ | String21 22 export type Draft<T> = T extends AtomicObject23- ? T24- : T extends object25- ? {-readonly [K in keyof T]: Draft<T[K]>}26- : T23+ ? T24+ : T extends object25+ ? {-readonly [K in keyof T]: Draft<T[K]>}26+ : T27 28 /** Convert a mutable type into a readonly type */29 export type Immutable<T> = T extends AtomicObject30- ? T31- : T extends object32- ? {readonly [K in keyof T]: Immutable<T[K]>}33- : T30+ ? T31+ : T extends object32+ ? {readonly [K in keyof T]: Immutable<T[K]>}33+ : T34 35 export interface Patch {36- op: "replace" | "remove" | "add"37- path: (string | number)[]38- value?: any36+ op: "replace" | "remove" | "add"37+ path: (string | number)[]38+ value?: any39 }40 41 export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void42 1 unmodified line44 type FromNothing<T> = T extends Nothing ? undefined : T45 46 /** The inferred return type of `produce` */47 export type Produced<Base, Return> = Return extends void48- ? Base49- : Return extends Promise<infer Result>50- ? Promise<Result extends void ? Base : FromNothing<Result>>51- : FromNothing<Return>48+ ? Base49+ : Return extends Promise<infer Result>50+ ? Promise<Result extends void ? Base : FromNothing<Result>>51+ : FromNothing<Return>52 53 /**54 * The `produce` function takes a value and a "recipe function" (whose55 * return value often depends on the base state). The recipe function is13 unmodified lines69 * @param {Function} patchListener - optional function that will be called with all the patches produced here70 * @returns {any} a new state, or the initial state if nothing was modified71 */72 export interface IProduce {73- /** Curried producer */74- <75- Recipe extends (...args: any[]) => any,76- Params extends any[] = Parameters<Recipe>,77- T = Params[0]78- >(79- recipe: Recipe80- ): <Base extends Immutable<T>>(81- base: Base,82- ...rest: Tail<Params>83- ) => Produced<Base, ReturnType<Recipe>>84- // ^ by making the returned type generic, the actual type of the passed in object is preferred85- // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe86- // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!73+ /** Curried producer */74+ <75+ Recipe extends (...args: any[]) => any,76+ Params extends any[] = Parameters<Recipe>,77+ T = Params[0]78+ >(79+ recipe: Recipe80+ ): <Base extends Immutable<T>>(81+ base: Base,82+ ...rest: Tail<Params>83+ ) => Produced<Base, ReturnType<Recipe>>84+ // ^ by making the returned type generic, the actual type of the passed in object is preferred85+ // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe86+ // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!87 88- /** Curried producer with initial state */89- <90- Recipe extends (...args: any[]) => any,91- Params extends any[] = Parameters<Recipe>,92- T = Params[0]93- >(94- recipe: Recipe,95- initialState: Immutable<T>96- ): <Base extends Immutable<T>>(97- base?: Base,98- ...rest: Tail<Params>99- ) => Produced<Base, ReturnType<Recipe>>88+ /** Curried producer with initial state */89+ <90+ Recipe extends (...args: any[]) => any,91+ Params extends any[] = Parameters<Recipe>,92+ T = Params[0]93+ >(94+ recipe: Recipe,95+ initialState: Immutable<T>96+ ): <Base extends Immutable<T>>(97+ base?: Base,98+ ...rest: Tail<Params>99+ ) => Produced<Base, ReturnType<Recipe>>100 101- /** Normal producer */102- <Base, D = Draft<Base>, Return = void>(103- base: Base,104- recipe: (draft: D) => Return,105- listener?: PatchListener106- ): Produced<Base, Return>101+ /** Normal producer */102+ <Base, D = Draft<Base>, Return = void>(103+ base: Base,104+ recipe: (draft: D) => Return,105+ listener?: PatchListener106+ ): Produced<Base, Return>107 }108 109 export const produce: IProduce110 export default produce111 112 /** Use a class type for `nothing` so its type is unique */113 declare class Nothing {114- // This lets us do `Exclude<T, Nothing>`115- private _: any114+ // This lets us do `Exclude<T, Nothing>`115+ private _: any116 }117 118 /**119 * The sentinel value returned by producers to replace the draft with undefined.57 unmodified lines177 /** Returns true if the given value can be drafted by Immer */178 export function isDraftable(value: any): boolean179 180 export class Immer {181- constructor(config: {182- useProxies?: boolean183- autoFreeze?: boolean184- onAssign?: (185- state: ImmerState,186- prop: string | number,187- value: unknown188- ) => void189- onDelete?: (state: ImmerState, prop: string | number) => void190- onCopy?: (state: ImmerState) => void191- })192- /**193- * The `produce` function takes a value and a "recipe function" (whose194- * return value often depends on the base state). The recipe function is195- * free to mutate its first argument however it wants. All mutations are196- * only ever applied to a __copy__ of the base state.197- *198- * Pass only a function to create a "curried producer" which relieves you199- * from passing the recipe function every time.200- *201- * Only plain objects and arrays are made mutable. All other objects are202- * considered uncopyable.203- *204- * Note: This function is __bound__ to its `Immer` instance.205- *206- * @param {any} base - the initial state207- * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified208- * @param {Function} patchListener - optional function that will be called with all the patches produced here209- * @returns {any} a new state, or the initial state if nothing was modified210- */211- produce: IProduce212- /**213- * When true, `produce` will freeze the copies it creates.214- */215- readonly autoFreeze: boolean216- /**217- * When true, drafts are ES2015 proxies.218- */219- readonly useProxies: boolean220- /**221- * Pass true to automatically freeze all copies created by Immer.222- *223- * By default, auto-freezing is disabled in production.224- */225- setAutoFreeze(autoFreeze: boolean): void226- /**227- * Pass true to use the ES2015 `Proxy` class when creating drafts, which is228- * always faster than using ES5 proxies.229- *230- * By default, feature detection is used, so calling this is rarely necessary.231- */232- setUseProxies(useProxies: boolean): void181+ constructor(config: {182+ useProxies?: boolean183+ autoFreeze?: boolean184+ onAssign?: (185+ state: ImmerState,186+ prop: string | number,187+ value: unknown188+ ) => void189+ onDelete?: (state: ImmerState, prop: string | number) => void190+ onCopy?: (state: ImmerState) => void191+ })192+ /**193+ * The `produce` function takes a value and a "recipe function" (whose194+ * return value often depends on the base state). The recipe function is195+ * free to mutate its first argument however it wants. All mutations are196+ * only ever applied to a __copy__ of the base state.197+ *198+ * Pass only a function to create a "curried producer" which relieves you199+ * from passing the recipe function every time.200+ *201+ * Only plain objects and arrays are made mutable. All other objects are202+ * considered uncopyable.203+ *204+ * Note: This function is __bound__ to its `Immer` instance.205+ *206+ * @param {any} base - the initial state207+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified208+ * @param {Function} patchListener - optional function that will be called with all the patches produced here209+ * @returns {any} a new state, or the initial state if nothing was modified210+ */211+ produce: IProduce212+ /**213+ * When true, `produce` will freeze the copies it creates.214+ */215+ readonly autoFreeze: boolean216+ /**217+ * When true, drafts are ES2015 proxies.218+ */219+ readonly useProxies: boolean220+ /**221+ * Pass true to automatically freeze all copies created by Immer.222+ *223+ * By default, auto-freezing is disabled in production.224+ */225+ setAutoFreeze(autoFreeze: boolean): void226+ /**227+ * Pass true to use the ES2015 `Proxy` class when creating drafts, which is228+ * always faster than using ES5 proxies.229+ *230+ * By default, feature detection is used, so calling this is rarely necessary.231+ */232+ setUseProxies(useProxies: boolean): void233 }234 235 export interface ImmerState<T = any> {236- parent?: ImmerState237- base: T238- copy: T239- assigned: {[prop: string]: boolean; [index: number]: boolean}236+ parent?: ImmerState237+ base: T238+ copy: T239+ assigned: {[prop: string]: boolean; [index: number]: boolean}240 }241 242 // Backward compatibility with --target es5243 declare global {244- interface Set<T> {}245- interface Map<K, V> {}246- interface WeakSet<T> {}247- interface WeakMap<K extends object, V> {}244+ interface Set<T> {}245+ interface Map<K, V> {}246+ interface WeakSet<T> {}247+ interface WeakMap<K extends object, V> {}248 }modified:src/immer.js+253 added-258 removed
1 import * as legacyProxy from "./es5"2 import * as modernProxy from "./proxy"3 import {applyPatches, generatePatches} from "./patches"4 import {5- assign,6- each,7- has,8- is,9- isDraft,10- isDraftable,11- isEnumerable,12- shallowCopy,13- DRAFT_STATE,14- NOTHING5+ assign,6+ each,7+ has,8+ is,9+ isDraft,10+ isDraftable,11+ isEnumerable,12+ shallowCopy,13+ DRAFT_STATE,14+ NOTHING15 } from "./common"16 import {ImmerScope} from "./scope"17 18 function verifyMinified() {}19 20 const configDefaults = {21- useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",22- autoFreeze:23- typeof process !== "undefined"24- ? process.env.NODE_ENV !== "production"25- : verifyMinified.name === "verifyMinified",26- onAssign: null,27- onDelete: null,28- onCopy: null21+ useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",22+ autoFreeze:23+ typeof process !== "undefined"24+ ? process.env.NODE_ENV !== "production"25+ : verifyMinified.name === "verifyMinified",26+ onAssign: null,27+ onDelete: null,28+ onCopy: null29 }30 31 export class Immer {32- constructor(config) {33- assign(this, configDefaults, config)34- this.setUseProxies(this.useProxies)35- this.produce = this.produce.bind(this)36- }37- produce(base, recipe, patchListener) {38- // curried invocation39- if (typeof base === "function" && typeof recipe !== "function") {40- const defaultBase = recipe41- recipe = base32+ constructor(config) {33+ assign(this, configDefaults, config)34+ this.setUseProxies(this.useProxies)35+ this.produce = this.produce.bind(this)36+ }37+ produce(base, recipe, patchListener) {38+ // curried invocation39+ if (typeof base === "function" && typeof recipe !== "function") {40+ const defaultBase = recipe41+ recipe = base42 43- const self = this44- return function curriedProduce(base = defaultBase, ...args) {45- return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore46- }47- }43+ const self = this44+ return function curriedProduce(base = defaultBase, ...args) {45+ return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore46+ }47+ }48 49- // prettier-ignore50- {51- if (typeof recipe !== "function") {52- throw new Error("The first or second argument to `produce` must be a function")53- }54- if (patchListener !== undefined && typeof patchListener !== "function") {55- throw new Error("The third argument to `produce` must be a function or undefined")56- }57- }49+ // prettier-ignore50+ {51+ if (typeof recipe !== "function") {52+ throw new Error("The first or second argument to `produce` must be a function")53+ }54+ if (patchListener !== undefined && typeof patchListener !== "function") {55+ throw new Error("The third argument to `produce` must be a function or undefined")56+ }57+ }58 59- let result59+ let result60 61- // Only plain objects, arrays, and "immerable classes" are drafted.62- if (isDraftable(base)) {63- const scope = ImmerScope.enter()64- const proxy = this.createProxy(base)65- let hasError = true66- try {67- result = recipe(proxy)68- hasError = false69- } finally {70- // finally instead of catch + rethrow better preserves original stack71- if (hasError) scope.revoke()72- else scope.leave()73- }74- if (result instanceof Promise) {75- return result.then(76- result => {77- scope.usePatches(patchListener)78- return this.processResult(result, scope)79- },80- error => {81- scope.revoke()82- throw error83- }84- )85- }86- scope.usePatches(patchListener)87- return this.processResult(result, scope)88- } else {89- result = recipe(base)90- if (result === undefined) return base91- return result !== NOTHING ? result : undefined92- }93- }94- createDraft(base) {95- if (!isDraftable(base)) {96- throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore97- }98- const scope = ImmerScope.enter()99- const proxy = this.createProxy(base)100- proxy[DRAFT_STATE].isManual = true101- scope.leave()102- return proxy103- }104- finishDraft(draft, patchListener) {105- const state = draft && draft[DRAFT_STATE]106- if (!state || !state.isManual) {107- throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore108- }109- if (state.finalized) {110- throw new Error("The given draft is already finalized") // prettier-ignore111- }112- const {scope} = state113- scope.usePatches(patchListener)114- return this.processResult(undefined, scope)115- }116- setAutoFreeze(value) {117- this.autoFreeze = value118- }119- setUseProxies(value) {120- this.useProxies = value121- assign(this, value ? modernProxy : legacyProxy)122- }123- applyPatches(base, patches) {124- // Mutate the base state when a draft is passed.125- if (isDraft(base)) {126- return applyPatches(base, patches)127- }128- // Otherwise, produce a copy of the base state.129- return this.produce(base, draft => applyPatches(draft, patches))130- }131- /** @internal */132- processResult(result, scope) {133- const baseDraft = scope.drafts[0]134- const isReplaced = result !== undefined && result !== baseDraft135- this.willFinalize(scope, result, isReplaced)136- if (isReplaced) {137- if (baseDraft[DRAFT_STATE].modified) {138- scope.revoke()139- throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore140- }141- if (isDraftable(result)) {142- // Finalize the result in case it contains (or is) a subset of the draft.143- result = this.finalize(result, null, scope)144- }145- if (scope.patches) {146- scope.patches.push({147- op: "replace",148- path: [],149- value: result150- })151- scope.inversePatches.push({152- op: "replace",153- path: [],154- value: baseDraft[DRAFT_STATE].base155- })156- }157- } else {158- // Finalize the base draft.159- result = this.finalize(baseDraft, [], scope)160- }161- scope.revoke()162- if (scope.patches) {163- scope.patchListener(scope.patches, scope.inversePatches)164- }165- return result !== NOTHING ? result : undefined166- }167- /**168- * @internal169- * Finalize a draft, returning either the unmodified base state or a modified170- * copy of the base state.171- */172- finalize(draft, path, scope) {173- const state = draft[DRAFT_STATE]174- if (!state) {175- if (Object.isFrozen(draft)) return draft176- return this.finalizeTree(draft, null, scope)177- }178- // Never finalize drafts owned by another scope.179- if (state.scope !== scope) {180- return draft181- }182- if (!state.modified) {183- return state.base184- }185- if (!state.finalized) {186- state.finalized = true187- this.finalizeTree(state.draft, path, scope)61+ // Only plain objects, arrays, and "immerable classes" are drafted.62+ if (isDraftable(base)) {63+ const scope = ImmerScope.enter()64+ const proxy = this.createProxy(base)65+ let hasError = true66+ try {67+ result = recipe(proxy)68+ hasError = false69+ } finally {70+ // finally instead of catch + rethrow better preserves original stack71+ if (hasError) scope.revoke()72+ else scope.leave()73+ }74+ if (result instanceof Promise) {75+ return result.then(76+ result => {77+ scope.usePatches(patchListener)78+ return this.processResult(result, scope)79+ },80+ error => {81+ scope.revoke()82+ throw error83+ }84+ )85+ }86+ scope.usePatches(patchListener)87+ return this.processResult(result, scope)88+ } else {89+ result = recipe(base)90+ if (result === undefined) return base91+ return result !== NOTHING ? result : undefined92+ }93+ }94+ createDraft(base) {95+ if (!isDraftable(base)) {96+ throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore97+ }98+ const scope = ImmerScope.enter()99+ const proxy = this.createProxy(base)100+ proxy[DRAFT_STATE].isManual = true101+ scope.leave()102+ return proxy103+ }104+ finishDraft(draft, patchListener) {105+ const state = draft && draft[DRAFT_STATE]106+ if (!state || !state.isManual) {107+ throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore108+ }109+ if (state.finalized) {110+ throw new Error("The given draft is already finalized") // prettier-ignore111+ }112+ const {scope} = state113+ scope.usePatches(patchListener)114+ return this.processResult(undefined, scope)115+ }116+ setAutoFreeze(value) {117+ this.autoFreeze = value118+ }119+ setUseProxies(value) {120+ this.useProxies = value121+ assign(this, value ? modernProxy : legacyProxy)122+ }123+ applyPatches(base, patches) {124+ // Mutate the base state when a draft is passed.125+ if (isDraft(base)) {126+ return applyPatches(base, patches)127+ }128+ // Otherwise, produce a copy of the base state.129+ return this.produce(base, draft => applyPatches(draft, patches))130+ }131+ /** @internal */132+ processResult(result, scope) {133+ const baseDraft = scope.drafts[0]134+ const isReplaced = result !== undefined && result !== baseDraft135+ this.willFinalize(scope, result, isReplaced)136+ if (isReplaced) {137+ if (baseDraft[DRAFT_STATE].modified) {138+ scope.revoke()139+ throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore140+ }141+ if (isDraftable(result)) {142+ // Finalize the result in case it contains (or is) a subset of the draft.143+ result = this.finalize(result, null, scope)144+ }145+ if (scope.patches) {146+ scope.patches.push({147+ op: "replace",148+ path: [],149+ value: result150+ })151+ scope.inversePatches.push({152+ op: "replace",153+ path: [],154+ value: baseDraft[DRAFT_STATE].base155+ })156+ }157+ } else {158+ // Finalize the base draft.159+ result = this.finalize(baseDraft, [], scope)160+ }161+ scope.revoke()162+ if (scope.patches) {163+ scope.patchListener(scope.patches, scope.inversePatches)164+ }165+ return result !== NOTHING ? result : undefined166+ }167+ /**168+ * @internal169+ * Finalize a draft, returning either the unmodified base state or a modified170+ * copy of the base state.171+ */172+ finalize(draft, path, scope) {173+ const state = draft[DRAFT_STATE]174+ if (!state) {175+ if (Object.isFrozen(draft)) return draft176+ return this.finalizeTree(draft, null, scope)177+ }178+ // Never finalize drafts owned by another scope.179+ if (state.scope !== scope) {180+ return draft181+ }182+ if (!state.modified) {183+ return state.base184+ }185+ if (!state.finalized) {186+ state.finalized = true187+ this.finalizeTree(state.draft, path, scope)188 189- if (this.onDelete) {190- // The `assigned` object is unreliable with ES5 drafts.191- if (this.useProxies) {192- const {assigned} = state193- for (const prop in assigned) {194- if (!assigned[prop]) this.onDelete(state, prop)195- }196- } else {197- const {base, copy} = state198- each(base, prop => {199- if (!has(copy, prop)) this.onDelete(state, prop)200- })201- }202- }203- if (this.onCopy) {204- this.onCopy(state)205- }189+ if (this.onDelete) {190+ // The `assigned` object is unreliable with ES5 drafts.191+ if (this.useProxies) {192+ const {assigned} = state193+ for (const prop in assigned) {194+ if (!assigned[prop]) this.onDelete(state, prop)195+ }196+ } else {197+ const {base, copy} = state198+ each(base, prop => {199+ if (!has(copy, prop)) this.onDelete(state, prop)200+ })201+ }202+ }203+ if (this.onCopy) {204+ this.onCopy(state)205+ }206 207- // At this point, all descendants of `state.copy` have been finalized,208- // so we can be sure that `scope.canAutoFreeze` is accurate.209- if (this.autoFreeze && scope.canAutoFreeze) {210- Object.freeze(state.copy)211- }207+ // At this point, all descendants of `state.copy` have been finalized,208+ // so we can be sure that `scope.canAutoFreeze` is accurate.209+ if (this.autoFreeze && scope.canAutoFreeze) {210+ Object.freeze(state.copy)211+ }212 213- if (path && scope.patches) {214- generatePatches(215- state,216- path,217- scope.patches,218- scope.inversePatches219- )220- }221- }222- return state.copy223- }224- /**225- * @internal226- * Finalize all drafts in the given state tree.227- */228- finalizeTree(root, rootPath, scope) {229- const state = root[DRAFT_STATE]230- if (state) {231- if (!this.useProxies) {232- // Create the final copy, with added keys and without deleted keys.233- state.copy = shallowCopy(state.draft, true)234- }235- root = state.copy236- }213+ if (path && scope.patches) {214+ generatePatches(state, path, scope.patches, scope.inversePatches)215+ }216+ }217+ return state.copy218+ }219+ /**220+ * @internal221+ * Finalize all drafts in the given state tree.222+ */223+ finalizeTree(root, rootPath, scope) {224+ const state = root[DRAFT_STATE]225+ if (state) {226+ if (!this.useProxies) {227+ // Create the final copy, with added keys and without deleted keys.228+ state.copy = shallowCopy(state.draft, true)229+ }230+ root = state.copy231+ }232 238- const needPatches = !!rootPath && !!scope.patches239- const finalizeProperty = (prop, value, parent) => {240- if (value === parent) {241- throw Error("Immer forbids circular references")242- }233+ const needPatches = !!rootPath && !!scope.patches234+ const finalizeProperty = (prop, value, parent) => {235+ if (value === parent) {236+ throw Error("Immer forbids circular references")237+ }238 244- // In the `finalizeTree` method, only the `root` object may be a draft.245- const isDraftProp = !!state && parent === root239+ // In the `finalizeTree` method, only the `root` object may be a draft.240+ const isDraftProp = !!state && parent === root241 247- if (isDraft(value)) {248- const path =249- isDraftProp && needPatches && !state.assigned[prop]250- ? rootPath.concat(prop)251- : null242+ if (isDraft(value)) {243+ const path =244+ isDraftProp && needPatches && !state.assigned[prop]245+ ? rootPath.concat(prop)246+ : null247 253- // Drafts owned by `scope` are finalized here.254- value = this.finalize(value, path, scope)248+ // Drafts owned by `scope` are finalized here.249+ value = this.finalize(value, path, scope)250 256- // Drafts from another scope must prevent auto-freezing.257- if (isDraft(value)) {258- scope.canAutoFreeze = false259- }251+ // Drafts from another scope must prevent auto-freezing.252+ if (isDraft(value)) {253+ scope.canAutoFreeze = false254+ }255 261- // Preserve non-enumerable properties.262- if (Array.isArray(parent) || isEnumerable(parent, prop)) {263- parent[prop] = value264- } else {265- Object.defineProperty(parent, prop, {value})266- }256+ // Preserve non-enumerable properties.257+ if (Array.isArray(parent) || isEnumerable(parent, prop)) {258+ parent[prop] = value259+ } else {260+ Object.defineProperty(parent, prop, {value})261+ }262 268- // Unchanged drafts are never passed to the `onAssign` hook.269- if (isDraftProp && value === state.base[prop]) return270- }271- // Unchanged draft properties are ignored.272- else if (isDraftProp && is(value, state.base[prop])) {273- return274- }275- // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.276- else if (isDraftable(value) && !Object.isFrozen(value)) {277- each(value, finalizeProperty)278- }263+ // Unchanged drafts are never passed to the `onAssign` hook.264+ if (isDraftProp && value === state.base[prop]) return265+ }266+ // Unchanged draft properties are ignored.267+ else if (isDraftProp && is(value, state.base[prop])) {268+ return269+ }270+ // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.271+ else if (isDraftable(value) && !Object.isFrozen(value)) {272+ each(value, finalizeProperty)273+ }274 280- if (isDraftProp && this.onAssign) {281- this.onAssign(state, prop, value)282- }283- }275+ if (isDraftProp && this.onAssign) {276+ this.onAssign(state, prop, value)277+ }278+ }279 285- each(root, finalizeProperty)286- return root287- }280+ each(root, finalizeProperty)281+ return root282+ }283 }modified:src/index.js+5 added-5 removed
61 unmodified lines62 */63 export const finishDraft = immer.finishDraft.bind(immer)64 65 export {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"72 73 export {Immer}modified:src/patches.js+115 added-115 removed
1 import {each} from "./common"2 3 export function generatePatches(state, basePath, patches, inversePatches) {4- Array.isArray(state.base)5- ? generateArrayPatches(state, basePath, patches, inversePatches)6- : generateObjectPatches(state, basePath, patches, inversePatches)4+ Array.isArray(state.base)5+ ? generateArrayPatches(state, basePath, patches, inversePatches)6+ : generateObjectPatches(state, basePath, patches, inversePatches)7 }8 9 function generateArrayPatches(state, basePath, patches, inversePatches) {10- let {base, copy, assigned} = state10+ let {base, copy, assigned} = state11 12- // Reduce complexity by ensuring `base` is never longer.13- if (copy.length < base.length) {14- ;[base, copy] = [copy, base]15- ;[patches, inversePatches] = [inversePatches, patches]16- }12+ // Reduce complexity by ensuring `base` is never longer.13+ if (copy.length < base.length) {14+ ;[base, copy] = [copy, base]15+ ;[patches, inversePatches] = [inversePatches, patches]16+ }17 18- const delta = copy.length - base.length18+ const delta = copy.length - base.length19 20- // Find the first replaced index.21- let start = 022- while (base[start] === copy[start] && start < base.length) {23- ++start24- }20+ // Find the first replaced index.21+ let start = 022+ while (base[start] === copy[start] && start < base.length) {23+ ++start24+ }25 26- // Find the last replaced index. Search from the end to optimize splice patches.27- let end = base.length28- while (end > start && base[end - 1] === copy[end + delta - 1]) {29- --end30- }26+ // Find the last replaced index. Search from the end to optimize splice patches.27+ let end = base.length28+ while (end > start && base[end - 1] === copy[end + delta - 1]) {29+ --end30+ }31 32- // Process replaced indices.33- for (let i = start; i < end; ++i) {34- if (assigned[i] && copy[i] !== base[i]) {35- const path = basePath.concat([i])36- patches.push({37- op: "replace",38- path,39- value: copy[i]40- })41- inversePatches.push({42- op: "replace",43- path,44- value: base[i]45- })46- }47- }32+ // Process replaced indices.33+ for (let i = start; i < end; ++i) {34+ if (assigned[i] && copy[i] !== base[i]) {35+ const path = basePath.concat([i])36+ patches.push({37+ op: "replace",38+ path,39+ value: copy[i]40+ })41+ inversePatches.push({42+ op: "replace",43+ path,44+ value: base[i]45+ })46+ }47+ }48 49- const useRemove = end != base.length50- const replaceCount = patches.length49+ const useRemove = end != base.length50+ const replaceCount = patches.length51 52- // Process added indices.53- for (let i = end + delta - 1; i >= end; --i) {54- const path = basePath.concat([i])55- patches[replaceCount + i - end] = {56- op: "add",57- path,58- value: copy[i]59- }60- if (useRemove) {61- inversePatches.push({62- op: "remove",63- path64- })65- }66- }52+ // Process added indices.53+ for (let i = end + delta - 1; i >= end; --i) {54+ const path = basePath.concat([i])55+ patches[replaceCount + i - end] = {56+ op: "add",57+ path,58+ value: copy[i]59+ }60+ if (useRemove) {61+ inversePatches.push({62+ op: "remove",63+ path64+ })65+ }66+ }67 68- // One "replace" patch reverses all non-splicing "add" patches.69- if (!useRemove) {70- inversePatches.push({71- op: "replace",72- path: basePath.concat(["length"]),73- value: base.length74- })75- }68+ // One "replace" patch reverses all non-splicing "add" patches.69+ if (!useRemove) {70+ inversePatches.push({71+ op: "replace",72+ path: basePath.concat(["length"]),73+ value: base.length74+ })75+ }76 }77 78 function generateObjectPatches(state, basePath, patches, inversePatches) {79- const {base, copy} = state80- each(state.assigned, (key, assignedValue) => {81- const origValue = base[key]82- const value = copy[key]83- const op = !assignedValue ? "remove" : key in base ? "replace" : "add"84- if (origValue === value && op === "replace") return85- const path = basePath.concat(key)86- patches.push(op === "remove" ? {op, path} : {op, path, value})87- inversePatches.push(88- op === "add"89- ? {op: "remove", path}90- : op === "remove"91- ? {op: "add", path, value: origValue}92- : {op: "replace", path, value: origValue}93- )94- })79+ const {base, copy} = state80+ each(state.assigned, (key, assignedValue) => {81+ const origValue = base[key]82+ const value = copy[key]83+ const op = !assignedValue ? "remove" : key in base ? "replace" : "add"84+ if (origValue === value && op === "replace") return85+ const path = basePath.concat(key)86+ patches.push(op === "remove" ? {op, path} : {op, path, value})87+ inversePatches.push(88+ op === "add"89+ ? {op: "remove", path}90+ : op === "remove"91+ ? {op: "add", path, value: origValue}92+ : {op: "replace", path, value: origValue}93+ )94+ })95 }96 97 export function applyPatches(draft, patches) {98- for (let i = 0; i < patches.length; i++) {99- const patch = patches[i]100- const {path} = patch101- if (path.length === 0 && patch.op === "replace") {102- draft = patch.value103- } else {104- let base = draft105- for (let i = 0; i < path.length - 1; i++) {106- base = base[path[i]]107- if (!base || typeof base !== "object")108- throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore109- }110- const key = path[path.length - 1]111- switch (patch.op) {112- case "replace":113- base[key] = patch.value114- break115- case "add":116- if (Array.isArray(base)) {117- // TODO: support "foo/-" paths for appending to an array118- base.splice(key, 0, patch.value)119- } else {120- base[key] = patch.value121- }122- break123- case "remove":124- if (Array.isArray(base)) {125- base.splice(key, 1)126- } else {127- delete base[key]128- }129- break130- default:131- throw new Error("Unsupported patch operation: " + patch.op)132- }133- }134- }135- return draft98+ for (let i = 0; i < patches.length; i++) {99+ const patch = patches[i]100+ const {path} = patch101+ if (path.length === 0 && patch.op === "replace") {102+ draft = patch.value103+ } else {104+ let base = draft105+ for (let i = 0; i < path.length - 1; i++) {106+ base = base[path[i]]107+ if (!base || typeof base !== "object")108+ throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore109+ }110+ const key = path[path.length - 1]111+ switch (patch.op) {112+ case "replace":113+ base[key] = patch.value114+ break115+ case "add":116+ if (Array.isArray(base)) {117+ // TODO: support "foo/-" paths for appending to an array118+ base.splice(key, 0, patch.value)119+ } else {120+ base[key] = patch.value121+ }122+ break123+ case "remove":124+ if (Array.isArray(base)) {125+ base.splice(key, 1)126+ } else {127+ delete base[key]128+ }129+ break130+ default:131+ throw new Error("Unsupported patch operation: " + patch.op)132+ }133+ }134+ }135+ return draft136 }modified:src/proxy.js+130 added-130 removed
1 "use strict"2 import {3- assign,4- each,5- has,6- is,7- isDraftable,8- isDraft,9- shallowCopy,10- DRAFT_STATE3+ assign,4+ each,5+ has,6+ is,7+ isDraftable,8+ isDraft,9+ shallowCopy,10+ DRAFT_STATE11 } from "./common"12 import {ImmerScope} from "./scope"13 14 // Do nothing before being finalized.15 export function willFinalize() {}16 17 export function createProxy(base, parent) {18- const scope = parent ? parent.scope : ImmerScope.current19- const state = {20- // Track which produce call this is associated with.21- scope,22- // True for both shallow and deep changes.23- modified: false,24- // Used during finalization.25- finalized: false,26- // Track which properties have been assigned (true) or deleted (false).27- assigned: {},28- // The parent draft state.29- parent,30- // The base state.31- base,32- // The base proxy.33- draft: null,34- // Any property proxies.35- drafts: {},36- // The base copy with any updated values.37- copy: null,38- // Called by the `produce` function.39- revoke: null40- }18+ const scope = parent ? parent.scope : ImmerScope.current19+ const state = {20+ // Track which produce call this is associated with.21+ scope,22+ // True for both shallow and deep changes.23+ modified: false,24+ // Used during finalization.25+ finalized: false,26+ // Track which properties have been assigned (true) or deleted (false).27+ assigned: {},28+ // The parent draft state.29+ parent,30+ // The base state.31+ base,32+ // The base proxy.33+ draft: null,34+ // Any property proxies.35+ drafts: {},36+ // The base copy with any updated values.37+ copy: null,38+ // Called by the `produce` function.39+ revoke: null40+ }41 42- const {revoke, proxy} = Array.isArray(base)43- ? // [state] is used for arrays, to make sure the proxy is array-ish and not violate invariants,44- // although state itself is an object45- Proxy.revocable([state], arrayTraps)46- : Proxy.revocable(state, objectTraps)42+ const {revoke, proxy} = Array.isArray(base)43+ ? // [state] is used for arrays, to make sure the proxy is array-ish and not violate invariants,44+ // although state itself is an object45+ Proxy.revocable([state], arrayTraps)46+ : Proxy.revocable(state, objectTraps)47 48- state.draft = proxy49- state.revoke = revoke48+ state.draft = proxy49+ state.revoke = revoke50 51- scope.drafts.push(proxy)52- return proxy51+ scope.drafts.push(proxy)52+ return proxy53 }54 55 const objectTraps = {56- get,57- has(target, prop) {58- return prop in source(target)59- },60- ownKeys(target) {61- return Reflect.ownKeys(source(target))62- },63- set,64- deleteProperty,65- getOwnPropertyDescriptor,66- defineProperty() {67- throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore68- },69- getPrototypeOf(target) {70- return Object.getPrototypeOf(target.base)71- },72- setPrototypeOf() {73- throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore74- }56+ get,57+ has(target, prop) {58+ return prop in source(target)59+ },60+ ownKeys(target) {61+ return Reflect.ownKeys(source(target))62+ },63+ set,64+ deleteProperty,65+ getOwnPropertyDescriptor,66+ defineProperty() {67+ throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore68+ },69+ getPrototypeOf(target) {70+ return Object.getPrototypeOf(target.base)71+ },72+ setPrototypeOf() {73+ throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore74+ }75 }76 77 const arrayTraps = {}78 each(objectTraps, (key, fn) => {79- arrayTraps[key] = function() {80- arguments[0] = arguments[0][0]81- return fn.apply(this, arguments)82- }79+ arrayTraps[key] = function() {80+ arguments[0] = arguments[0][0]81+ return fn.apply(this, arguments)82+ }83 })84 arrayTraps.deleteProperty = function(state, prop) {85- if (isNaN(parseInt(prop))) {86- throw new Error("Immer only supports deleting array indices") // prettier-ignore87- }88- return objectTraps.deleteProperty.call(this, state[0], prop)85+ if (isNaN(parseInt(prop))) {86+ throw new Error("Immer only supports deleting array indices") // prettier-ignore87+ }88+ return objectTraps.deleteProperty.call(this, state[0], prop)89 }90 arrayTraps.set = function(state, prop, value) {91- if (prop !== "length" && isNaN(parseInt(prop))) {92- throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore93- }94- return objectTraps.set.call(this, state[0], prop, value)91+ if (prop !== "length" && isNaN(parseInt(prop))) {92+ throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore93+ }94+ return objectTraps.set.call(this, state[0], prop, value)95 }96 97 // returns the object we should be reading the current value from, which is base, until some change has been made98 function source(state) {99- return state.copy || state.base99+ return state.copy || state.base100 }101 102 // Access a property without creating an Immer draft.103 function peek(draft, prop) {104- const state = draft[DRAFT_STATE]105- const desc = Reflect.getOwnPropertyDescriptor(106- state ? source(state) : draft,107- prop108- )109- return desc && desc.value104+ const state = draft[DRAFT_STATE]105+ const desc = Reflect.getOwnPropertyDescriptor(106+ state ? source(state) : draft,107+ prop108+ )109+ return desc && desc.value110 }111 112 function get(state, prop) {113- if (prop === DRAFT_STATE) return state114- let {drafts} = state113+ if (prop === DRAFT_STATE) return state114+ let {drafts} = state115 116- // Check for existing draft in unmodified state.117- if (!state.modified && has(drafts, prop)) {118- return drafts[prop]119- }116+ // Check for existing draft in unmodified state.117+ if (!state.modified && has(drafts, prop)) {118+ return drafts[prop]119+ }120 121- const value = source(state)[prop]122- if (state.finalized || !isDraftable(value)) {123- return value124- }121+ const value = source(state)[prop]122+ if (state.finalized || !isDraftable(value)) {123+ return value124+ }125 126- // Check for existing draft in modified state.127- if (state.modified) {128- // Assigned values are never drafted. This catches any drafts we created, too.129- if (value !== peek(state.base, prop)) return value130- // Store drafts on the copy (when one exists).131- drafts = state.copy132- }126+ // Check for existing draft in modified state.127+ if (state.modified) {128+ // Assigned values are never drafted. This catches any drafts we created, too.129+ if (value !== peek(state.base, prop)) return value130+ // Store drafts on the copy (when one exists).131+ drafts = state.copy132+ }133 134- return (drafts[prop] = createProxy(value, state))134+ return (drafts[prop] = createProxy(value, state))135 }136 137 function set(state, prop, value) {138- if (!state.modified) {139- const baseValue = peek(state.base, prop)140- // Optimize based on value's truthiness. Truthy values are guaranteed to141- // never be undefined, so we can avoid the `in` operator. Lastly, truthy142- // values may be drafts, but falsy values are never drafts.143- const isUnchanged = value144- ? is(baseValue, value) || value === state.drafts[prop]145- : is(baseValue, value) && prop in state.base146- if (isUnchanged) return true147- markChanged(state)148- }149- state.assigned[prop] = true150- state.copy[prop] = value151- return true138+ if (!state.modified) {139+ const baseValue = peek(state.base, prop)140+ // Optimize based on value's truthiness. Truthy values are guaranteed to141+ // never be undefined, so we can avoid the `in` operator. Lastly, truthy142+ // values may be drafts, but falsy values are never drafts.143+ const isUnchanged = value144+ ? is(baseValue, value) || value === state.drafts[prop]145+ : is(baseValue, value) && prop in state.base146+ if (isUnchanged) return true147+ markChanged(state)148+ }149+ state.assigned[prop] = true150+ state.copy[prop] = value151+ return true152 }153 154 function deleteProperty(state, prop) {155- // The `undefined` check is a fast path for pre-existing keys.156- if (peek(state.base, prop) !== undefined || prop in state.base) {157- state.assigned[prop] = false158- markChanged(state)159- }160- if (state.copy) delete state.copy[prop]161- return true155+ // The `undefined` check is a fast path for pre-existing keys.156+ if (peek(state.base, prop) !== undefined || prop in state.base) {157+ state.assigned[prop] = false158+ markChanged(state)159+ }160+ if (state.copy) delete state.copy[prop]161+ return true162 }163 164 // Note: We never coerce `desc.value` into an Immer draft, because we can't make165 // the same guarantee in ES5 mode.166 function getOwnPropertyDescriptor(state, prop) {167- const owner = source(state)168- const desc = Reflect.getOwnPropertyDescriptor(owner, prop)169- if (desc) {170- desc.writable = true171- desc.configurable = !Array.isArray(owner) || prop !== "length"172- }173- return desc167+ const owner = source(state)168+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop)169+ if (desc) {170+ desc.writable = true171+ desc.configurable = !Array.isArray(owner) || prop !== "length"172+ }173+ return desc174 }175 176 function markChanged(state) {177- if (!state.modified) {178- state.modified = true179- state.copy = assign(shallowCopy(state.base), state.drafts)180- state.drafts = null181- if (state.parent) markChanged(state.parent)182- }177+ if (!state.modified) {178+ state.modified = true179+ state.copy = assign(shallowCopy(state.base), state.drafts)180+ state.drafts = null181+ if (state.parent) markChanged(state.parent)182+ }183 }modified:src/scope.js+28 added-28 removed
1 import {DRAFT_STATE} from "./common"2 3 /** Each scope represents a `produce` call. */4 export class ImmerScope {5- constructor(parent) {6- this.drafts = []7- this.parent = parent5+ constructor(parent) {6+ this.drafts = []7+ this.parent = parent8 9- // 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 = true12 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- }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 }34 35 ImmerScope.current = null36 ImmerScope.enter = function() {37- return (this.current = new ImmerScope(this.current))37+ return (this.current = new ImmerScope(this.current))38 }39 40 function revoke(draft) {41- draft[DRAFT_STATE].revoke()41+ draft[DRAFT_STATE].revoke()42 }modified:.prettierrc+1 added-2 removed
3 unmodified lines4 "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": {6 unmodified lines