Added support for frozen trees, and automatically freeze generated trees
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent e4ca0d6 · Browse files · 6 files·+170 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+170 added−51 removed
- tests:+87 added−36 removed
- other:+83 added−15 removed
Provenance
- Commit
ab8987f- Tree
0b65771- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
e4ca0d6
6 files changed+170 added−51 removed
modified:__tests__/base.js+2 added-36 removed
1+"use strict"2 import immer from ".."3 4 describe("base", () => {5 let baseState121 unmodified lines127 })128 129 it("reusing object should work", () => {130 const nextState = immer(baseState, s => {130- debugger131 const obj = s.anObject132 delete s.anObject133 s.messy = obj134 })39 unmodified lines174 const nextState = immer(baseState, s => {175 s.aProp = undefined176 })177 expect(nextState).not.toBe(baseState)178- expect(baseState.aProp).toBe('hi')178+ expect(baseState.aProp).toBe("hi")179 expect(nextState.aProp).toBe(undefined)180 })181 182 afterEach(() => {13 unmodified lines196 }197 }198 }199 })200-201-describe("readme example", () => {202- it("works", () => {203- const baseState = [204- {205- todo: "Learn typescript",206- done: true207- },208- {209- todo: "Try immer",210- done: false211- }212- ]213-214- const nextState = immer(baseState, state => {215- state.push({ todo: "Tweet about it" })216- state[1].done = true217- })218-219- // the new item is only added to the next state,220- // base state is unmodified221- expect(baseState.length).toBe(2)222- expect(nextState.length).toBe(3)223-224- // same for the changed 'done' prop225- expect(baseState[1].done).toBe(false)226- expect(nextState[1].done).toBe(true)227-228- // unchanged data is structurally shared229- expect(nextState[0]).toBe(baseState[0])230- // changed data not (dûh)231- expect(nextState[1]).not.toBe(baseState[1])232- })233-})added:__tests__/frozen.js+49 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"use strict"import immer from ".."
describe("auto freeze", () => { const baseState = { object: { a: 1 }, array: [1, 2] }
it("should freeze objects after modifications", () => { expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen const next = immer(baseState, draft => { draft.object.c = 2 }) expect(Object.isFrozen(next.object)).toBe(true) expect(Object.isFrozen(next)).toBe(true)
expect(() => { next.object.a = 2 }).toThrow(/Cannot assign to read only property/) })
it("should freeze arrays after modifications", () => { expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen const next = immer(baseState, draft => { draft.array.push(3) }) 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(/Cannot add\/remove sealed array elements/) })
it("can handle already frozen trees", () => { const a = [] const b = { a: a } Object.freeze(a) Object.freeze(b) const n = immer(b, draft => { draft.c = true draft.a.push(3) debugger }) expect(n).toEqual({ c: true, a: [3] }) })})added:__tests__/readme.js+36 added
123456789101112131415161718192021222324252627282930313233343536"use strict"import immer from ".."
describe("readme example", () => { it("works", () => { const baseState = [ { todo: "Learn typescript", done: true }, { todo: "Try immer", done: false } ]
const nextState = immer(baseState, draft => { draft.push({ todo: "Tweet about it" }) draft[1].done = true })
// the new item is only added to the next state, // base state is unmodified expect(baseState.length).toBe(2) expect(nextState.length).toBe(3)
// same for the changed 'done' prop expect(baseState[1].done).toBe(false) expect(nextState[1].done).toBe(true)
// unchanged data is structurally shared expect(nextState[0]).toBe(baseState[0]) // changed data not (dûh) expect(nextState[1]).not.toBe(baseState[1]) })})modified:immer.js+58 added-13 removed
1+"use strict"2 // @ts-check3 3-const isProxySymbol = Symbol("immer-proxy")4+const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version5 6+// This property indicates that the current object is cloned for another object,7+// to make sure the proxy of a frozen object is writeable8+const CLONE_TARGET = Symbol("immer-clone-target")9+10+let autoFreeze = true11+12 /**13 * Immer takes a state, and runs a function against it.14 * That function can freely mutate the state, as it will create copies-on-write.15 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned10 unmodified lines26 const copies = new Map()27 28 const objectTraps = {29 get(target, prop) {23- if (prop === isProxySymbol) return target30+ if (prop === IMMER_PROXY) return target31 return createProxy(getCurrentSource(target)[prop])32 },33 has(target, prop) {34 return prop in getCurrentSource(target)5 unmodified lines40 const current = createProxy(getCurrentSource(target)[prop])41 const newValue = createProxy(value)42 if (current !== newValue) {43 const copy = getOrCreateCopy(target)37- copy[prop] = isProxy(newValue) ? newValue[isProxySymbol] : newValue44+ copy[prop] = isProxy(newValue) ? newValue[IMMER_PROXY] : newValue45 }46 return true47 },48 deleteProperty(target, property) {5 unmodified lines54 55 // creates a copy for a base object if there ain't one56 function getOrCreateCopy(base) {57 let copy = copies.get(base)51- if (!copy) {52- copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)53- copies.set(base, copy)58+ if (copy) return copy59+ const cloneTarget = base[CLONE_TARGET]60+ if (cloneTarget) {61+ // base is a clone already (source was frozen), no need to create addtional copy62+ copies.set(cloneTarget, base)63+ return base64 }65+ // create a fresh copy66+ copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)67+ copies.set(base, copy)68 return copy69 }70 71 // returns the current source of truth for a base object6 unmodified lines78 function createProxy(base) {79 if (isPlainObject(base) || Array.isArray(base)) {80 if (isProxy(base)) return base // avoid double wrapping81 if (proxies.has(base)) return proxies.get(base)82+ let proxyTarget = base83+ // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.84+ if (Object.isFrozen(proxyTarget)) {85+ proxyTarget = Array.isArray(proxyTarget) ? proxyTarget.slice() : { ...proxyTarget }86+ Object.defineProperty(proxyTarget, CLONE_TARGET, {87+ enumerable: false,88+ value: base,89+ configurable: true90+ })91+ }92+ // create the proxy69- const proxy = new Proxy(base, objectTraps)93+ const proxy = new Proxy(proxyTarget, objectTraps)94 proxies.set(base, proxy)95 return proxy96 }97 return base22 unmodified lines120 }121 122 function finalizeObject(thing) {123 if (!hasChanges(thing)) return thing100- const copy = getOrCreateCopy(thing)124+ const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..125 Object.keys(copy).forEach(prop => {126 copy[prop] = finalize(copy[prop])127 })104- return copy128+ delete copy[CLONE_TARGET]129+ return freeze(copy)130 }131 132 function finalizeArray(thing) {133 if (!hasChanges(thing)) return thing109- const copy = getOrCreateCopy(thing)134+ const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..135 copy.forEach((value, index) => {136 copy[index] = finalize(copy[index])137 })113- return copy138+ delete copy[CLONE_TARGET]139+ return freeze(copy)140 }141 142 // create proxy for root143 const rootClone = createProxy(baseState)9 unmodified lines153 return proto === Object.prototype || proto === null154 }155 156 function isProxy(value) {131- return !!value && !!value[isProxySymbol]157+ return !!value && !!value[IMMER_PROXY]158 }159 160+function freeze(value) {161+ if (autoFreeze) {162+ Object.freeze(value)163+ }164+ return value165+}166+167+/**168+ * Automatically freezes any state trees generated by immer.169+ * This protects against accidental modifications of the state tree outside of an immer function.170+ * This comes with a performance impact, so it is recommended to disable this option in production.171+ * It is by default enabled.172+ */173+function setAutoFreeze(enableAutoFreeze) {174+ autoFreeze = enableAutoFreeze175+}176+177+module.exports.__esModule = true134-module.exports = immer178+module.exports.default = immer179+module.exports.setAutoFreeze = setAutoFreezemodified:index.d.ts+10 added-2 removed
123455678910101112131415161718/** * Immer takes a state, and runs a function against it. * That function can freely mutate the state, as it will create copies-on-write. * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned * * * @param currentState - the state to start with * @param thunk - function that receives a proxy of the current state as first argument and which can be freely modified * @returns The next state: a new state, or the current state if nothing was modified */export function immer<S = any>(currentState: S, thunk: (draftState: S) => void): S;export function immer<S = any>(currentState: S, thunk: (draftState: S) => void): S
/** * Automatically freezes any state trees generated by immer. * This protects against accidental modifications of the state tree outside of an immer function. * This comes with a performance impact, so it is recommended to disable this option in production. * It is by default enabled. */export function setAutoFreeze(autoFreeze: boolean)modified:readme.md+15 added
66 unmodified lines67 * Deep updates are trivial68 * Small, dependency free library with minimal api surface69 * No accidental mutations of current state, but intentional mutations of a draft state70 71+## Auto freezing72+73+ Immer automatically freezes any state trees that are modified using `immer.74+ This protects against accidental modifications of the state tree outside of an immer function.75+ This comes with a performance impact, so it is recommended to disable this option in production.76+ It is by default enabled.77+78+ Use `setAutoFreeze(true / false)` to turn this feature on or off.79+80 ## Reducer Example81 82 A lot of words; here is a simple example of what difference that could make in practice.83 The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)78 unmodified lines162 * Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before optimize!), do the current state analysis before entering the `immer` block or read form the `currentState` rather than the `draftState`163 164 ## Changelog165 166+### 0.0.5167+168+* Fixed `immer` function export, it is now properly exposed as `default`169+* Immer now automatically freezes any state modifications made. Turn this is using `setAutoFreeze(false)`170+* Added support for frozen state trees in strict mode.171+172 ### 0.0.4 (31-12-2017)173 174 * Added typescript typings [#11](https://github.com/mweststrate/immer/pull/11) by [@benbraou](https://github.com/benbraou)175 * Fixed bug when setting properties to `undefined`. Fixes [#12](https://github.com/mweststrate/immer/issues/12) through [#13](https://github.com/mweststrate/immer/pull/13) by [@benbraou](https://github.com/benbraou)