Skip to content
Myr

Both implementation stateless

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 b7cd045 · Browse files · 1 file+193 added−190 removed
This commit

State

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

Diff stats

1 file+193 added−190 removed

  • other:+193 added−190 removed

1 file+193 added−190 removed

modified:src/es5.js+193 added-190 removed
1"use strict"2// @ts-check34const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version5const descriptors = {}67let autoFreeze = true8let states = null910function createState(parent, proxy, base) {11 return {12 modified: false,13 hasCopy: false,14 parent,15 base,16 proxy,17 copy: undefined,18 finished: false,19 finalizing: false20 }21}2223function source(state) {24 return state.hasCopy ? state.copy : state.base25}2627function get(state, prop) {28 assertUnfinished(state)29 const value = source(state)[prop]30 if (!state.finalizing && !isProxy(value) && isProxyable(value)) {31 prepareCopy(state)32 return (state.copy[prop] = createProxy(state, value))33 }34 return value35}3637function set(state, prop, value) {38 assertUnfinished(state)39 if (!state.modified) {40 if (Object.is(source(state)[prop], value)) return41 markChanged(state)42 }43 prepareCopy(state)44 state.copy[prop] = value45}4647function markChanged(state) {48 if (!state.modified) {49 state.modified = true50 if (state.parent) markChanged(state.parent)51 }52}5354function prepareCopy(state) {55 if (state.hasCopy) return56 state.hasCopy = true57 state.copy = Array.isArray(state.base)58 ? state.base.slice()59 : Object.assign({}, state.base)60}6162// creates a proxy for plain objects / arrays63function createProxy(parent, base) {64 let proxy65 if (Array.isArray(base)) proxy = createArrayProxy(base)66 else proxy = createObjectProxy(base)67 const state = createState(parent, proxy, base)68 createHiddenProperty(proxy, PROXY_STATE, state)69 states.push(state)70 return proxy71}7273function createPropertyProxy(prop) {74 return (75 descriptors[prop] ||76 (descriptors[prop] = {77 configurable: true,78 enumerable: true,79 get() {80 return get(this[PROXY_STATE], prop)81 },82 set(value) {83 set(this[PROXY_STATE], prop, value)84 }85 })86 )87}8889function createObjectProxy(base) {90 const proxy = Object.assign({}, base)91 Object.keys(base).forEach(prop =>92 Object.defineProperty(proxy, prop, createPropertyProxy(prop))93 )94 return proxy95}9697function createArrayProxy(base) {98 const proxy = new Array(base.length)99 for (let i = 0; i < base.length; i++)100 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))101 return proxy102}103104function assertUnfinished(state) {105 if (state.finished === true)106 throw new Error(107 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"108 )109}110111// this sounds very expensive, but actually it is not that extensive in practice112// as it will only visit proxies, and only do key-based change detection for objects for113// which it is not already know that they are changed (that is, only object for which no known key was changed)114function markChanges() {115 // intentionally we process the proxies in reverse order;116 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore117 // reverse order of proxy creation approximates this118 for (let i = states.length - 1; i >= 0; i--) {119 const state = states[i]120 if (state.modified === false) {121 if (Array.isArray(state.base)) {122 if (hasArrayChanges(state)) markChanged(state)123 } else if (hasObjectChanges(state)) markChanged(state)124 }125 }126}127128function hasObjectChanges(state) {129 const baseKeys = Object.keys(state.base)130 const keys = Object.keys(state.proxy)131 return !shallowEqual(baseKeys, keys)132}133134function hasArrayChanges(state) {135 return state.proxy.length !== state.base.length136}137138function finalize(proxy) {139 // TODO: almost litterally same as Proxy impl; let's reduce code duplication and rollup140 if (isProxy(proxy)) {141 const state = proxy[PROXY_STATE]142 if (state.modified === true) {143 if (Array.isArray(state.base)) return finalizeArray(proxy, state)144 return finalizeObject(proxy, state)145 } else return state.base146 } else if (proxy !== null && typeof proxy === "object") {147 // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original148 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well149 if (Array.isArray(proxy)) {150 for (let i = 0; i < proxy.length; i++) proxy[i] = finalize(proxy[i])151 return freeze(proxy)152 }153 const proto = Object.getPrototypeOf(proxy)154 if (proto === null || proto === Object.prototype) {155 for (let key in proxy) proxy[key] = finalize(proxy[key])156 return freeze(proxy)157 }158 }159 return proxy160}161162function finalizeObject(proxy, state) {163 const res = Object.assign({}, proxy)164 const base = state.base165 for (let prop in res) {166 if (proxy[prop] !== base[prop]) res[prop] = finalize(res[prop])167 }168 return freeze(res)169}170171function finalizeArray(proxy, state) {172 const res = proxy.slice()173 const base = state.base174 for (let i = 0; i < res.length; i++) {175 if (res[i] !== base[i]) res[i] = finalize(res[i])176 }177 return freeze(res)178}179180/**181 * Immer takes a state, and runs a function against it.182 * That function can freely mutate the state, as it will create copies-on-write.183 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned
24 unmodified lines
208 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))209 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")210 }21140 let finalizing = false41 let finished = false42 const descriptors = {}43 const states = []4445 function createState(parent, proxy, base) {46 return {47 modified: false,48 hasCopy: false,49 parent,50 base,51 proxy,52 copy: undefined53 }54 }5556 function source(state) {57 return state.hasCopy ? state.copy : state.base58 }5960 function get(state, prop) {61 assertUnfinished(state)62 const value = source(state)[prop]63 if (!finalizing && !isProxy(value) && isProxyable(value)) {64 prepareCopy(state)65 return (state.copy[prop] = createProxy(state, value))66 }67 return value68 }6970 function set(state, prop, value) {71 assertUnfinished()72 if (!state.modified) {73 if (Object.is(source(state)[prop], value)) return74 markChanged(state)75 }76 prepareCopy(state)77 state.copy[prop] = value78 }7980 function markChanged(state) {81 if (!state.modified) {82 state.modified = true83 if (state.parent) markChanged(state.parent)84 }85 }8687 function prepareCopy(state) {88 if (state.hasCopy) return89 state.hasCopy = true90 state.copy = Array.isArray(state.base)91 ? state.base.slice()92 : Object.assign({}, state.base)93 }9495 // creates a proxy for plain objects / arrays96 function createProxy(parent, base) {97 let proxy98 if (Array.isArray(base)) proxy = createArrayProxy(base)99 else proxy = createObjectProxy(base)100 const state = createState(parent, proxy, base)101 createHiddenProperty(proxy, PROXY_STATE, state)102 states.push(state)103 return proxy104 }105106 function createPropertyProxy(prop) {107 return (108 descriptors[prop] ||109 (descriptors[prop] = {110 configurable: true,111 enumerable: true,112 get() {113 return get(this[PROXY_STATE], prop)114 },115 set(value) {116 set(this[PROXY_STATE], prop, value)117 }118 })119 )120 }121122 function createObjectProxy(base) {123 const proxy = Object.assign({}, base)124 Object.keys(base).forEach(prop =>125 Object.defineProperty(proxy, prop, createPropertyProxy(prop))126 )127 return proxy128 }129130 function createArrayProxy(base) {131 const proxy = new Array(base.length)132 for (let i = 0; i < base.length; i++)133 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))134 return proxy135 }136137 function assertUnfinished() {138 if (finished)139 throw new Error(140 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"212 const prevStates = states213 states = []214 try {215 // create proxy for root216 const rootClone = createProxy(undefined, baseState)217 // execute the thunk218 const maybeVoidReturn = producer(rootClone)219 //values either than undefined will trigger warning;220 !Object.is(maybeVoidReturn, undefined) &&221 console.warn(222 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`223 )224 // and finalize the modified proxy225 for (let i = 0; i < states.length; i++) states[i].finalizing = true226 // find and mark all changes (for parts not done yet)227 markChanges()228 const res = finalize(rootClone)229 // make sure all proxies become unusable230 for (let i = 0; i < states.length; i++) states[i].finished = true231 return res232 } finally {233 states = prevStates234 }143144 // this sounds very expensive, but actually it is not that extensive in practice145 // as it will only visit proxies, and only do key-based change detection for objects for146 // which it is not already know that they are changed (that is, only object for which no known key was changed)147 function markChanges() {148 // intentionally we process the proxies in reverse order;149 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore150 // reverse order of proxy creation approximates this151 for (let i = states.length - 1; i >= 0; i--) {152 const state = states[i]153 if (state.modified === false) {154 if (Array.isArray(state.base)) {155 if (hasArrayChanges(state)) markChanged(state)156 } else if (hasObjectChanges(state)) markChanged(state)157 }158 }159 }160161 function hasObjectChanges(state) {162 const baseKeys = Object.keys(state.base)163 const keys = Object.keys(state.proxy)164 return !shallowEqual(baseKeys, keys)165 }166167 function hasArrayChanges(state) {168 return state.proxy.length !== state.base.length169 }170171 function finalize(proxy) {172 // TODO: almost litterally same as Proxy impl; let's reduce code duplication and rollup173 if (isProxy(proxy)) {174 const state = proxy[PROXY_STATE]175 if (state.modified === true) {176 if (Array.isArray(state.base))177 return finalizeArray(proxy, state)178 return finalizeObject(proxy, state)179 } else return state.base180 } else if (proxy !== null && typeof proxy === "object") {181 // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original182 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well183 if (Array.isArray(proxy)) {184 for (let i = 0; i < proxy.length; i++)185 proxy[i] = finalize(proxy[i])186 return freeze(proxy)187 }188 const proto = Object.getPrototypeOf(proxy)189 if (proto === null || proto === Object.prototype) {190 for (let key in proxy) proxy[key] = finalize(proxy[key])191 return freeze(proxy)192 }193 }194 return proxy195 }196197 function finalizeObject(proxy, state) {198 const res = Object.assign({}, proxy)199 const base = state.base200 for (let prop in res) {201 if (proxy[prop] !== base[prop]) res[prop] = finalize(res[prop])202 }203 return freeze(res)204 }205206 function finalizeArray(proxy, state) {207 const res = proxy.slice()208 const base = state.base209 for (let i = 0; i < res.length; i++) {210 if (res[i] !== base[i]) res[i] = finalize(res[i])211 }212 return freeze(res)213 }214215 // create proxy for root216 const rootClone = createProxy(undefined, baseState)217 // execute the thunk218 const maybeVoidReturn = producer(rootClone)219 //values either than undefined will trigger warning;220 !Object.is(maybeVoidReturn, undefined) &&221 console.warn(222 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`223 )224 // and finalize the modified proxy225 finalizing = true226 // find and mark all changes (for parts not done yet)227 markChanges()228 const res = finalize(rootClone)229 // make sure all proxies become unusable230 finished = true231 return res235}236237function isProxy(value) {238 return !!value && !!value[PROXY_STATE]
61 unmodified lines