Skip to content
Myr

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

6 files+170 added−51 removed

modified:__tests__/base.js+2 added-36 removed
1"use strict"2import immer from ".."34describe("base", () => {5 let baseState
121 unmodified lines
127 })128129 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 lines
174 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 })181182 afterEach(() => {
13 unmodified lines
196 }197 }198 }199})200201describe("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 ]213214 const nextState = immer(baseState, state => {215 state.push({ todo: "Tweet about it" })216 state[1].done = true217 })218219 // 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)223224 // same for the changed 'done' prop225 expect(baseState[1].done).toBe(false)226 expect(nextState[1].done).toBe(true)227228 // 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
added:__tests__/readme.js+36 added
modified:immer.js+58 added-13 removed
1"use strict"2// @ts-check33const isProxySymbol = Symbol("immer-proxy")4const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version56// This property indicates that the current object is cloned for another object,7// to make sure the proxy of a frozen object is writeable8const CLONE_TARGET = Symbol("immer-clone-target")910let autoFreeze = true1112/**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 returned
10 unmodified lines
26 const copies = new Map()2728 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 lines
40 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 lines
5455 // 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 }7071 // returns the current source of truth for a base object
6 unmodified lines
78 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 base
22 unmodified lines
120 }121122 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 }131132 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 }141142 // create proxy for root143 const rootClone = createProxy(baseState)
9 unmodified lines
153 return proto === Object.prototype || proto === null154}155156function isProxy(value) {131 return !!value && !!value[isProxySymbol]157 return !!value && !!value[IMMER_PROXY]158}159160function freeze(value) {161 if (autoFreeze) {162 Object.freeze(value)163 }164 return value165}166167/**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 */173function setAutoFreeze(enableAutoFreeze) {174 autoFreeze = enableAutoFreeze175}176177module.exports.__esModule = true134module.exports = immer178module.exports.default = immer179module.exports.setAutoFreeze = setAutoFreeze
modified:index.d.ts+10 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 what difference that 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 optimize!), do the current state analysis before entering the `immer` block or read form 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)