es5.js
This file
Path
src/es5.js
296 lines · 9.7 KiB · JavaScript
Last changed by
classless es5 implMichel Weststratebefore adoptionb7cd045
History of this fileTake it
transpile es5 codeMichel Weststratebefore adoptionf012154
lines 1–17why, one step back1"use strict"2// @ts-check34const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version56let autoFreeze = true78/**9 * Immer takes a state, and runs a function against it.10 * That function can freely mutate the state, as it will create copies-on-write.11 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned12 *13 * @export14 * @param {any} baseState - the state to start with15 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified16 * @returns {any} a new state, or the base state if nothing was modified17 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 18why, one step back18export default function produce(baseState, producer) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 19–44why, one step back19 // curried invocation20 if (arguments.length === 1) {21 const producer = baseState22 // prettier-ignore23 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")24 return function() {25 const args = arguments26 return produce(args[0], draft => {27 args[0] = draft // blegh!28 baseState.apply(null, args)29 })30 }31 }3233 // prettier-ignore34 {35 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)36 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))37 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")38 }3940 let finalizing = false41 let finished = false42 const descriptors = {}43 const states = []44classless es5 implMichel Weststratebefore adoptionb7cd045
lines 45–52why, one step back45 function createState(parent, proxy, base) {46 return {47 modified: false,48 hasCopy: false,49 parent,50 base,51 proxy,52 copy: undefinedtranspile es5 codeMichel Weststratebefore adoptionf012154
line 53why, one step back53 }classless es5 implMichel Weststratebefore adoptionb7cd045
line 54why, one step back54 }transpile es5 codeMichel Weststratebefore adoptionf012154
line 55why, one step back55classless es5 implMichel Weststratebefore adoptionb7cd045
lines 56–58why, one step back56 function source(state) {57 return state.hasCopy ? state.copy : state.base58 }transpile es5 codeMichel Weststratebefore adoptionf012154
line 59why, one step back59classless es5 implMichel Weststratebefore adoptionb7cd045
lines 60–65why, one step back60 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))transpile es5 codeMichel Weststratebefore adoptionf012154
line 66why, one step back66 }classless es5 implMichel Weststratebefore adoptionb7cd045
lines 67–68why, one step back67 return value68 }transpile es5 codeMichel Weststratebefore adoptionf012154
line 69why, one step back69classless es5 implMichel Weststratebefore adoptionb7cd045
lines 70–74why, one step back70 function set(state, prop, value) {71 assertUnfinished()72 if (!state.modified) {73 if (Object.is(source(state)[prop], value)) return74 markChanged(state)transpile es5 codeMichel Weststratebefore adoptionf012154
line 75why, one step back75 }classless es5 implMichel Weststratebefore adoptionb7cd045
lines 76–78why, one step back76 prepareCopy(state)77 state.copy[prop] = value78 }transpile es5 codeMichel Weststratebefore adoptionf012154
line 79why, one step back79classless es5 implMichel Weststratebefore adoptionb7cd045
lines 80–83why, one step back80 function markChanged(state) {81 if (!state.modified) {82 state.modified = true83 if (state.parent) markChanged(state.parent)transpile es5 codeMichel Weststratebefore adoptionf012154
line 84why, one step back84 }classless es5 implMichel Weststratebefore adoptionb7cd045
line 85why, one step back85 }transpile es5 codeMichel Weststratebefore adoptionf012154
line 86why, one step back86classless es5 implMichel Weststratebefore adoptionb7cd045
lines 87–92why, one step back87 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)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 93–99why, one step back93 }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)classless es5 implMichel Weststratebefore adoptionb7cd045
line 100why, one step back100 const state = createState(parent, proxy, base)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 101–112why, one step back101 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() {classless es5 implMichel Weststratebefore adoptionb7cd045
line 113why, one step back113 return get(this[PROXY_STATE], prop)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 114–115why, one step back114 },115 set(value) {classless es5 implMichel Weststratebefore adoptionb7cd045
line 116why, one step back116 set(this[PROXY_STATE], prop, value)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 117–154why, one step back117 }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?"141 )142 }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)) {classless es5 implMichel Weststratebefore adoptionb7cd045
lines 155–156why, one step back155 if (hasArrayChanges(state)) markChanged(state)156 } else if (hasObjectChanges(state)) markChanged(state)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 157–171why, one step back157 }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) {Fixed es5 implementationMichel Weststratebefore adoption931e18a
lines 172–194why, one step back172 // 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 proxytranspile es5 codeMichel Weststratebefore adoptionf012154
lines 195–196why, one step back195 }196Fixed es5 implementationMichel Weststratebefore adoption931e18a
line 197why, one step back197 function finalizeObject(proxy, state) {transpile es5 codeMichel Weststratebefore adoptionf012154
line 198why, one step back198 const res = Object.assign({}, proxy)Fixed es5 implementationMichel Weststratebefore adoption931e18a
lines 199–202why, one step back199 const base = state.base200 for (let prop in res) {201 if (proxy[prop] !== base[prop]) res[prop] = finalize(res[prop])202 }transpile es5 codeMichel Weststratebefore adoptionf012154
lines 203–205why, one step back203 return freeze(res)204 }205Fixed es5 implementationMichel Weststratebefore adoption931e18a
lines 206–212why, one step back206 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)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 213–242why, one step back213 }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 res232}233234function isProxy(value) {235 return !!value && !!value[PROXY_STATE]236}237238function isProxyable(value) {239 if (!value) return false240 if (typeof value !== "object") return false241 if (Array.isArray(value)) return true242 const proto = Object.getPrototypeOf(value)Fixed es5 implementationMichel Weststratebefore adoption931e18a
line 243why, one step back243 return proto === null || proto === Object.prototypetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 244–293why, one step back244}245246function freeze(value) {247 if (autoFreeze) {248 Object.freeze(value)249 }250 return value251}252253function createHiddenProperty(target, prop, value) {254 Object.defineProperty(target, prop, {255 value: value,256 enumerable: false,257 writable: true258 })259}260261function shallowEqual(objA, objB) {262 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js263 if (Object.is(objA, objB)) return true264 if (265 typeof objA !== "object" ||266 objA === null ||267 typeof objB !== "object" ||268 objB === null269 ) {270 return false271 }272 const keysA = Object.keys(objA)273 const keysB = Object.keys(objB)274 if (keysA.length !== keysB.length) return false275 for (let i = 0; i < keysA.length; i++) {276 if (277 !hasOwnProperty.call(objB, keysA[i]) ||278 !Object.is(objA[keysA[i]], objB[keysA[i]])279 ) {280 return false281 }282 }283 return true284}285286/**287 * Automatically freezes any state trees generated by immer.288 * This protects against accidental modifications of the state tree outside of an immer function.289 * This comes with a performance impact, so it is recommended to disable this option in production.290 * It is by default enabled.291 *292 * @returns {void}293 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 294why, one step back294export function setAutoFreeze(enableAutoFreeze) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 295–296why, one step back295 autoFreeze = enableAutoFreeze296}