Merge remote-tracking branch 'origin/v1.8'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parents 8e7b371, f12a7a8 · Browse files · 9 files·+283 added−62 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+283 added−62 removed
- tests:+246 added−48 removed
- other:+37 added−14 removed
Provenance
- Commit
7790417- Tree
24a5a0e- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent 1
8e7b371- Parent 2
f12a7a8
9 files changed+283 added−62 removed
modified:__tests__/base.js+145 added-17 removed
1 "use strict"2-import produce, {setAutoFreeze, setUseProxies, nothing} from "../src/immer"2+import produce, {3+ setAutoFreeze,4+ setUseProxies,5+ nothing,6+ isDraft7+} from "../src/immer"8 import deepFreeze from "deep-freeze"9 import cloneDeep from "lodash.clonedeep"10 import * as lodash from "lodash"11 886 unmodified lines898 expect(next).not.toBe(base)899 expect(next.user).toEqual(user)900 })901 897- if (freeze)898- it("should freeze new data well", () => {899- const base = {}900- const next = produce(901- base,902- draft => {903- draft.x = {y: [{z: true}]}904- },905- listener906- )907- expect(Object.isFrozen(next)).toBe(true)908- expect(Object.isFrozen(next.x)).toBe(true)909- expect(Object.isFrozen(next.x.y)).toBe(true)910- expect(Object.isFrozen(next.x.y[0].z)).toBe(true)911- })912-902 it("should structurally share identical objects in the tree", () => {903 const base = {bear: {legs: 4}, eagle: {legs: 3}}904 const next = produce(905 base,410 unmodified lines1316 expect(produce(() => nothing)({})).toBe(undefined)1317 expect(produce(() => nothing)(3)).toBe(undefined)1318 })1319 1320+ // TODO: use fuzz testing1321+ {1322+ class Foo {}1323+ const primitives = {1324+ "falsy number": 0,1325+ "truthy number": 1,1326+ "negative number": -1,1327+ infinity: 1 / 0,1328+ true: true,1329+ false: false,1330+ "empty string": "",1331+ "truthy string": "1",1332+ null: null,1333+ undefined: undefined,1334+1335+ /**1336+ * These objects are treated as primitives because Immer1337+ * chooses not to make drafts for them.1338+ */1339+ "regexp object": /.+/g,1340+ "boxed number": new Number(0),1341+ "boxed string": new String(""),1342+ "boxed boolean": new Boolean(),1343+ "date object": new Date(),1344+ "class instance": new Foo()1345+ }1346+ for (const name in primitives) {1347+ describe("base state type - " + name, () => {1348+ const value = primitives[name]1349+ it("does not create a draft", () => {1350+ produce(value, draft => {1351+ expect(draft).toBe(value)1352+ })1353+ })1354+ it("returns the same value when the producer returns undefined", () => {1355+ expect(produce(value, () => {})).toBe(value)1356+ })1357+ if (value && typeof value == "object") {1358+ it("does not return a copy when the producer makes changes", () => {1359+ expect(1360+ produce(value, draft => {1361+ draft.foo = true1362+ })1363+ ).toBe(value)1364+ })1365+ }1366+ expect(1367+ produce(value, draft => {1368+ expect(draft).toBe(value)1369+ })1370+ ).toBe(value)1371+ })1372+ }1373+ const objects = {1374+ "empty object": {},1375+ "plain object": {a: 1, b: {c: 1}},1376+ "frozen object": Object.freeze({}),1377+ "null-prototype object": Object.create(null),1378+ "empty array": [],1379+ "plain array": [1, [2, [3, []]]],1380+ "frozen array": Object.freeze([])1381+ }1382+ for (const name in objects) {1383+ describe("base state type - " + name, () => {1384+ const value = objects[name]1385+ it("returns a copy when changes are made", () => {1386+ const random = Math.random()1387+ const result = produce(value, draft => {1388+ if (Array.isArray(value)) {1389+ draft.push(random)1390+ } else {1391+ draft[random] = true1392+ }1393+ })1394+ expect(result).not.toBe(value)1395+ expect(result.constructor).toBe(value.constructor)1396+ if (Array.isArray(value)) {1397+ expect(result[result.length - 1]).toBe(random)1398+ } else {1399+ expect(result[random]).toBe(true)1400+ }1401+ })1402+ it("should ", () => {})1403+ expect(1404+ produce(value, draft => {1405+ expect(draft).not.toBe(value)1406+ expect(value).toEqual(draft)1407+ })1408+ ).toBe(value)1409+ })1410+ }1411+ }1412+1413 afterEach(() => {1414 expect(baseState).toBe(origBaseState)1415 expect(baseState).toEqual(createBaseState())1416 })11 unmodified lines1428 }1429 return freeze ? deepFreeze(data) : data1430 }1431 })1432+1433+ describe(`isDraft - ${name}`, () => {1434+ beforeAll(() => {1435+ setAutoFreeze(freeze)1436+ setUseProxies(useProxies)1437+ })1438+1439+ it("returns true for object drafts", () => {1440+ produce({}, state => {1441+ expect(isDraft(state)).toBeTruthy()1442+ })1443+ })1444+ it("returns true for array drafts", () => {1445+ produce([], state => {1446+ expect(isDraft(state)).toBeTruthy()1447+ })1448+ })1449+ it("returns true for objects nested in object drafts", () => {1450+ produce({a: {b: {}}}, state => {1451+ expect(isDraft(state.a)).toBeTruthy()1452+ expect(isDraft(state.a.b)).toBeTruthy()1453+ })1454+ })1455+ it("returns false for new objects added to a draft", () => {1456+ produce({}, state => {1457+ state.a = {}1458+ expect(isDraft(state.a)).toBeFalsy()1459+ })1460+ })1461+ it("returns false for objects returned by the producer", () => {1462+ const object = produce(null, Object.create)1463+ expect(isDraft(object)).toBeFalsy()1464+ })1465+ it("returns false for arrays returned by the producer", () => {1466+ const array = produce(null, _ => [])1467+ expect(isDraft(array)).toBeFalsy()1468+ })1469+ it("returns false for object drafts returned by the producer", () => {1470+ const object = produce({}, state => state)1471+ expect(isDraft(object)).toBeFalsy()1472+ })1473+ it("returns false for array drafts returned by the producer", () => {1474+ const array = produce([], state => state)1475+ expect(isDraft(array)).toBeFalsy()1476+ })1477+ })1478 }1479 1480 function enumerableOnly(x) {1481 // this can be done better...2 unmodified linesmodified:__tests__/curry.js-3 removed
8 unmodified lines91011121314151314151663 unmodified lines8 unmodified lines setUseProxies(useProxies)
it("should check arguments", () => { expect(() => produce()).toThrow(/produce expects 1 to 3 arguments/) expect(() => produce(new Buffer(""), () => {})).toThrow( /the first argument to an immer producer should be a primitive, plain object or array/ ) expect(() => produce({}, () => {}, [])).toThrow( /third argument of a producer/ ) expect(() => produce({}, {})).toThrow(/should be a function/)63 unmodified linesmodified:__tests__/frozen.js+101 added-28 removed
122345678910111213131415161415161718192021222324181920212526272829232425303132332728293435363738394041424344454647484950515253543233343555565758596061373839624142434445466364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212311 unmodified lines"use strict"import deepFreeze from "deep-freeze"import produce, {setUseProxies, setAutoFreeze} from "../src/immer"
const {isFrozen} = Object
runTests("proxy", true)runTests("es5", false)
function runTests(name, useProxies) { describe("auto freeze - " + name, () => { setUseProxies(useProxies) setAutoFreeze(true)
const baseState = { object: {a: 1}, array: [1, 2] } it("never freezes the base state", () => { const base = {arr: [1], obj: {a: 1}} const next = produce(base, draft => { draft.arr.push(1) }) expect(isFrozen(base)).toBeFalsy() expect(isFrozen(base.arr)).toBeFalsy() expect(isFrozen(next)).toBeTruthy() expect(isFrozen(next.arr)).toBeTruthy() })
it("should freeze objects after modifications", () => { expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen const next = produce(baseState, draft => { draft.object.c = 2 it("never freezes reused state", () => { const base = {arr: [1], obj: {a: 1}} const next = produce(base, draft => { draft.arr.push(1) }) expect(Object.isFrozen(next.object)).toBe(true) expect(Object.isFrozen(next)).toBe(true) expect(Object.isFrozen(next.array)).toBe(false) expect(next.obj).toBe(base.obj) expect(isFrozen(next.obj)).toBeFalsy() })
expect(() => { next.object.a = 2 }).toThrow(/Cannot assign to read only property/) describe("the result is always auto-frozen when", () => { it("the root draft is mutated (and no error is thrown)", () => { const base = {} const next = produce(base, draft => { draft.a = 1 }) expect(next).not.toBe(base) expect(isFrozen(next)).toBeTruthy() })
it("a nested draft is mutated (and no error is thrown)", () => { const base = {a: {}} const next = produce(base, draft => { draft.a.b = 1 }) expect(next).not.toBe(base) expect(isFrozen(next)).toBeTruthy() expect(isFrozen(next.a)).toBeTruthy() }) })
it("should freeze arrays after modifications", () => { expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen const next = produce(baseState, draft => { draft.array.push(3) describe("the result is never auto-frozen when", () => { it("the producer is a no-op", () => { const base = {} const next = produce(base, () => {}) expect(next).toBe(base) expect(isFrozen(next)).toBeFalsy() }) expect(Object.isFrozen(next.object)).toBe(false) // not touched expect(Object.isFrozen(next)).toBe(true) expect(Object.isFrozen(next.array)).toBe(true)
expect(() => { next.array.shift() }).toThrow( // Exception message for older / newer Node.js version. /Cannot add\/remove sealed array elements|Cannot assign to read only property '0' of object '\[object Array\]'/ ) it("the root draft is returned", () => { const base = {} const next = produce(base, draft => draft) expect(next).toBe(base) expect(isFrozen(next)).toBeFalsy() })
it("a nested draft is returned", () => { const base = {a: {}} const next = produce(base, draft => draft.a) expect(next).toBe(base.a) expect(isFrozen(next)).toBeFalsy() })
it("the base state is returned", () => { const base = {} const next = produce(base, () => base) expect(next).toBe(base) expect(isFrozen(next)).toBeFalsy() })
it("a new object replaces a primitive base", () => { const obj = {} const next = produce(null, () => obj) expect(next).toBe(obj) expect(isFrozen(next)).toBeFalsy() })
it("a new object replaces the entire draft", () => { const obj = {a: {b: {}}} const next = produce({}, () => obj) expect(next).toBe(obj) expect(isFrozen(next)).toBeFalsy() expect(isFrozen(next.a)).toBeFalsy() expect(isFrozen(next.a.b)).toBeFalsy() })
it("a new object is added to the root draft", () => { const base = {} const next = produce(base, draft => { draft.a = {} }) expect(next).not.toBe(base) expect(isFrozen(next)).toBeTruthy() expect(isFrozen(next.a)).toBeFalsy() })
it("a new object is added to a nested draft", () => { const base = {a: {}} const next = produce(base, draft => { draft.a.b = {} }) expect(next).not.toBe(base) expect(isFrozen(next)).toBeTruthy() expect(isFrozen(next.a)).toBeTruthy() expect(isFrozen(next.a.b)).toBeFalsy() }) })
it("can handle already frozen trees", () => { const a = []11 unmodified linesmodified:src/common.js-2 removed
154 unmodified lines155 if (isProxy(child)) {156 parent[i] = finalize(child)157 } else finalizeNonProxiedObject(child)158 })159- // always freeze completely new data160- freeze(parent)159 }160 161 export function is(x, y) {162 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js6 unmodified linesmodified:src/immer.d.ts+2 added
159 unmodified lines160 161 export function applyPatches<S>(state: S, patches: Patch[]): S162 163 export function original<T>(value: T): T | void164+165+export function isDraft(value: any): booleanmodified:src/immer.js+8 added-7 removed
1-export {setAutoFreeze, setUseProxies, original} from "./common"1+export {2+ setAutoFreeze,3+ setUseProxies,4+ original,5+ isProxy as isDraft6+} from "./common"7 8 import {applyPatches as applyPatchesImpl} from "./patches"9 import {isProxyable, getUseProxies, NOTHING} from "./common"10 import {produceProxy} from "./proxy"31 unmodified lines42 if (typeof producer !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")43 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")44 }45 41- // if state is a primitive, don't bother proxying at all42- if (typeof baseState !== "object" || baseState === null) {46+ // avoid proxying anything except plain objects and arrays47+ if (!isProxyable(baseState)) {48 const returnValue = producer(baseState)49 return returnValue === undefined50 ? baseState51 : normalizeResult(returnValue)52 }53 49- if (!isProxyable(baseState))50- throw new Error(51- `the first argument to an immer producer should be a primitive, plain object or array, got ${typeof baseState}: "${baseState}"`52- )54 return normalizeResult(55 getUseProxies()56 ? produceProxy(baseState, producer, patchListener)57 : produceEs5(baseState, producer, patchListener)12 unmodified linesmodified:src/immer.js.flow+3 added-1 removed
85 unmodified lines86 declare export function setUseProxies(useProxies: boolean): void87 88 declare export function applyPatches<S>(state: S, patches: Patch[]): S89 90-declare export function original<S>(value: S): ?S90+declare export function original<S>(value: S): ?S91+92+declare export function isDraft(value: any): booleanmodified:changelog.md+10 added-4 removed
1 # Changelog2 3-### 1.7.4 (28-Oct-2018)3+### 1.8.0 (19-Nov-2018)4 5-- improve `Draft<T>` type for TypeScript users ([see here](https://github.com/mweststrate/immer/commit/512256bbde4ea1e2b6a75399d6ad59925752ad6b))6-- remove unused function7-- better test coverage5+* Introduce the `isDraft` function to check if a value is a proxy created by Immer.6+* Several minor code & performance improvements [#249](https://github.com/mweststrate/immer/pull/249) [#237](https://github.com/mweststrate/immer/pull/237)7+* Functions are now also acceptable as primitive base state, see [#236](https://github.com/mweststrate/immer/pull/236) [#233](https://github.com/mweststrate/immer/pull/233)8+* Improved test coverage [#250](https://github.com/mweststrate/immer/pull/250)9 10+Credits for this release go to [@aleclarson](https://github.com/aleclarson), who made all these improvements!11+12 ### 1.7.3 (24-Oct-2018)13 14+- improve `Draft<T>` type for TypeScript users ([see here](https://github.com/mweststrate/immer/commit/512256bbde4ea1e2b6a75399d6ad59925752ad6b))15+- remove unused function16+- better test coverage17 - Use proxies only if both `Proxy` and `Reflect` global APIs exist (fixes [#226](https://github.com/mweststrate/immer/issues/226))18 19 ### 1.7.2 (20-Sep-2018)20 184 unmodified linesmodified:readme.md+14 added
432 unmodified lines433 original(draftState.users) // is === baseState.users434 })435 ```436 437+Just want to know if a value is a proxied instance? Use the `isDraft` function!438+439+```js440+import { isDraft } from "immer";441+442+const baseState = { users: [{ name: "Bobby" }] };443+const nextState = produce(baseState, draft => {444+ isDraft(draft) // => true445+ isDraft(draft.users) // => true446+ isDraft(draft.users[0]) // => true447+})448+isDraft(nextState) // => false449+```450+451 ## Using `this`452 453 The recipe will be always invoked with the `draft` as `this` context.454 266 unmodified lines