Skip to content
Myr

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

6 files+188 added−60 removed

modified:__tests__/base.js+3 added-38 removed
1"use strict"2import immer from ".."34describe("base", () => {5 let baseState
131 unmodified lines
137 })138139 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 lines
203 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/)208209 expect(nextState).not.toBe(baseState)210 expect(baseState.aProp).toBe("hi")211 expect(nextState.aProp).toBe("hello")212212 })214 213214 afterEach(() => {215 expect(baseState).toBe(origBaseState)216 expect(baseState).toEqual(createBaseState())217 })
10 unmodified lines
228 },229 }230 }231})233234describe("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 ]246247 const nextState = immer(baseState, state => {248 state.push({todo: "Tweet about it"})249 state[1].done = true250 })251252 // 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)256257 // same for the changed 'done' prop258 expect(baseState[1].done).toBe(false)259 expect(nextState[1].done).toBe(true)260261 // 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
added:__tests__/readme.js+36 added
modified:immer.js+72 added-20 removed
1"use strict"2// @ts-check34/**5 * @typedef {Object} RevocableProxy6 * @property {any} proxy7 * @property {Function} revoke8 */97// @ts-check10const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version119const 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 writeable14const CLONE_TARGET = Symbol("immer-clone-target")1516let autoFreeze = true1718/**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 returned
3 unmodified lines
25 * @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 */28function immer(baseState, thunk) {2229 /**30 * Maps baseState objects to revocable proxies31 * @type {Map<Object,RevocableProxy>}32 */
3 unmodified lines
36 const copies = new Map()3738 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 lines
51 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 lines
6667 // 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 }8283 // returns the current source of truth for a base object84 function getCurrentSource(base) {85 const copy = copies.get(base)86 return copy || base87 }76 8889 // 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 base
26 unmodified lines
141 }142143 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 }152153 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 }162163 // create proxy for root164 const rootClone = createProxy(baseState)
11 unmodified lines
176}177178/**179 * Revoke all the proxies stored in the revocableProxies map151 * 180 *181 * @param {Map<Object,RevocableProxy>} revocableProxies182 */154function revoke (revocableProxies){183function revoke(revocableProxies) {184 for (var revocableProxy of revocableProxies.values()) {185 revocableProxy.revoke()186 }187}
4 unmodified lines
192 return proto === Object.prototype || proto === null193}194195function isProxy(value) {167 return !!value && !!value[isProxySymbol]196 return !!value && !!value[IMMER_PROXY]197}198199function freeze(value) {200 if (autoFreeze) {201 Object.freeze(value)202 }203 return value204}205206/**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 */214function setAutoFreeze(enableAutoFreeze) {215 autoFreeze = enableAutoFreeze216}217218Object.defineProperty(exports, "__esModule", {219 value: true,220})170module.exports = immer221module.exports.default = immer222module.exports.setAutoFreeze = setAutoFreeze
modified:index.d.ts+13 added-2 removed
modified:readme.md+15 added
66 unmodified lines
67* Deep updates are trivial68* Small, dependency free library with minimal api surface69* No accidental mutations of current state, but intentional mutations of a draft state7071## Auto freezing7273 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.7778 Use `setAutoFreeze(true / false)` to turn this feature on or off.7980## Reducer Example8182A lot of words; here is a simple example of the difference that this approach could make in practice.83The 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 lines
162* 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`163164## Changelog165166### 0.0.5167168* 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.171172### 0.0.4 (31-12-2017)173174* 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)