immer.js
This file
Path
src/immer.js
260 lines · 8.1 KiB · JavaScript
Last changed by
classlessMichel Weststratebefore adoption388f4f1
History of this fileTake it
transpile es5 codeMichel Weststratebefore adoptionf012154
lines 1–8why, one step back1"use strict"2// @ts-check34if (typeof Proxy === "undefined")5 throw new Error(6 "Immer requires `Proxy` to be available, but it seems to be not available on your platform. Consider requiring immer '\"immer/es5\"' instead."7 )8Making several improvements at onceMichel Weststratebefore adoption1116ccf
line 9why, one step back9const PROXY_STATE = Symbol("immer-proxy-state")transpile es5 codeMichel Weststratebefore adoptionf012154
line 10why, one step back10let autoFreeze = trueextracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
line 11why, one step back11let revocableProxies = nulltranspile es5 codeMichel Weststratebefore adoptionf012154
lines 12–13why, one step back1213const objectTraps = {leaner implementationMichel Weststratebefore adoption7b13028
line 14why, one step back14 get,transpile es5 codeMichel Weststratebefore adoptionf012154
line 15why, one step back15 has(target, prop) {extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
line 16why, one step back16 return prop in source(target)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 17–18why, one step back17 },18 ownKeys(target) {extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
line 19why, one step back19 return Reflect.ownKeys(source(target))transpile es5 codeMichel Weststratebefore adoptionf012154
line 20why, one step back20 },leaner implementationMichel Weststratebefore adoption7b13028
lines 21–24why, one step back21 set,22 deleteProperty,23 getOwnPropertyDescriptor,24 defineProperty,transpile es5 codeMichel Weststratebefore adoptionf012154
lines 25–29why, one step back25 setPrototypeOf() {26 throw new Error("Don't even try this...")27 }28}29leaner implementationMichel Weststratebefore adoption7b13028
lines 30–34why, one step back30const arrayTraps = {}31for (let key in objectTraps) {32 arrayTraps[key] = function() {33 arguments[0] = arguments[0][0]34 return objectTraps[key].apply(this, arguments)transpile es5 codeMichel Weststratebefore adoptionf012154
lines 35–37why, one step back35 }36}37classlessMichel Weststratebefore adoption388f4f1
lines 38–45why, one step back38function createState(parent, base) {39 return {40 modified: false,41 finalized: false,42 parent,43 base,44 copy: undefined,45 proxies: {}extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 46–53why, one step back46 }47}4849function source(state) {50 return state.modified === true ? state.copy : state.base51}5253function get(state, prop) {leaner implementationMichel Weststratebefore adoption7b13028
line 54why, one step back54 if (prop === PROXY_STATE) return stateextracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 55–74why, one step back55 if (state.modified) {56 const value = state.copy[prop]57 if (!isProxy(value) && isProxyable(value))58 return (state.copy[prop] = createProxy(state, value))59 return value60 } else {61 if (prop in state.proxies) return state.proxies[prop]62 const value = state.base[prop]63 if (!isProxy(value) && isProxyable(value))64 return (state.proxies[prop] = createProxy(state, value))65 return value66 }67}6869function set(state, prop, value) {70 if (!state.modified) {71 if (72 (prop in state.base && Object.is(state.base[prop], value)) ||73 (prop in state.proxies && state.proxies[prop] === value)74 )leaner implementationMichel Weststratebefore adoption7b13028
line 75why, one step back75 return trueextracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 76–78why, one step back76 markChanged(state)77 }78 state.copy[prop] = valueleaner implementationMichel Weststratebefore adoption7b13028
line 79why, one step back79 return trueextracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 80–81why, one step back80}81leaner implementationMichel Weststratebefore adoption7b13028
line 82why, one step back82function deleteProperty(state, prop) {extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 83–84why, one step back83 markChanged(state)84 delete state.copy[prop]leaner implementationMichel Weststratebefore adoption7b13028
line 85why, one step back85 return trueextracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 86–116why, one step back86}8788function getOwnPropertyDescriptor(state, prop) {89 const owner = state.modified90 ? state.copy91 : prop in state.proxies ? state.proxies : state.base92 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)93 if (descriptor && !(Array.isArray(owner) && prop === "length"))94 descriptor.configurable = true95 return descriptor96}9798function defineProperty() {99 throw new Error(100 "Immer does currently not support defining properties on draft objects"101 )102}103104function markChanged(state) {105 if (!state.modified) {106 state.modified = true107 state.copy = Array.isArray(state.base)108 ? state.base.slice()109 : Object.assign({}, state.base) // TODO: eliminate those isArray checks?110 Object.assign(state.copy, state.proxies) // yup that works for arrays as well111 if (state.parent) markChanged(state.parent)112 }113}114115// creates a proxy for plain objects / arrays116function createProxy(parentState, base) {classlessMichel Weststratebefore adoption388f4f1
line 117why, one step back117 const state = createState(parentState, base)extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 118–172why, one step back118 let proxy119 if (Array.isArray(base)) {120 proxy = Proxy.revocable([state], arrayTraps)121 } else {122 proxy = Proxy.revocable(state, objectTraps)123 }124 revocableProxies.push(proxy)125 return proxy.proxy126}127128// given a base object, returns it if unmodified, or return the changed cloned if modified129function finalize(base) {130 if (isProxy(base)) {131 const state = base[PROXY_STATE]132 if (state.modified === true) {133 if (state.finalized === true) return state.copy134 state.finalized = true135 if (Array.isArray(state.base)) return finalizeArray(state)136 return finalizeObject(state)137 } else return state.base138 } else if (base !== null && typeof base === "object") {139 // 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 original140 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well141 // TODO: optimize this; walk the tree without writing to find proxies142 if (Array.isArray(base)) {143 for (let i = 0; i < base.length; i++) base[i] = finalize(base[i])144 return freeze(base)145 }146 const proto = Object.getPrototypeOf(base)147 if (proto === null || proto === Object.prototype) {148 for (let key in base) base[key] = finalize(base[key])149 return freeze(base)150 }151 }152 return base153}154155function finalizeObject(state) {156 const copy = state.copy157 const base = state.base158 for (var prop in copy) {159 if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])160 }161 return freeze(copy)162}163164function finalizeArray(state) {165 const copy = state.copy166 const base = state.base167 for (let i = 0; i < copy.length; i++) {168 if (copy[i] !== base[i]) copy[i] = finalize(copy[i])169 }170 return freeze(copy)171}172transpile es5 codeMichel Weststratebefore adoptionf012154
lines 173–182why, one step back173/**174 * produce takes a state, and runs a function against it.175 * That function can freely mutate the state, as it will create copies-on-write.176 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned177 *178 * @export179 * @param {any} baseState - the state to start with180 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified181 * @returns {any} a new state, or the base state if nothing was modified182 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 183why, one step back183export default function produce(baseState, producer) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 184–204why, one step back184 // curried invocation185 if (arguments.length === 1) {186 const producer = baseState187 // prettier-ignore188 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")189 return function() {190 const args = arguments191 return produce(args[0], draft => {192 args[0] = draft // blegh!193 baseState.apply(null, args)194 })195 }196 }197198 // prettier-ignore199 {200 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)201 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))202 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")203 }204extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 205–215why, one step back205 const previousProxies = revocableProxies206 revocableProxies = []207 try {208 // create proxy for root209 const rootClone = createProxy(undefined, baseState)210 // execute the thunk211 const maybeVoidReturn = producer(rootClone)212 //values either than undefined will trigger warning;213 !Object.is(maybeVoidReturn, undefined) &&214 console.warn(215 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`transpile es5 codeMichel Weststratebefore adoptionf012154
line 216why, one step back216 )extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea
lines 217–223why, one step back217 // and finalize the modified proxy218 const res = finalize(rootClone)219 // revoke all proxies220 revocableProxies.forEach(p => p.revoke())221 return res222 } finally {223 revocableProxies = previousProxiestranspile es5 codeMichel Weststratebefore adoptionf012154
lines 224–235why, one step back224 }225}226227function isProxy(value) {228 return !!value && !!value[PROXY_STATE]229}230231function isProxyable(value) {232 if (!value) return false233 if (typeof value !== "object") return false234 if (Array.isArray(value)) return true235 const proto = Object.getPrototypeOf(value)initial solutionMichel Weststratebefore adoptiond618d28
line 236why, one step back236 return proto === null || proto === Object.prototypetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 237–257why, one step back237}238239function freeze(value) {240 // short circuit to achieve 100% code coverage instead of 98%241 /*242 if(autoFreeze) {243 Object.freeze(value)244 }245 * */246 autoFreeze && Object.freeze(value)247 return value248}249250/**251 * Automatically freezes any state trees generated by immer.252 * This protects against accidental modifications of the state tree outside of an immer function.253 * This comes with a performance impact, so it is recommended to disable this option in production.254 * It is by default enabled.255 *256 * @returns {void}257 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 258why, one step back258export function setAutoFreeze(enableAutoFreeze) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 259–260why, one step back259 autoFreeze = enableAutoFreeze260}