extracted class methods from Proxy impl
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 75de7af · Browse files · 1 file·+165 added−160 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+165 added−160 removed
- other:+165 added−160 removed
Provenance
- Commit
d20adea- Tree
d01a539- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
75de7af
1 file changed+165 added−160 removed
modified:src/immer.js+165 added-160 removed
6 unmodified lines7 )8 9 const PROXY_STATE = Symbol("immer-proxy-state")10 let autoFreeze = true11+let revocableProxies = null12 13 const objectTraps = {14 get(target, prop) {15 if (prop === PROXY_STATE) return target15- return target.get(prop)16+ return get(target, prop)17 },18 has(target, prop) {18- return prop in target.source19+ return prop in source(target)20 },21 ownKeys(target) {21- return Reflect.ownKeys(target.source)22+ return Reflect.ownKeys(source(target))23 },24 set(target, prop, value) {24- target.set(prop, value)25+ set(target, prop, value) // TODO: eliminate these closures26 return true27 },28 deleteProperty(target, prop) {28- target.deleteProp(prop)29+ deleteProp(target, prop) // TODO: eliminate these closures30 return true31 },32 getOwnPropertyDescriptor(target, prop) {32- return target.getOwnPropertyDescriptor(prop)33+ return getOwnPropertyDescriptor(target, prop)34 },35 defineProperty(target, property, descriptor) {35- target.defineProperty(property, descriptor)36+ defineProperty(target, property, descriptor)37 },38 setPrototypeOf() {39 throw new Error("Don't even try this...")40 }1 unmodified line42 43 const arrayTraps = {44 get(target, prop) {45 if (prop === PROXY_STATE) return target[0]45- return target[0].get(prop)46+ return get(target[0], prop)47 },48 has(target, prop) {48- return prop === PROXY_STATE || prop in target[0].source49+ return prop === PROXY_STATE || prop in source(target[0])50 },51 ownKeys(target) {51- return Reflect.ownKeys(target[0].source)52+ return Reflect.ownKeys(source(target[0]))53 },54 set(target, prop, value) {54- target[0].set(prop, value)55+ set(target[0], prop, value)56 return true57 },58 deleteProperty(target, prop) {58- target[0].deleteProp(prop)59+ deleteProp(target[0], prop)60 return true61 },62 getOwnPropertyDescriptor(target, prop) {62- return target[0].getOwnPropertyDescriptor(prop)63+ return getOwnPropertyDescriptor(target[0], prop)64 },65 defineProperty(target, property, descriptor) {65- target[0].defineProperty(property, descriptor)66+ defineProperty(target[0], property, descriptor)67 },68 setPrototypeOf() {69 throw new Error("Don't even try this...")70 }71 }72 73+class State {74+ constructor(parent, base) {75+ this.modified = false76+ this.finalized = false77+ this.parent = parent78+ this.base = base79+ this.copy = undefined80+ this.proxies = {}81+ }82+}83+84+function source(state) {85+ return state.modified === true ? state.copy : state.base86+}87+88+function get(state, prop) {89+ if (state.modified) {90+ const value = state.copy[prop]91+ if (!isProxy(value) && isProxyable(value))92+ return (state.copy[prop] = createProxy(state, value))93+ return value94+ } else {95+ if (prop in state.proxies) return state.proxies[prop]96+ const value = state.base[prop]97+ if (!isProxy(value) && isProxyable(value))98+ return (state.proxies[prop] = createProxy(state, value))99+ return value100+ }101+}102+103+function set(state, prop, value) {104+ if (!state.modified) {105+ if (106+ (prop in state.base && Object.is(state.base[prop], value)) ||107+ (prop in state.proxies && state.proxies[prop] === value)108+ )109+ return110+ markChanged(state)111+ }112+ state.copy[prop] = value113+}114+115+function deleteProp(state, prop) {116+ markChanged(state)117+ delete state.copy[prop]118+}119+120+function getOwnPropertyDescriptor(state, prop) {121+ const owner = state.modified122+ ? state.copy123+ : prop in state.proxies ? state.proxies : state.base124+ const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)125+ if (descriptor && !(Array.isArray(owner) && prop === "length"))126+ descriptor.configurable = true127+ return descriptor128+}129+130+function defineProperty() {131+ throw new Error(132+ "Immer does currently not support defining properties on draft objects"133+ )134+}135+136+function markChanged(state) {137+ if (!state.modified) {138+ state.modified = true139+ state.copy = Array.isArray(state.base)140+ ? state.base.slice()141+ : Object.assign({}, state.base) // TODO: eliminate those isArray checks?142+ Object.assign(state.copy, state.proxies) // yup that works for arrays as well143+ if (state.parent) markChanged(state.parent)144+ }145+}146+147+// creates a proxy for plain objects / arrays148+function createProxy(parentState, base) {149+ const state = new State(parentState, base)150+ let proxy151+ if (Array.isArray(base)) {152+ proxy = Proxy.revocable([state], arrayTraps)153+ } else {154+ proxy = Proxy.revocable(state, objectTraps)155+ }156+ revocableProxies.push(proxy)157+ return proxy.proxy158+}159+160+// given a base object, returns it if unmodified, or return the changed cloned if modified161+function finalize(base) {162+ if (isProxy(base)) {163+ const state = base[PROXY_STATE]164+ if (state.modified === true) {165+ if (state.finalized === true) return state.copy166+ state.finalized = true167+ if (Array.isArray(state.base)) return finalizeArray(state)168+ return finalizeObject(state)169+ } else return state.base170+ } else if (base !== null && typeof base === "object") {171+ // 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 original172+ // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well173+ // TODO: optimize this; walk the tree without writing to find proxies174+ if (Array.isArray(base)) {175+ for (let i = 0; i < base.length; i++) base[i] = finalize(base[i])176+ return freeze(base)177+ }178+ const proto = Object.getPrototypeOf(base)179+ if (proto === null || proto === Object.prototype) {180+ for (let key in base) base[key] = finalize(base[key])181+ return freeze(base)182+ }183+ }184+ return base185+}186+187+function finalizeObject(state) {188+ const copy = state.copy189+ const base = state.base190+ for (var prop in copy) {191+ if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])192+ }193+ return freeze(copy)194+}195+196+function finalizeArray(state) {197+ const copy = state.copy198+ const base = state.base199+ for (let i = 0; i < copy.length; i++) {200+ if (copy[i] !== base[i]) copy[i] = finalize(copy[i])201+ }202+ return freeze(copy)203+}204+205 /**206 * produce takes a state, and runs a function against it.207 * That function can freely mutate the state, as it will create copies-on-write.208 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned23 unmodified lines232 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)233 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))234 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")235 }103- const revocableProxies = []236 105- class State {106- constructor(parent, base) {107- this.modified = false108- this.finalized = false109- this.parent = parent110- this.base = base111- this.copy = undefined112- this.proxies = {}113- }114-115- get source() {116- return this.modified === true ? this.copy : this.base117- }118-119- get(prop) {120- if (this.modified) {121- const value = this.copy[prop]122- if (!isProxy(value) && isProxyable(value))123- return (this.copy[prop] = createProxy(this, value))124- return value125- } else {126- if (prop in this.proxies) return this.proxies[prop]127- const value = this.base[prop]128- if (!isProxy(value) && isProxyable(value))129- return (this.proxies[prop] = createProxy(this, value))130- return value131- }132- }133-134- set(prop, value) {135- if (!this.modified) {136- if (137- (prop in this.base && Object.is(this.base[prop], value)) ||138- (prop in this.proxies && this.proxies[prop] === value)139- )140- return141- this.markChanged()142- }143- this.copy[prop] = value144- }145-146- deleteProp(prop) {147- this.markChanged()148- delete this.copy[prop]149- }150-151- getOwnPropertyDescriptor(prop) {152- const owner = this.modified153- ? this.copy154- : prop in this.proxies ? this.proxies : this.base155- const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)156- if (descriptor && !(Array.isArray(owner) && prop === "length"))157- descriptor.configurable = true158- return descriptor159- }160-161- defineProperty(property, descriptor) {162- throw new Error(163- "Immer does currently not support defining properties on draft objects"237+ const previousProxies = revocableProxies238+ revocableProxies = []239+ try {240+ // create proxy for root241+ const rootClone = createProxy(undefined, baseState)242+ // execute the thunk243+ const maybeVoidReturn = producer(rootClone)244+ //values either than undefined will trigger warning;245+ !Object.is(maybeVoidReturn, undefined) &&246+ console.warn(247+ `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`248 )165- }166-167- markChanged() {168- if (!this.modified) {169- this.modified = true170- this.copy = Array.isArray(this.base)171- ? this.base.slice()172- : Object.assign({}, this.base) // TODO: eliminate those isArray checks?173- Object.assign(this.copy, this.proxies) // yup that works for arrays as well174- if (this.parent) this.parent.markChanged()175- }176- }249+ // and finalize the modified proxy250+ const res = finalize(rootClone)251+ // revoke all proxies252+ revocableProxies.forEach(p => p.revoke())253+ return res254+ } finally {255+ revocableProxies = previousProxies256 }178-179- // creates a proxy for plain objects / arrays180- function createProxy(parentState, base) {181- const state = new State(parentState, base)182- let proxy183- if (Array.isArray(base)) {184- proxy = Proxy.revocable([state], arrayTraps)185- } else {186- proxy = Proxy.revocable(state, objectTraps)187- }188- revocableProxies.push(proxy)189- return proxy.proxy190- }191-192- // given a base object, returns it if unmodified, or return the changed cloned if modified193- function finalize(base) {194- if (isProxy(base)) {195- const state = base[PROXY_STATE]196- if (state.modified === true) {197- if (state.finalized === true) return state.copy198- state.finalized = true199- if (Array.isArray(state.base)) return finalizeArray(state)200- return finalizeObject(state)201- } else return state.base202- } else if (base !== null && typeof base === "object") {203- // 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 original204- // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well205- // TODO: optimize this; walk the tree without writing to find proxies206- if (Array.isArray(base)) {207- for (let i = 0; i < base.length; i++)208- base[i] = finalize(base[i])209- return freeze(base)210- }211- const proto = Object.getPrototypeOf(base)212- if (proto === null || proto === Object.prototype) {213- for (let key in base) base[key] = finalize(base[key])214- return freeze(base)215- }216- }217- return base218- }219-220- function finalizeObject(state) {221- const copy = state.copy222- const base = state.base223- for (var prop in copy) {224- if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])225- }226- return freeze(copy)227- }228-229- function finalizeArray(state) {230- const copy = state.copy231- const base = state.base232- for (let i = 0; i < copy.length; i++) {233- if (copy[i] !== base[i]) copy[i] = finalize(copy[i])234- }235- return freeze(copy)236- }237-238- // create proxy for root239- const rootClone = createProxy(undefined, baseState)240- // execute the thunk241- const maybeVoidReturn = producer(rootClone)242- //values either than undefined will trigger warning;243- !Object.is(maybeVoidReturn, undefined) &&244- console.warn(245- `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`246- )247- // and finalize the modified proxy248- const res = finalize(rootClone)249- // revoke all proxies250- revocableProxies.forEach(p => p.revoke())251- return res257 }258 259 function isProxy(value) {260 return !!value && !!value[PROXY_STATE]32 unmodified lines