Cleaner ES5 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 fbeeade · Browse files · 1 file·+92 added−95 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+92 added−95 removed
- other:+92 added−95 removed
Provenance
- Commit
ef94110- Tree
2c41844- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
fbeeade
1 file changed+92 added−95 removed
modified:es5.js+92 added-95 removed
1 "use strict"2 // @ts-check3 4-const PROXY_TARGET = Symbol("immer-proxy")5-const CHANGED_STATE = Symbol("immer-changed-state")6-const PARENT = Symbol("immer-parent")4+const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version5 6 let autoFreeze = true7 8 /**9 unmodified lines18 function immer(baseState, thunk) {19 let finalizing = false20 let finished = false21 const descriptors = {}24- const proxies = []22+ const states = []23 24+ class State {25+ constructor(parent, proxy, base) {26+ this.modified = false27+ this.hasCopy = false28+ this.parent = parent29+ this.base = base30+ this.proxy = proxy31+ this.copy = undefined32+ }33+34+ get source() {35+ return this.hasCopy ? this.copy : this.base36+ }37+38+ get(prop) {39+ assertUnfinished()40+ const value = this.source[prop]41+ if (!finalizing && !isProxy(value) && isProxyable(value)) {42+ this.prepareCopy()43+ return (this.copy[prop] = createProxy(this, value))44+ }45+ return value46+ }47+48+ set(prop, value) {49+ assertUnfinished()50+ if (!this.modified) {51+ if (this.source[prop] === value) return52+ this.markChanged()53+ }54+ this.prepareCopy()55+ this.copy[prop] = value56+ }57+58+ markChanged() {59+ if (!this.modified) {60+ this.modified = true61+ if (this.parent) this.parent.markChanged()62+ }63+ }64+65+ prepareCopy() {66+ if (this.hasCopy) return67+ this.hasCopy = true68+ this.copy = Array.isArray(this.base)69+ ? this.base.slice()70+ : Object.assign({}, this.base)71+ }72+ }73+74 // creates a proxy for plain objects / arrays27- function createProxy(base, parent) {75+ function createProxy(parent, base) {76 let proxy29- if (isPlainObject(base)) proxy = createObjectProxy(base)30- else if (Array.isArray(base)) proxy = createArrayProxy(base)31- else throw new Error("Expected a plain object or array")32- createHiddenProperty(proxy, PROXY_TARGET, base)33- createHiddenProperty(proxy, CHANGED_STATE, false)34- createHiddenProperty(proxy, PARENT, parent)35- proxies.push(proxy)77+ if (Array.isArray(base)) proxy = createArrayProxy(base)78+ else proxy = createObjectProxy(base)79+ const state = new State(parent, proxy, base)80+ createHiddenProperty(proxy, PROXY_STATE, state)81+ states.push(state)82 return proxy83 }84 39- function assertUnfinished() {40- if (finished)41- throw new Error(42- "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"43- )44- }45-46- function proxySet(proxy, prop, value) {47- // immer func not ended?48- assertUnfinished()49- // actually a change?50- if (Object.is(proxy[prop], value)) return51- // mark changed52- markDirty(proxy)53- // and stop proxying, we know this object has changed54- Object.defineProperty(proxy, prop, {55- enumerable: true,56- writable: true,57- configurable: true,58- value: value59- })60- }61-85 function createPropertyProxy(prop) {86 return (87 descriptors[prop] ||88 (descriptors[prop] = {89 configurable: true,90 enumerable: true,91 get() {69- assertUnfinished()70- // find the target object71- const target = this[PROXY_TARGET]72- // find the original value73- const value = target[prop]74- // if we are finalizing, don't bother creating proxies, just return base value75- if (finalizing) return value76- // if not proxy-able, return value77- if (!isPlainObject(value) && !Array.isArray(value))78- return value79- // otherwise, create proxy80- const proxy = createProxy(value, this)81- // and make sure this proxy is returned from this prop in the future if read82- // (write behavior as is)83- Object.defineProperty(this, prop, {84- configurable: true,85- enumerable: true,86- get() {87- return proxy88- },89- set(value) {90- proxySet(this, prop, value)91- }92- })93- return proxy92+ return this[PROXY_STATE].get(prop)93 },94 set(value) {96- proxySet(this, prop, value)95+ this[PROXY_STATE].set(prop, value)96 }97 })98 )99 }12 unmodified lines112 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))113 return proxy114 }115 116+ function assertUnfinished() {117+ if (finished)118+ throw new Error(119+ "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"120+ )121+ }122+123 // this sounds very expensive, but actually it is not that extensive in practice124 // as it will only visit proxies, and only do key-based change detection for objects for125 // which it is not already know that they are changed (that is, only object for which no known key was changed)126 function markChanges() {127 // intentionally we process the proxies in reverse order;128 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore129 // reverse order of proxy creation approximates this124- for (let i = proxies.length - 1; i >= 0; i--) {125- const proxy = proxies[i]126- if (127- proxy[CHANGED_STATE] === false &&128- ((isPlainObject(proxy) && hasObjectChanges(proxy)) ||129- (Array.isArray(proxy) && hasArrayChanges(proxy)))130- ) {131- markDirty(proxy)130+ for (let i = states.length - 1; i >= 0; i--) {131+ const state = states[i]132+ if (state.modified === false) {133+ if (Array.isArray(state.base)) {134+ if (hasArrayChanges(state)) state.markChanged()135+ } else if (hasObjectChanges(state)) state.markChanged()136 }137 }138 }139 136- function hasObjectChanges(proxy) {137- const baseKeys = Object.keys(proxy[PROXY_TARGET])138- const keys = Object.keys(proxy)140+ function hasObjectChanges(state) {141+ const baseKeys = Object.keys(state.base)142+ const keys = Object.keys(state.proxy)143 return !shallowEqual(baseKeys, keys)144 }145 142- function hasArrayChanges(proxy) {143- return proxy[PROXY_TARGET].length !== proxy.length146+ function hasArrayChanges(state) {147+ return state.proxy.length !== state.base.length148 }149 150 function finalize(proxy) {151 // given a base object, returns it if unmodified, or return the changed cloned if modified152 if (!isProxy(proxy)) return proxy149- if (!proxy[CHANGED_STATE]) return proxy[PROXY_TARGET] // return the original target150- if (isPlainObject(proxy)) return finalizeObject(proxy)153+ const state = proxy[PROXY_STATE]154+ if (state.modified === false) return state.base // return the original target155 if (Array.isArray(proxy)) return finalizeArray(proxy)152- throw new Error("Illegal state")156+ return finalizeObject(proxy)157 }158 159 function finalizeObject(proxy) {156- const res = {}157- Object.keys(proxy).forEach(prop => {158- res[prop] = finalize(proxy[prop])160+ const res = Object.assign({}, proxy)161+ Object.keys(res).forEach(prop => {162+ res[prop] = finalize(res[prop])163 })164 return freeze(res)165 }166 1 unmodified line168 return freeze(proxy.map(finalize))169 }170 171 // create proxy for root168- const rootClone = createProxy(baseState, undefined)172+ const rootClone = createProxy(undefined, baseState)173 // execute the thunk174 const maybeVoidReturn = thunk(rootClone)175 //values either than undefined will trigger warning;176 !Object.is(maybeVoidReturn, undefined) &&9 unmodified lines186 finished = true187 return res188 }189 186-function markDirty(proxy) {187- proxy[CHANGED_STATE] = true188- let parent = proxy189- while ((parent = parent[PARENT])) {190- if (parent[CHANGED_STATE] === true) return191- parent[CHANGED_STATE] = true192- }190+function isProxy(value) {191+ return !!value && !!value[PROXY_STATE]192 }193 195-function isPlainObject(value) {196- if (value === null || typeof value !== "object") return false194+function isProxyable(value) {195+ if (!value) return false196+ if (typeof value !== "object") return false197+ if (Array.isArray(value)) return true198 const proto = Object.getPrototypeOf(value)198- return proto === Object.prototype || proto === null199+ return (proto === proto) === null || Object.prototype200 }201 201-function isProxy(value) {202- return !!(value && value[PROXY_TARGET])203-}204-202 function freeze(value) {203 if (autoFreeze) {204 Object.freeze(value)205 }51 unmodified lines