Skip to content
Myr

Simplified ES5 implementation

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 875aa48 · Browse files · 2 files+96 added−73 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+96 added−73 removed

  • tests:+16 added−17 removed
  • other:+80 added−56 removed

2 files+96 added−73 removed

modified:__tests__/base.js+16 added-17 removed
7 unmodified lines
8 beforeEach(() => {9 origBaseState = baseState = createBaseState()10 })1112 it.only("should return the original without modifications", () => {13 debugger12 it("should return the original without modifications", () => {13 const nextState = immer(baseState, () => {})14 expect(nextState).toBe(baseState)15 })16
14 unmodified lines
3132 expect(warning).toHaveBeenCalledTimes(4)33 })3436 it.only("should return a copy when modifying stuff", () => {35 it("should return a copy when modifying stuff", () => {36 const nextState = immer(baseState, s => {37 s.aProp = "hello world"38 })39 expect(nextState).not.toBe(baseState)
2 unmodified lines
42 // structural sharing?43 expect(nextState.nested).toBe(baseState.nested)44 })4547 it.only("deep change bubbles up", () => {48 debugger46 it("deep change bubbles up", () => {47 const nextState = immer(baseState, s => {48 s.anObject.nested.yummie = false49 })50 expect(nextState).not.toBe(baseState)
2 unmodified lines
53 expect(nextState.anObject.nested.yummie).toBe(false)54 expect(nextState.anArray).toBe(baseState.anArray)55 })5659 it.only("can add props", () => {60 debugger57 it("can add props", () => {58 const nextState = immer(baseState, s => {59 s.anObject.cookie = {tasty: true}60 })61 expect(nextState).not.toBe(baseState)
1 unmodified line
63 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)64 expect(nextState.anObject.cookie).toEqual({tasty: true})65 })6670 it.only("can delete props", () => {67 it("can delete props", () => {68 const nextState = immer(baseState, s => {69 delete s.anObject.nested70 })71 expect(nextState).not.toBe(baseState)72 expect(nextState.anObject).not.toBe(baseState.anObject)73 expect(nextState.anObject.nested).toBe(undefined)74 })7579 it.only("ignores single non-modification", () => {76 it("ignores single non-modification", () => {77 const nextState = immer(baseState, s => {78 s.aProp = "hi"79 })80 expect(nextState).toBe(baseState)81 })8286 it.only("processes single modification", () => {83 it("processes single modification", () => {84 const nextState = immer(baseState, s => {85 s.aProp = "hello"86 s.aProp = "hi"87 })
100 unmodified lines
188 expect(baseState.aProp).toBe("hi")189 expect(nextState.aProp).toBe(undefined)190 })191192 // ES implementation does't protect against all outside modifications, just some..195 it("should revoke the proxy of the baseState after immer function is executed", () => {193 it.skip("should revoke the proxy of the baseState after immer function is executed", () => {194 let proxy195 const nextState = immer(baseState, s => {196 proxy = s197 s.aProp = "hello"
3 unmodified lines
201 expect(nextState.aProp).toBe("hello")202203 expect(() => {204 proxy.aProp = "Hallo"207 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)205 }).toThrowError(/revoked/)206 expect(() => {207 const aProp = proxy.aProp210 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)208 }).toThrowError(/revoked/)209210 expect(nextState).not.toBe(baseState)211 expect(baseState.aProp).toBe("hi")212 expect(nextState.aProp).toBe("hello")
5 unmodified lines
218 proxy = s.anObject219 })220 expect(nextState).toBe(baseState)221 expect(() => {222 // In ES5 implemenation only protects existing props, but alas..224 proxy.test = "Hallo"225 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)223 proxy.coffee = "Hallo"224 }).toThrowError(/revoked/)225 expect(() => {227 const test = proxy.test228 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)226 const test = proxy.coffee227 }).toThrowError(/revoked/)228 })229230 afterEach(() => {231 expect(baseState).toBe(origBaseState)
16 unmodified lines
modified:immer-es5.js+80 added-56 removed
11 unmodified lines
12const CHANGED_STATE = Symbol("immer-changed-state")1314let autoFreeze = true1516function proxySet(target, prop, value) {17 if (Object.is(target[prop], value)) return18 target[CHANGED_STATE] = true19 Object.defineProperty(target, prop, {20 enumerable: true,21 writable: true,22 configurable: true,23 value: value,24 })25}2616/**17 * Immer takes a state, and runs a function against it.18 * That function can freely mutate the state, as it will create copies-on-write.19 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned
9 unmodified lines
2930 // creates a proxy for plain objects / arrays31 function createProxy(base) {32 if (isPlainObject(base)) return createObjectProxy(base)44 // if (Array.isArray(base)) return createArrayProxy(base) // TODO: create Array proxy?33 if (Array.isArray(base)) return createArrayProxy(base)34 throw "Expected a plain object or array"35 }3648 function createObjectProxy(base) {37 function assertUnfinished() {38 if (finished)39 throw new Error(40 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?",41 )42 }4344 function proxySet(target, prop, value) {45 assertUnfinished()46 if (Object.is(target[prop], value)) return47 target[CHANGED_STATE] = true48 Object.defineProperty(target, prop, {49 enumerable: true,50 writable: true,51 configurable: true,52 value: value,53 })54 }5556 function createPropertyProxy(proxy, base, prop) {57 // TODO: optimize, reuse property accessors, closures etc58 Object.defineProperty(proxy, prop, {59 configurable: true,60 enumerable: true,61 get() {62 assertUnfinished()63 if (finalizing) return base[prop]64 const value = base[prop]65 if (!isPlainObject(value) && !Array.isArray(value)) return value66 const proxy = createProxy(value)67 Object.defineProperty(this, prop, {68 configurable: true,69 enumerable: true,70 get() {71 return proxy72 },73 set(value) {74 proxySet(this, prop, value)75 },76 })77 return proxy78 },79 set(value) {80 proxySet(this, prop, value)81 },82 })83 }8485 function createObjectProxy(base) {86 const proxy = {}87 createHiddenProperty(proxy, PROXY_TARGET, base)88 createHiddenProperty(proxy, CHANGED_STATE, false)53 Object.keys(base).forEach(prop => {54 Object.defineProperty(proxy, prop, {55 configurable: true,56 enumerable: true,57 get() {58 if (finished)59 throw "Cannot use proxy outside immer function"60 if (finalizing) return base[prop]61 const value = base[prop]62 if (!isPlainObject(value) && !Array.isArray(value))63 return value64 const proxy = createProxy(value)65 Object.defineProperty(this, prop, {66 configurable: true,67 enumerable: true,68 get() {69 return proxy70 },71 set(value) {72 if (finished)73 throw "Cannot use proxy outside immer function"74 proxySet(this, prop, value)75 },76 })77 return proxy78 },79 set(value) {80 if (finished)81 throw "Cannot use proxy outside immer function"82 proxySet(this, prop, value)83 },84 })85 })89 Object.keys(base).forEach(prop =>90 createPropertyProxy(proxy, base, prop),91 )92 return proxy93 }9495 function createArrayProxy(base) {96 const proxy = []97 createHiddenProperty(proxy, PROXY_TARGET, base)98 createHiddenProperty(proxy, CHANGED_STATE, false)99 for (let i = 0; i < base.length; i++)100 createPropertyProxy(proxy, base, "" + i)101 return proxy102 }103104 // checks if the given base object has modifications, either because it is modified, or105 // because one of it's children is106 function hasChanges(proxy) {107 if (!isProxy(proxy)) return false108 if (proxy[CHANGED_STATE]) return true // some property was modified109 if (isPlainObject(proxy)) return objectHasChanges(proxy)110 if (Array.isArray(proxy)) return arrayHasChanges(proxy)111 }112113 function objectHasChanges(proxy) {114 const baseKeys = Object.keys(proxy[PROXY_TARGET])115 const keys = Object.keys(proxy)116 if (!shallowEqual(baseKeys, keys)) return true117 // look deeper, this object was not modified, but maybe some of its children are118 for (let i = 0; i < keys.length; i++) {99 const value = proxy[keys[i]]100 if (hasChanges(value)) return true119 if (hasChanges(proxy[keys[i]])) return true120 }121 return false122 }123124 function arrayHasChanges(proxy) {125 const target = proxy[PROXY_TARGET]126 if (target.length !== proxy.length) return true127 // look deeper, this object was not modified, but maybe some of its children are128 for (let i = 0; i < proxy.length; i++) {129 if (hasChanges(proxy[i])) return true130 }131 return false132 }133134 // given a base object, returns it if unmodified, or return the changed cloned if modified135 function finalize(thing) {136 if (!isProxy(thing)) return thing137 if (isPlainObject(thing)) return finalizeObject(thing)
9 unmodified lines
147 })148 return freeze(res)149 }150122 function finalizeArray(thing) {123 if (!hasChanges(thing)) return thing124 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..125 copy.forEach((value, index) => {126 copy[index] = finalize(copy[index])127 })128 delete copy[CLONE_TARGET]129 return freeze(copy)151 function finalizeArray(proxy) {152 if (!hasChanges(proxy)) return proxy[PROXY_TARGET]153 return freeze(proxy.map(finalize))154 }155156 // create proxy for root157 const rootClone = createProxy(baseState)
99 unmodified lines