Merge pull request #15 from mweststrate/feature/freeze
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Added support for frozen trees, and automatically freeze generated trees
authored by Michel Weststrate · committed by GitHub · parents e775cca, 84905e7 · Browse files · 6 files·+188 added−60 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+188 added−60 removed
- tests:+88 added−38 removed
- other:+100 added−22 removed
Provenance
- Commit
0d24494- Tree
abd6ea1- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
e775cca- Parent 2
84905e7
6 files changed+188 added−60 removed
modified:__tests__/base.js+3 added-38 removed
1+"use strict"2 import immer from ".."3 4 describe("base", () => {5 let baseState131 unmodified lines137 })138 139 it("reusing object should work", () => {140 const nextState = immer(baseState, s => {140- debugger141 const obj = s.anObject142 delete s.anObject143 s.messy = obj144 })58 unmodified lines203 proxy.aProp = "Hallo"204 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)205 expect(() => {206 const aProp = proxy.aProp207- }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/) 207+ }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)208 209 expect(nextState).not.toBe(baseState)210 expect(baseState.aProp).toBe("hi")211 expect(nextState.aProp).toBe("hello")212-212 })214- 213+214 afterEach(() => {215 expect(baseState).toBe(origBaseState)216 expect(baseState).toEqual(createBaseState())217 })10 unmodified lines228 },229 }230 }231 })233-234-describe("readme example", () => {235- it("works", () => {236- const baseState = [237- {238- todo: "Learn typescript",239- done: true,240- },241- {242- todo: "Try immer",243- done: false,244- },245- ]246-247- const nextState = immer(baseState, state => {248- state.push({todo: "Tweet about it"})249- state[1].done = true250- })251-252- // the new item is only added to the next state,253- // base state is unmodified254- expect(baseState.length).toBe(2)255- expect(nextState.length).toBe(3)256-257- // same for the changed 'done' prop258- expect(baseState[1].done).toBe(false)259- expect(nextState[1].done).toBe(true)260-261- // unchanged data is structurally shared262- expect(nextState[0]).toBe(baseState[0])263- // changed data not (dûh)264- expect(nextState[1]).not.toBe(baseState[1])265- })266-})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(Object.isFrozen(next.array)).toBe(false)
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) }) 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+72 added-20 removed
1+"use strict"2+// @ts-check3+4 /**5 * @typedef {Object} RevocableProxy6 * @property {any} proxy7 * @property {Function} revoke8 */9 7-// @ts-check10+const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version11 9-const isProxySymbol = Symbol("immer-proxy")12+// This property indicates that the current object is cloned for another object,13+// to make sure the proxy of a frozen object is writeable14+const CLONE_TARGET = Symbol("immer-clone-target")15 16+let autoFreeze = true17+18 /**19 * Immer takes a state, and runs a function against it.20 * That function can freely mutate the state, as it will create copies-on-write.21 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned3 unmodified lines25 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified26 * @returns {any} a new state, or the base state if nothing was modified27 */28 function immer(baseState, thunk) {22-29 /**30 * Maps baseState objects to revocable proxies31 * @type {Map<Object,RevocableProxy>}32 */3 unmodified lines36 const copies = new Map()37 38 const objectTraps = {39 get(target, prop) {34- if (prop === isProxySymbol) return target40+ if (prop === IMMER_PROXY) return target41 return createProxy(getCurrentSource(target)[prop])42 },43 has(target, prop) {44 return prop in getCurrentSource(target)6 unmodified lines51 const newValue = createProxy(value)52 if (current !== newValue) {53 const copy = getOrCreateCopy(target)54 copy[prop] = isProxy(newValue)49- ? newValue[isProxySymbol]55+ ? newValue[IMMER_PROXY]56 : newValue57 }58 return true59 },6 unmodified lines66 67 // creates a copy for a base object if there ain't one68 function getOrCreateCopy(base) {69 let copy = copies.get(base)64- if (!copy) {65- copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)66- copies.set(base, copy)70+ if (copy) return copy71+ const cloneTarget = base[CLONE_TARGET]72+ if (cloneTarget) {73+ // base is a clone already (source was frozen), no need to create addtional copy74+ copies.set(cloneTarget, base)75+ return base76 }77+ // create a fresh copy78+ copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)79+ copies.set(base, copy)80 return copy81 }82 83 // returns the current source of truth for a base object84 function getCurrentSource(base) {85 const copy = copies.get(base)86 return copy || base87 }76- 88+89 // creates a proxy for plain objects / arrays90 function createProxy(base) {91 if (isPlainObject(base) || Array.isArray(base)) {92 if (isProxy(base)) return base // avoid double wrapping81- if (revocableProxies.has(base)) return revocableProxies.get(base).proxy82- //const proxy = new Proxy(base, objectTraps)83- const revocableProxy = Proxy.revocable(base, objectTraps)93+ if (revocableProxies.has(base))94+ return revocableProxies.get(base).proxy95+ let proxyTarget96+ // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.97+ if (Object.isFrozen(base)) {98+ proxyTarget = Array.isArray(base)99+ ? base.slice()100+ : Object.assign({}, base)101+ Object.defineProperty(proxyTarget, CLONE_TARGET, {102+ enumerable: false,103+ value: base,104+ configurable: true,105+ })106+ } else {107+ proxyTarget = base108+ }109+ // create the proxy110+ const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)111 revocableProxies.set(base, revocableProxy)112 return revocableProxy.proxy113 }114 return base26 unmodified lines141 }142 143 function finalizeObject(thing) {144 if (!hasChanges(thing)) return thing118- const copy = getOrCreateCopy(thing)145+ const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..146 Object.keys(copy).forEach(prop => {147 copy[prop] = finalize(copy[prop])148 })122- return copy149+ delete copy[CLONE_TARGET]150+ return freeze(copy)151 }152 153 function finalizeArray(thing) {154 if (!hasChanges(thing)) return thing127- const copy = getOrCreateCopy(thing)155+ const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..156 copy.forEach((value, index) => {157 copy[index] = finalize(copy[index])158 })131- return copy159+ delete copy[CLONE_TARGET]160+ return freeze(copy)161 }162 163 // create proxy for root164 const rootClone = createProxy(baseState)11 unmodified lines176 }177 178 /**179 * Revoke all the proxies stored in the revocableProxies map151- * 180+ *181 * @param {Map<Object,RevocableProxy>} revocableProxies182 */154-function revoke (revocableProxies){183+function revoke(revocableProxies) {184 for (var revocableProxy of revocableProxies.values()) {185 revocableProxy.revoke()186 }187 }4 unmodified lines192 return proto === Object.prototype || proto === null193 }194 195 function isProxy(value) {167- return !!value && !!value[isProxySymbol]196+ return !!value && !!value[IMMER_PROXY]197 }198 199+function freeze(value) {200+ if (autoFreeze) {201+ Object.freeze(value)202+ }203+ return value204+}205+206+/**207+ * Automatically freezes any state trees generated by immer.208+ * This protects against accidental modifications of the state tree outside of an immer function.209+ * This comes with a performance impact, so it is recommended to disable this option in production.210+ * It is by default enabled.211+ *212+ * @returns {void}213+ */214+function setAutoFreeze(enableAutoFreeze) {215+ autoFreeze = enableAutoFreeze216+}217+218+Object.defineProperty(exports, "__esModule", {219+ value: true,220+})170-module.exports = immer221+module.exports.default = immer222+module.exports.setAutoFreeze = setAutoFreezemodified:index.d.ts+13 added-2 removed
123455678910101112131415161718192021/** * 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 default function<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 the difference that this approach 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 you optimize!), do the current state analysis before entering the `immer` block or read from 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)